Find the index of the left pointer after possible moves in the array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size N. Our task is to find the index of the left pointer after possible moves in the array.

We have two pointers for the array, one left pointer and another right pointer.

Left pointer starts at index 0 and the value is incremented.

Right pointer starts at index (n-1) and the value is decremented.

The value of a pointer increases if the sum traversed is lesser than other, i.e. if left pointer's sum is less than right pointer's sum, left pointer is increased otherwise right pointer is decreased. And sum's are updated.

Let's take an example to understand the problem,

Input : arr[] = {5, 6, 3, 7, 9, 4}
Output : 2

Explanation

leftPointer = 0 -> sum = 5, rightPointer = 5 -> sum = 4. Move rightPointer
leftPointer = 0 -> sum = 5, rightPointer = 4 -> sum = 13. Move leftPointer
leftPointer = 1 -> sum = 11, rightPointer = 4 -> sum = 13. Move leftPointer
leftPointer = 2 -> sum = 14, rightPointer = 4 -> sum = 13. Move rightPointer
leftPointer = 2 -> sum = 14, rightPointer = 3 -> sum = 20. Move rightPointer
Position of the left pointer is 2.

Solution Approach

A simple solution to the problem is by moving the leftPointer and rightPointer based on the sums. And then check if leftPointer is one greater than rightPointer.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findIndexLeftPointer(int arr[], int n) {
   if(n == 1)
      return 0;
   int leftPointer = 0,rightPointer = n-1,leftPointerSum = arr[0], rightPointerSum = arr[n-1];
   while (rightPointer > leftPointer + 1) {
      if (leftPointerSum < rightPointerSum) {
         leftPointer++;
         leftPointerSum += arr[leftPointer];
      }
      else if (leftPointerSum > rightPointerSum) {
         rightPointer--;
         rightPointerSum += arr[rightPointer];
      }
      else {
         break;
      }
   }
   return leftPointer;
}
int main() {
   int arr[] = { 5, 6, 3, 7, 9, 4 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The index of left pointer after moving is "<<findIndexLeftPointer(arr, n);
   return 0;
}

Output

The index of left pointer after moving is 2
raja
Updated on 28-Jan-2022 07:32:10

Advertisements