HackerRank Strong Password Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Strong Password Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

Strong Password Solution
Strong Password Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Strong Password

Task

Louise joined a social networking site to stay in touch with her friends. The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria:

  • Its length is at least 6.
  • It contains at least one digit.
  • It contains at least one lowercase English character.
  • It contains at least one uppercase English character.
  • It contains at least one special character. The special characters are: [email protected]#$%^&*()-+

She typed a random string of length n in the password field but wasn’t sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong?

Note: Here’s the set of types of characters in a form you can paste in your solution:

numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "[email protected]#$%^&*()-+"

Example

password = ‘2bbbb’

This password is 5 characters long and is missing an uppercase and a special character. The minimum number of characters to add is 2.

password = ‘2bb#A’

Function Description

Complete the minimumNumber function in the editor below.

minimumNumber has the following parameters:

  • int n: the length of the password
  • string password: the password to test

Returns

  • int: the minimum number of characters to add

Input Format

The first line contains an integer n, the length of the password.

The second line contains the password string. Each character is either a lowercase/uppercase English alphabet, a digit, or a special character.

Constraints

  • 1 <= n <= 100
  • All characters in password are in [a-z], [A-Z], [0-9], or [[email protected]#$%^&*()-+ ].

Sample Input 0

3
Ab1

Sample Output 0

3

Explanation 0

She can make the password strong by adding 3 characters, for example, $hk, turning the password into Ab1$hk which is strong.

2 characters aren’t enough since the length must be at least 6.

Sample Input 1

11
#HackerRank

Sample Output 1

1

Explanation 1

The password isn’t strong, but she can make it strong by adding a single digit.

HackerRank Strong Password Solution

Strong Password Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int minimumNumber(int n, char* password) {
    
    int L_c = 0;
    int U_c = 0;
    int no = 0;
    int s_c = 0;
    
    int len = strlen(password);
    int i;
    for(i = 0; i<n; i++)
    {
        if(password[i] >= 'a' && password[i] <= 'z')
            L_c++;
        else if(password[i] >= 'A' && password[i] <= 'Z')
            U_c++;
        else if(password[i] >= '0' && password[i] <= '9')
            no++;
        else
            s_c++;
    }
    
    int add = 0;
    if(L_c == 0)
        add++;
    if(U_c == 0)
        add++;
    if(no == 0)
        add++;
    if(s_c == 0)
        add++;
    
    len = len + add;
    
    if(len < 6)
        add = add + 6 - len;
    
    return add;
}

int main() {
    int n; 
    scanf("%i", &n);
    char* password = (char *)malloc(512000 * sizeof(char));
    scanf("%s", password);
    int answer = minimumNumber(n, password);
    printf("%d\n", answer);
    return 0;
}

Strong Password Solution in Cpp

#include <cstdio>
#include <cmath>
#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
#include <map>
#include <cassert>
#include <string>
#include <cstring>
#include <queue>

using namespace std;

#define rep(i,a,b) for(int i = a; i < b; i++)
#define S(x) scanf("%d",&x)
#define S2(x,y) scanf("%d%d",&x,&y)
#define P(x) printf("%d\n",x)
#define all(v) v.begin(),v.end()
#define FF first
#define SS second
#define pb push_back
#define mp make_pair

typedef long long int LL;
typedef pair<int, int > pii;
typedef vector<int > vi;

int X[4];

int main() {
  int n;
  S(n);
  string s;
  cin >> s;
  rep(i,0,n) {
    if(s[i] >= '0' && s[i] <= '9') X[0] = 1;
    else if(s[i] >= 'a' && s[i] <= 'z') X[1] = 1;
    else if(s[i] >= 'A' && s[i] <= 'Z') X[2] = 1;
    else X[3] = 1;
  }
  int ans = 4;
  rep(i,0,4) ans -= X[i];
  ans = max(ans, 6 - n);
  P(ans);
  return 0;
}

Strong Password Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int minimumNumber(int n, String password) {
        // Return the minimum number of characters to make the password strong
           int totalChar = password.length();  
        int upperCase = 0,count=0;  
        int lowerCase = 0;  
        int digits = 0;  
        int others = 0;  
        for (int i = 0; i < password.length(); i++) {  
            char ch = password.charAt(i);  
            if (Character.isUpperCase(ch)) {  
                upperCase++;  
            }  
            else if (Character.isLowerCase(ch)) {  
                lowerCase++;  
            }  
            else if (Character.isDigit(ch)) {  
                digits++;  
            }  
            else {  
                others++;  
            }  
        }  
            if(upperCase==0)
                count++;
              if(lowerCase==0)
                count++;
              if(digits==0)
                count++;
              if(others==0)
                count++;
         if(count+n<6)
        {
             count+=(6-count-n);
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String password = in.next();
        int answer = minimumNumber(n, password);
        System.out.println(answer);
        in.close();
    }
}

Strong Password Solution in Python

#!/bin/python

import sys

numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "[email protected]#$%^&*()-+"

def minimumNumber(n, password):
    add = 0
    if len(password) < 6:
        add = max(add, 6-len(password))
    digit = True
    lower = True
    upper = True
    special = True
    for c in password:
        if c in numbers:
            digit = False
        if c in lower_case:
            lower = False
        if c in upper_case:
            upper = False
        if c in special_characters:
            special = False
    needed = digit + lower + upper + special
    add = max(needed, add)
    return add

if __name__ == "__main__":
    n = int(raw_input().strip())
    password = raw_input().strip()
    answer = minimumNumber(n, password)
    print answer

Strong Password Solution using JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function minimumNumber(n, password) {
    const containsDigit = (password.match(/[0-9]/) || []).length > 0;
    const containsLower = (password.match(/[a-z]/) || []).length > 0;
    const containsUpper = (password.match(/[A-Z]/) || []).length > 0;
    const containsSpecial = (password.match(/[[email protected]#$%^&*\(\)\-+]/) || []).length > 0;
    const needChars = (!containsDigit + !containsLower + !containsUpper + !containsSpecial);
    const need2 = Math.max(0, 6 - password.length);
    return Math.max(0, need2, needChars);
}

function main() {
    var n = parseInt(readLine());
    var password = readLine();
    var answer = minimumNumber(n, password);
    process.stdout.write("" + answer + "\n");

}

Strong Password Solution in Scala

object Solution {
  val numbers = "0123456789".toSet
  val lower_case = "abcdefghijklmnopqrstuvwxyz".toSet
  val upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toSet
  val special_characters = "[email protected]#$%^&*()-+".toSet
  val classes = List(numbers, lower_case, upper_case, special_characters)
  def minimumNumber(n: Int, password: String): Int =  {
    val chars = password.toSet
    val missingClasses = classes.count(_.intersect(chars).size == 0)

    Math.max(6-password.size, missingClasses)
  }

  def main(args: Array[String]) {
    val sc = new java.util.Scanner (System.in);
    var n = sc.nextInt();
    var password = sc.next();
    val answer = minimumNumber(n, password);
    println(answer)
  }
}

Strong Password Solution in Pascal

{$mode objfpc}
uses math;

var
  i,n,kq:integer;
  o:char;
  f1,f2,f3,f4:boolean;

begin
  readln(n);
  for i:=1 to n do
    begin
      read(o);
      if ('0' <= o) and (o <= '9') then f1:=true
      else
      if ('a' <= o) and (o <= 'z') then f2:=true
      else
      if ('A' <= o) and (o <= 'Z') then f3:=true
      else
      f4:=true;
    end;
  if not f1 then inc(kq);
  if not f2 then inc(kq);
  if not f3 then inc(kq);
  if not f4 then inc(kq);
  write(max(kq , 6-n));
end.

Disclaimer: This problem (Strong Password) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment