Logo
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    Akhil Abraham
    Akhil Abraham
    /Posts
    Posts
    /LeetCode
    LeetCode
    /
    LeetCode
    /0724 - Find Pivot Index
    0724 - Find Pivot Index
    0724 - Find Pivot Index
    0724 - Find Pivot Index

    0724 - Find Pivot Index

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/find-pivot-index/

    Solution 1 - Prefix Sum

    Given an array of integers nums, find the pivot index — the index where the sum of all elements strictly to the left equals the sum of all elements strictly to the right. Return the leftmost pivot index, or -1 if none exists.

    Approach: Compute the total sum first. Then iterate through the array, maintaining a running left sum. At each index, the right sum is total - left_sum - nums[i]. If left_sum == right_sum, return that index.

    TimeComplexity:O(n)TimeComplexity: O(n)TimeComplexity:O(n)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)
    """ 0724.1 - Solution 1 - Prefix Sum """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def pivotIndex(self, nums: List[int]) -> int:
            """Find Pivot Index Function"""
            total = sum(nums)
            left_sum = 0
    
            for i, num in enumerate(nums):
                right_sum = total - left_sum - num
                if left_sum == right_sum:
                    return i
                left_sum += num
    
            return -1
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().pivotIndex([1, 7, 3, 6, 5, 6]))   # Expected: 3
        print(Solution().pivotIndex([1, 2, 3]))              # Expected: -1
        print(Solution().pivotIndex([2, 1, -1]))             # Expected: 0
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()