I recently completed Visa's Software Engineer online assessment, which included three algorithmic coding questions. The problems covered minimizing the cost of prefix operations on an integer array, constructing the lexicographically smallest palindrome with minimum character replacements, and scheduling requests across multiple services with different processing costs.
Interview Details
Question 1 — Minimum Cost to Make All Array Elements Equal Using Prefix Operations
Given an integer array arr, you can perform the following operation any number of times:
Choose a prefix of length k, where 1 <= k <= n.
Choose any integer x, which may be positive or negative.
Add x to every element within the selected prefix.
The cost of performing an operation is |x|, the absolute value of the chosen integer. The goal is to make all elements in the array equal while minimizing the sum of operation costs.
Example
Input:
arr = [3, 6, 4, 9]
Output:
10
Input:
arr = [3, 6, 4, 9]
Output:
10
Explanation
One possible sequence of operations is:
Add +3 to the first element, producing [6, 6, 4, 9]. Cost: 3.
Add +2 to the first two elements, producing [8, 8, 6, 9]. Cost: 2.
Add +3 to the first three elements, producing [11, 11, 9, 9]. Cost: 3.
Add -2 to the first three elements, producing [9, 9, 9, 9]. Cost: 2.
The total cost is 3 + 2 + 3 + 2 = 10.
Constraints
1 <= n <= 200,000
1 <= arr[i] <= 1,000,000,000
Key Observation — Adjacent Differences
The important observation was that a prefix operation changes only one adjacent difference within the array. For a prefix ending at index i, adding the same value to all elements in that prefix leaves the differences between elements inside the prefix unchanged.
Unlock Full Details
Create a free account to unlock this interview experience report.