Count distinct passwords from one substring reversal
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests strings, counting and combinatorics.
A security team scores a password by its variability. Variability is the number of distinct strings you can get by reversing exactly one contiguous substring of the password.
Reversing a single character, or any palindromic substring, leaves the password unchanged. So the original password always counts once.
Implement:
def count_distinct_passwords(password: str) -> int
Return the variability of password.
Constraints
1 <= len(password) <= 10^5-
passwordhas only lowercase English letters. - The answer can be larger than
2^31 - 1.
Example 1
Input: password = "xyz"
Output: 4
The reachable strings are "xyz" (unchanged), "yxz", "xzy", and "zyx".
Example 2
Input: password = "ppq"
Output: 3
The reachable strings are "ppq", "pqp", and "qpp". Reversing "pp" gives back the original.
Clarifying questions
- Does reversing the whole password count as one of the reversals?
- Is the password guaranteed to be non-empty?
- Should the answer be exact, or modulo some number?
What a strong answer covers
- Starts from brute force (reverse every substring and put the results in a set), at O(n^3), to fix the definition.
- Sees that reversing
s[i..j]gives a new string exactly whens[i] != s[j]: if the ends match, the result equals reversings[i+1..j-1]. And different pairs(i, j)with different ends give different strings. - Counts the pairs
i < jwith different letters using letter counts, O(n + 26), and adds 1 for the original password. - Uses Python integers, since the count can be about
5 * 10^9. - Tests: both examples, a single letter, all letters equal, all letters distinct, and the brute force on random short strings.
Follow-ups
- Exactly two reversals.
- Reverse any substring of length at most
L. - Return the lexicographically smallest password reachable with one reversal.
Where it's asked
What it tests
strings · counting · combinatorics
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
