Strong Password HackerRank Solution in C, C++, Java, Python

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: !@#$%^&*()-+

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 = “!@#$%^&*()-+”

 

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 .

Password = ‘2bb#A’

This password is 5 characters long and has at least one of each character type. The minimum number of characters to add is .

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 , 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 [!@#$%^&*()-+ ].

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.

 

Strong Password HackerRank 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 HackerRank Solution in C++

#include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------

int N;
string S;
int A[4]={1,1,1,1};

void solve() {
    int i,j,k,l,r,x,y; string s;
    
    cin>>N>>S;
    FORR(c,S) {
        if(c>='0' && c<='9') A[0]=0;
        else if(c>='a' && c<='z') A[1]=0;
        else if(c>='A' && c<='Z') A[2]=0;
        else A[3]=0;
    }
    
    int add=A[0]+A[1]+A[2]+A[3];
    int add2=max(0,6-N-add);
    cout<<add+add2<<endl;
    
}


int main(int argc,char** argv){
    string s;int i;
    if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
    FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
    cout.tie(0); solve(); return 0;
}

 

Strong Password HackerRank Solution in Java

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class A {
    InputStream is;
    PrintWriter out;
    String INPUT = "";
    
    void solve()
    {
        String numbers = "0123456789",
                lower_case = "abcdefghijklmnopqrstuvwxyz",
                upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                special_characters = "!@#$%^&*()-+";
        int n = ni();
        char[] s = ns(n);
        int need = 0;
        int x = 0;
        for(char c : s){
            if(numbers.indexOf(c) >= 0)x |= 1;
            if(lower_case.indexOf(c) >= 0)x |= 2;
            if(upper_case.indexOf(c) >= 0)x |= 4;
            if(special_characters.indexOf(c) >= 0)x |= 8;
        }
        need = 4-Integer.bitCount(x);
        out.println(Math.max(6-n, need));
    }
    
    void run() throws Exception
    {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        out = new PrintWriter(System.out);
        
        long s = System.currentTimeMillis();
        solve();
        out.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }
    
    public static void main(String[] args) throws Exception { new A().run(); }
    
    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;
    
    private int readByte()
    {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }
    
    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
    
    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }
    
    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    
    private char[] ns(int n)
    {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }
    
    private char[][] nm(int n, int m)
    {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }
    
    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }
    
    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
    
    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
    
    private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}

 

Strong Password HackerRank Solution in Python

INF = 999999999999999999L
EPS = 1e-12

def read():
    return raw_input().strip()

def read_ints():
    return map(int,read().split())
    
def contains(chars, word):
    for c in chars:
        if c in word:
            return True
    return False 

numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "!@#$%^&*()-+"

n = int(read())
word = read()

if n < 6:
    val1 = 6-n
else:
    val1 = 0
    
if not contains(numbers,word):
    val2 = 1 
else:
    val2 = 0 
if not contains(lower_case,word):
    val2 += 1 
if not contains(upper_case,word):
    val2 += 1 
if not contains(special_characters,word):
    val2 += 1 
    
print max(val1,val2)

 

Strong Password HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

    static int minimumNumber(int n, string password) {
        string numbers = "0123456789";
        string lower_case = "abcdefghijklmnopqrstuvwxyz";
        string upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string special_characters = "!@#$%^&*()-+";
        
        int count=0;
        if(!numbers.ToCharArray().Any(password.Contains))
            count++;
        if(!lower_case.ToCharArray().Any(password.Contains))
            count++;
        if(!upper_case.ToCharArray().Any(password.Contains))
            count++;
        if(!special_characters.ToCharArray().Any(password.Contains))
            count++;
        return Math.Max(6-n,count);
    }

    static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());
        string password = Console.ReadLine();
        int answer = minimumNumber(n, password);
        Console.WriteLine(answer);
    }
}

 

Attempt Strong Password HackerRank Challenge

Link – https://www.hackerrank.com/challenges/strong-password/ 

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/two-characters-hackerrank-solution/

Leave a Comment