Equilibrium Index of an Array in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Equilibrium Index of an Array in C

šŸ“‘ On this page:
  • Introduction
  • C Program to Find Equilibrium Index
  • Sample Output
  • Program Explanation
  • Step-by-Step Approach
  • Time & Space Complexity
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • What is an equilibrium index of an array
  • How to find equilibrium index using prefix sum technique
  • Optimized approach using total sum
  • Time and space complexity analysis
  • Real-world applications and practice problems

Introduction to Equilibrium Index

The equilibrium index of an array is an index such that the sum of elements at lower indices is equal to the sum of elements at higher indices. In other words, for an array arr[] of size n, an index i is an equilibrium index if:

arr[0] + arr[1] + ... + arr[i-1] = arr[i+1] + arr[i+2] + ... + arr[n-1]

Key points about equilibrium index:

  • First and last positions: Index 0 is an equilibrium index if sum of all elements except first is 0. Index n-1 is an equilibrium index if sum of all elements except last is 0.
  • Multiple equilibrium indices: An array can have multiple equilibrium indices.
  • No equilibrium index: Some arrays may not have any equilibrium index.
  • Important concept: Used in various problems like prefix sum, subarray sum, and pivot index problems.

šŸ’” Example: For array [-7, 1, 5, 2, -4, 3, 0], the equilibrium index is 3 because:
arr[0] + arr[1] + arr[2] = -7 + 1 + 5 = -1
arr[4] + arr[5] + arr[6] = -4 + 3 + 0 = -1

C Program to Find Equilibrium Index

#include <stdio.h>

// Function to find equilibrium index using total sum approach
int equilibriumIndex(int arr[], int n) {
    int totalSum = 0;
    
    // Calculate total sum of the array
    for (int i = 0; i < n; i++) {
        totalSum += arr[i];
    }
    
    int leftSum = 0;
    
    // Traverse the array from left to right
    for (int i = 0; i < n; i++) {
        // Remove current element from total sum to get right sum
        int rightSum = totalSum - leftSum - arr[i];
        
        // Check if left sum equals right sum
        if (leftSum == rightSum) {
            return i; // Found equilibrium index
        }
        
        // Update left sum for next iteration
        leftSum += arr[i];
    }
    
    return -1; // No equilibrium index found
}

// Function to find all equilibrium indices
void findAllEquilibriumIndices(int arr[], int n) {
    int totalSum = 0;
    
    for (int i = 0; i < n; i++) {
        totalSum += arr[i];
    }
    
    int leftSum = 0;
    int found = 0;
    
    printf("Equilibrium indices: ");
    for (int i = 0; i < n; i++) {
        int rightSum = totalSum - leftSum - arr[i];
        
        if (leftSum == rightSum) {
            printf("%d ", i);
            found = 1;
        }
        
        leftSum += arr[i];
    }
    
    if (!found) {
        printf("None");
    }
    printf("\n");
}

// Function to print the array
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

// Driver program to test the equilibrium index
int main() {
    int arr1[] = {-7, 1, 5, 2, -4, 3, 0};
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    
    printf("Array 1: ");
    printArray(arr1, n1);
    
    int eqIndex1 = equilibriumIndex(arr1, n1);
    if (eqIndex1 != -1) {
        printf("Equilibrium index: %d\n", eqIndex1);
        printf("Left sum: ");
        for (int i = 0; i < eqIndex1; i++) {
            printf("%d ", arr1[i]);
        }
        printf("= %d\n", eqIndex1);
        printf("Right sum: ");
        for (int i = eqIndex1 + 1; i < n1; i++) {
            printf("%d ", arr1[i]);
        }
        printf("= %d\n", eqIndex1);
    } else {
        printf("No equilibrium index found.\n");
    }
    
    printf("\n");
    
    int arr2[] = {1, 2, 3, 4, 5, 6};
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
    
    printf("Array 2: ");
    printArray(arr2, n2);
    findAllEquilibriumIndices(arr2, n2);
    
    printf("\n");
    
    int arr3[] = {0, 0, 0, 0};
    int n3 = sizeof(arr3) / sizeof(arr3[0]);
    
    printf("Array 3: ");
    printArray(arr3, n3);
    findAllEquilibriumIndices(arr3, n3);
    
    return 0;
}

Sample Output

Array 1: -7 1 5 2 -4 3 0 
Equilibrium index: 3
Left sum: -7 1 5 = -1
Right sum: -4 3 0 = -1

Array 2: 1 2 3 4 5 6 
Equilibrium indices: None

Array 3: 0 0 0 0 
Equilibrium indices: 0 1 2 3

Another Example:

Array: 1 3 5 2 2 
Equilibrium index: 2
Left sum: 1 + 3 = 4
Right sum: 2 + 2 = 4

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Equilibrium Index Function:
    • Step 1: Calculate total sum of the array using a loop
    • Step 2: Initialize leftSum = 0
    • Step 3: Traverse the array from left to right:
      • Calculate rightSum = totalSum - leftSum - arr[i]
      • If leftSum == rightSum, return i
      • Add current element to leftSum
    • Step 4: Return -1 if no equilibrium index is found
  3. Find All Equilibrium Indices Function:
    • Uses the same approach but stores and prints all indices
    • Useful when multiple equilibrium indices exist
  4. Print Function: Displays all elements of the array.
  5. Main Function:
    • Tests the algorithm on different arrays
    • Demonstrates both single and multiple equilibrium index scenarios
    • Displays left and right sums for verification

šŸ“ Key Insight: The total sum approach is optimal because it avoids calculating the sum of left and right parts separately for each index. We maintain a running left sum and derive the right sum from the total sum.

Step-by-Step Approach

Step Action Explanation
1Calculate Total SumFind sum of all elements in the array
2Initialize Left SumSet leftSum = 0 (sum of elements before current index)
3Traverse ArrayFor each index, calculate rightSum = totalSum - leftSum - arr[i]
4Check ConditionIf leftSum == rightSum, current index is equilibrium index
5Update Left SumAdd current element to leftSum for next iteration
6Return ResultReturn index if found, else -1

Algorithm for Equilibrium Index

  1. Calculate Total Sum:
    • totalSum = sum(arr[0] to arr[n-1])
  2. Initialize:
    • leftSum = 0
  3. Traverse:
    • For i = 0 to n-1:
      • rightSum = totalSum - leftSum - arr[i]
      • If leftSum == rightSum: return i
      • leftSum += arr[i]
  4. Return: Return -1 if no equilibrium index is found

Time & Space Complexity

Complexity Best Case Average Case Worst Case
Time O(n) O(n) O(n)
Space O(1) - Constant space

šŸ“Š Key Points:

  • Linear time: The algorithm makes a single pass through the array
  • Constant space: Only uses a few variables regardless of array size
  • Optimal: O(n) is the best possible complexity as we must examine each element

šŸ’» Practice Exercise

Challenge 1: Modify the program to find the equilibrium index of an array without using the total sum (use prefix sum array).

Challenge 2: Write a program to find the pivot index of an array (similar to equilibrium index but defined differently in some contexts).

Challenge 3: Find the equilibrium index of an array with floating-point numbers.

šŸ” Click to Show Solution for Challenge 1
// Using prefix sum array
int equilibriumIndexPrefix(int arr[], int n) {
    int prefixSum[n];
    int totalSum = 0;
    
    // Build prefix sum array
    for (int i = 0; i < n; i++) {
        totalSum += arr[i];
        prefixSum[i] = totalSum;
    }
    
    for (int i = 0; i < n; i++) {
        int leftSum = (i == 0) ? 0 : prefixSum[i - 1];
        int rightSum = totalSum - prefixSum[i];
        
        if (leftSum == rightSum) {
            return i;
        }
    }
    return -1;
}
šŸ” Click to Show Solution for Challenge 3
// For floating point numbers
int equilibriumIndexFloat(float arr[], int n) {
    float totalSum = 0.0;
    for (int i = 0; i < n; i++) {
        totalSum += arr[i];
    }
    
    float leftSum = 0.0;
    for (int i = 0; i < n; i++) {
        float rightSum = totalSum - leftSum - arr[i];
        if (leftSum == rightSum) {
            return i;
        }
        leftSum += arr[i];
    }
    return -1;
}

Frequently Asked Questions

1. Can an array have multiple equilibrium indices?

Yes, an array can have multiple equilibrium indices. For example, array [0, 0, 0, 0] has equilibrium indices 0, 1, 2, and 3. Our findAllEquilibriumIndices() function handles this scenario.

2. What is the difference between equilibrium index and pivot index?

In most contexts, equilibrium index and pivot index are the same. However, in some problems, pivot index excludes the current element from the sum on either side, which is the same as our definition. The term "pivot index" is often used in LeetCode problems.

3. Can the equilibrium index be the first or last element?

Yes! The first element (index 0) is an equilibrium index if the sum of all elements except the first is 0. Similarly, the last element (index n-1) is an equilibrium index if the sum of all elements except the last is 0.

4. What is the time complexity of the naive approach?

The naive approach (calculating left and right sums for each index) would be O(n²). Our approach using total sum reduces it to O(n), which is optimal for this problem.

5. What are the real-world applications of equilibrium index?

Equilibrium index is used in:

  • Finding pivot points in financial data
  • Load balancing in distributed systems
  • Prefix sum problems and subarray sum queries
  • Split arrays into equal-sum subarrays

šŸ’” Pro Tip: Always consider edge cases like empty arrays, arrays with negative numbers, and arrays with all zeros when implementing equilibrium index algorithms.

šŸ“– Related Tutorials

  • Prefix Sum Array in C
  • Subarray Sum in C
  • Two Sum Problem in C
  • Array Rotation in C

Previous Topic: -->> Counting Sort in C   ||   Next topic: -->> Prefix Sum Array in C


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.