Solve Two Algorithm Challenges
Company: Visa
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Take-home Project
Quick Answer: These two problems evaluate algorithmic skills in array optimization and graph pathfinding: the first focuses on selecting three ordered, non-overlapping variable-length subarrays to maximize the total sum with lexicographic tie-breaking, and the second targets shortest-path computation and optional path reconstruction in a directed weighted graph.
Part 1: Maximize Three Non-Overlapping Subarrays
Constraints
- 0 <= len(nums) <= 200000
- -10^9 <= nums[i] <= 10^9
- 1 <= k1, k2, k3 <= 200000
- A valid answer must satisfy i + k1 <= j, j + k2 <= l, and l + k3 <= len(nums)
Examples
Input: ([1, 2, 1, 2, 6, 7, 5, 1], 2, 2, 2)
Expected Output: [0, 3, 5]
Explanation: The best three length-2 subarrays start at 0, 3, and 5 with sums 3, 8, and 12.
Input: ([4, 5, 10, 6, 11, 17, 4, 5, 2], 1, 2, 3)
Expected Output: [0, 1, 3]
Explanation: The maximum total is achieved by subarrays starting at 0, 1, and 3, giving 4 + 15 + 34 = 53.
Input: ([1, 2], 1, 1, 1)
Expected Output: []
Explanation: The array is too short to fit three non-overlapping subarrays.
Input: ([5, 5, 5, 5, 5, 5], 1, 1, 1)
Expected Output: [0, 1, 2]
Explanation: Many choices have the same total sum, so the lexicographically smallest valid answer is returned.
Hints
- Precompute the sum of every window of size k1, k2, and k3 using a sliding window or prefix sums.
- For each possible middle subarray start j, quickly find the best first subarray on the left and the best third subarray on the right. Be careful to keep the smallest indices when sums tie.
Part 2: Shortest Path in a Directed Weighted Graph
Constraints
- 1 <= n <= 200000
- 0 <= len(edges) <= 300000
- 0 <= u, v < n
- 0 <= w <= 10^9
- 0 <= source, target < n
Examples
Input: (5, [(0, 1, 2), (0, 2, 5), (1, 2, 1), (1, 3, 2), (2, 3, 1), (3, 4, 3)], 0, 4)
Expected Output: 7
Explanation: One shortest path is 0 -> 1 -> 3 -> 4 with total cost 2 + 2 + 3 = 7.
Input: (4, [(0, 1, 1), (1, 2, 2)], 0, 3)
Expected Output: -1
Explanation: Node 3 cannot be reached from node 0.
Input: (3, [(0, 1, 4), (1, 2, 5)], 2, 2)
Expected Output: 0
Explanation: The shortest path from a node to itself has cost 0.
Input: (4, [(0, 1, 10), (0, 1, 3), (1, 2, 0), (2, 3, 2), (0, 3, 10)], 0, 3)
Expected Output: 5
Explanation: The best route uses the cheaper parallel edge 0 -> 1 with weight 3, then 1 -> 2 -> 3 for a total of 5.
Hints
- Since all edge weights are non-negative, think about the classic shortest-path algorithm that uses a priority queue.
- Store the best known distance to each node, and when you pop a node with a larger stale distance, skip it.