Find Pivot Index
Updated
Problem statement
For an integer array nums, call index i a pivot when the numbers strictly to its left add up to the same total as the numbers strictly to its right. nums[i] itself belongs to neither side, and an empty side adds up to 0.
Return the smallest pivot index, or -1 if no index is a pivot.
Function
pivotIndex(nums: int[]) → intExamples
Example 1
nums = [2,3,-1,8,4]return = 3At index 3 the numbers to the left add up to 2 + 3 + (-1) = 4, and the number to the right is 4. No smaller index works: the left and right sums are 0 and 14 at index 0, 2 and 11 at index 1, and 5 and 12 at index 2. The answer is 3.
Example 2
nums = [1,2,3]return = -1The left and right sums are 0 and 5 at index 0, 1 and 3 at index 1, and 3 and 0 at index 2. They are never equal, so the answer is -1.
Example 3
nums = [4,-4,9]return = 2At index 2 the left sum is 4 + (-4) = 0, and there is nothing to the right, so the right sum is also 0. The answer is 2.
Constraints
1 <= nums.length <= 10^4-1000 <= nums[i] <= 1000
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Roll a Weighted DieLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Advertisement Click Range SumsGoogle · ONSITE INTERVIEWGoogle interview questions
- Calculate Server Shutdown PenaltyStripe · PHONE SCREEN · ONSITE INTERVIEWStripe interview questions
- Leftmost Equilibrium IndexExpedia · ONSITE INTERVIEWExpedia interview questions
- Product of Array Except SelfWalmart Labs · ONSITE INTERVIEW
- Subarrays Whose Sum Is a Power of TwoKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Maximize Compatible Car RidersUber Freight · PHONE SCREEN · ONSITE INTERVIEWUber Freight interview questions
- Count Subarrays with Sum KMakeMyTrip.com · ONSITE INTERVIEWMakeMyTrip.com interview questions
- Product Of Array Except SelfInfosys · ONSITE INTERVIEWInfosys interview questions
- Maximum Subarray Sum with Length at Most KOracle · ONSITE INTERVIEWOracle interview questions