Determine balanced k values in a permutation
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates algorithmic reasoning about permutations and contiguous subarray properties, testing skills in array manipulation, positional reasoning, combinatorial insight, and complexity-aware algorithm design within the Coding & Algorithms domain.
Constraints
- 1 <= n <= 2 * 10^5
- p is a permutation of the integers 1..n
- An O(n) or O(n log n) solution is expected
Examples
Input: (5, [4, 1, 3, 2, 5])
Expected Output: "10111"
Explanation: For k=1, the value 1 appears alone, so it is balanced. For k=2, positions of 1 and 2 are not adjacent. For k=3, values {1,2,3} occupy positions 2..4. For k=4 and k=5, the required values also occupy a contiguous block.
Input: (1, [1])
Expected Output: "1"
Explanation: The only possible k is 1, and the single-element subarray [1] matches {1}.
Input: (4, [2, 1, 4, 3])
Expected Output: "1101"
Explanation: k=1 and k=2 are balanced because 1 and then {1,2} occupy contiguous positions. For k=3, positions of {1,2,3} span length 4, so it fails. k=4 is balanced because the whole array contains {1,2,3,4}.
Input: (6, [1, 2, 3, 4, 5, 6])
Expected Output: "111111"
Explanation: For every k, the first k elements are exactly {1,2,...,k}, so every k is balanced.
Input: (5, [3, 4, 5, 1, 2])
Expected Output: "11001"
Explanation: k=1 is balanced by the subarray [1], and k=2 is balanced by [1,2]. For k=3 and k=4, the positions of 1..k are too spread out. k=5 is balanced because the full array contains all values 1..5.
Solution
def solution(n, p):
if n == 0:
return ""
pos = [0] * (n + 1)
for i, value in enumerate(p):
pos[value] = i
answer = []
min_pos = pos[1]
max_pos = pos[1]
for k in range(1, n + 1):
if k > 1:
if pos[k] < min_pos:
min_pos = pos[k]
if pos[k] > max_pos:
max_pos = pos[k]
if max_pos - min_pos + 1 == k:
answer.append('1')
else:
answer.append('0')
return ''.join(answer)
Time complexity: O(n). Space complexity: O(n).
Hints
- Instead of checking every subarray, first record the position of each value from 1 to n.
- For a fixed k, the numbers 1..k can form a valid length-k subarray exactly when their minimum and maximum positions span k indices.