Solve two algorithm problems from a menu
Company: Palantir
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving, practical coding implementation, complexity analysis, testing rigor, and the ability to discuss design trade-offs across topics such as arrays, strings, hash maps, and graphs.
Part 1: Longest Consecutive Sequence
Constraints
- 0 <= len(nums) <= 200000
- -10^9 <= nums[i] <= 10^9
- The input may contain duplicate values
- Return 0 when the input list is empty
Examples
Input: ([100, 4, 200, 1, 3, 2],)
Expected Output: 4
Explanation: The longest consecutive sequence is [1, 2, 3, 4], so the answer is 4.
Input: ([0, 3, 7, 2, 5, 8, 4, 6, 0, 1],)
Expected Output: 9
Explanation: The numbers 0 through 8 are all present, giving a longest sequence length of 9.
Input: ([],)
Expected Output: 0
Explanation: An empty list has no consecutive sequence.
Input: ([9],)
Expected Output: 1
Explanation: A single element forms a consecutive sequence of length 1.
Input: ([-2, -3, -1, 10],)
Expected Output: 3
Explanation: The longest consecutive sequence is [-3, -2, -1], which has length 3.
Solution
def solution(nums):
num_set = set(nums)
best = 0
for num in num_set:
if num - 1 not in num_set:
current = num
length = 1
while current + 1 in num_set:
current += 1
length += 1
if length > best:
best = length
return best