# Strong Password Checker in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string, password. We have to find out minimum changes required to make the password strong. So the password has some following criteria −

• It must be at least 6 character long and at most 20-character long
• It must contain at least one lowercase letter, at least one uppercase letter, and at least one numeric character.
• It must not contain three repeating characters in a row like …aaa…, …PPP…, …888….

So if the input is like "aa26bbb", so we need at least one change, as there is no uppercase letter, and there is three b’s in a row, so we can replace any b with one uppercase letter to make it strong.

To solve this, we will follow these steps −

• set missingTypes := 3.
• if it has at least one lowercase letter, decrease missingTypes by 1
• if it has at least one uppercase letter, decrease missingTypes by 1
• if it has at least one number, decrease missingTypes by 1
• change := 0, one := 0 and two := 0, p := 2
• while p < size of s, do
• if s[p] is same as s[p – 1] and this is also same as s[p - 2], then
• length := 2
• while p < size of s and s[p] = s[p – 1], do
• length := length + 1
• p := p + 1
• change := change + length / 3
• if length is divisible by 3, then increase one by 1
• otherwise when length is divisible by 3, then increase two by 1
• otherwise increase p by 1
• if size of s < 6, then return max of missing_type and 6 – size of s
• otherwise when size of s < 20, then return max of missing_type and change
• otherwise
• delete := size of s – 20
• change := change – minimum of delete and one
• change := change – (min of (max of delete – one and 0) and two * 2)/2
• change := change – (max of delete – one – 2 * two and 0)/2
• return delete + max of missing_type and change

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution(object):
def strongPasswordChecker(self, s):
missing_type = 3
if any('a' <= c <= 'z' for c in s): missing_type -= 1
if any('A' <= c <= 'Z' for c in s): missing_type -= 1
if any(c.isdigit() for c in s): missing_type -= 1
change = 0
one = two = 0
p = 2
while p < len(s):
if s[p] == s[p-1] == s[p-2]:
length = 2
while p < len(s) and s[p] == s[p-1]:
length += 1
p += 1
change += length / 3
if length % 3 == 0: one += 1
elif length % 3 == 1: two += 1
else:
p += 1
if len(s) < 6:
return max(missing_type, 6 - len(s))
elif len(s) <= 20:
return max(missing_type, change)
else:
delete = len(s) - 20
change -= min(delete, one)
change -= min(max(delete - one, 0), two * 2) / 2
change -= max(delete - one - 2 * two, 0) / 3
return delete + max(missing_type, change)
ob = Solution()
print(ob.strongPasswordChecker('aa26bbb'))

## Input

“aa26bbb”

## Output

1
Published on 01-Jun-2020 10:51:05
Advertisements