← Questions

Count distinct passwords from one substring reversal

0
AmazonCoding

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
  • password has 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 when s[i] != s[j]: if the ends match, the result equals reversing s[i+1..j-1]. And different pairs (i, j) with different ends give different strings.
  • Counts the pairs i < j with 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding