Count ordered fragment pairs forming a password
Company: Capital One
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates proficiency with string manipulation, handling duplicate fragments, and combinatorial reasoning about ordered index pairs that concatenate to a target, reflecting algorithmic problem-solving and correctness under index distinctness constraints.
Constraints
- 1 <= len(password)
- 0 <= N (fragments may be empty; fragments may repeat)
- The answer can exceed 32-bit range; use a 64-bit integer.
- Empty-string fragments are allowed and count when '' + password == password or password + '' == password.
Examples
Input: ("abc", ["a", "bc", "ab", "c"])
Expected Output: 2
Explanation: Valid ordered pairs: ("a","bc") at indices (0,1) and ("ab","c") at indices (2,3). Each split contributes one pair, total 2.
Input: ("aa", ["a", "a"])
Expected Output: 2
Explanation: Split "a"+"a". prefix==suffix=="a" with count 2, so a*(a-1)=2*1=2: ordered pairs (0,1) and (1,0).
Input: ("aa", ["a"])
Expected Output: 0
Explanation: Only one fragment equals "a". Since i must differ from j and there is no second "a", no pair forms; a*(a-1)=1*0=0.
Input: ("abcd", ["ab", "cd", "abc", "d", "a", "bcd"])
Expected Output: 3
Explanation: Splits that match: "a"+"bcd", "ab"+"cd", and "abc"+"d" — three distinct ordered pairs.
Input: ("xyxy", ["xy", "xy", "xy"])
Expected Output: 6
Explanation: Only split "xy"+"xy" works; prefix==suffix=="xy" with count 3, giving 3*2=6 ordered distinct-index pairs.
Input: ("hello", ["hel", "world", "lo"])
Expected Output: 1
Explanation: Only "hel"+"lo"=="hello" matches (count 1 each, different strings): one ordered pair.
Input: ("ab", [])
Expected Output: 0
Explanation: Empty fragment list: no pairs possible.
Input: ("a", ["a", "", "a"])
Expected Output: 4
Explanation: Edge case with an empty-string fragment. Split ""+"a": prefix "" (count 1) times suffix "a" (count 2)=2. Split "a"+"": 2*1=2. Total 4 ordered pairs.
Hints
- Brute force over all i != j is O(N^2). Instead, note that a valid pair must split `password` at exactly one position into a prefix and a suffix.
- Count how many fragments equal each string with a hash map, then for each of the L+1 split positions multiply (count of prefix) by (count of suffix).
- When prefix == suffix the two halves are the same string, and a single fragment cannot pair with itself: use a*(a-1) instead of a*a to respect i != j.