Open In App

Count of possible rotations of given Array to remove largest element from first half

Last Updated : 28 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[ ] with even length N, the task is to find the number of cyclic shifts (rotations) possible for this array, such that the first half of array does not contain the maximum element.

Examples:

Input: N = 6, arr[ ] = { 3, 3, 5, 3, 3, 3 }
Output: 3
Explanation: The maximum element here is 5 at index 2. This 5 can be shifted to second half of the array using any of the below three valid right shifts:

  • shift by 1: (3, 3, 3, 5, 3, 3)
  • shift by 2: (3, 3, 3, 3, 5, 3)
  • shift by 3: (3, 3, 3, 3, 3, 5)

Input: N = 6, arr[ ] = {8, 8, 9, 8, 8, 9}
Output: 0
Explanation: Any rotation in the article wont help in removing the maximum element from 1st half, as there are two occurrences of 9 at index 2 and 5. So any rotation will keep atleast one 9 at index 0, 1 or 2.

 

Naive Approach: The most basic approach to solve this problem, is based on below idea:

Find all rotations of given array. In the end, just return the count of such rotations which do not have the maximum element in first half.

Time Complexity: O(N3) where N^2 is for rotations and N is for finding maximum in each rotation.
Auxiliary Space: O(1)

Efficient Approach: The idea to solve the problem is by traversing the array and some basic concepts of maths. 

The idea is to find distance between maximum elements and simply check if the range is greater than half of array size. If yes, rotation is possible, or else rotation is not possible.

For case when rotation is possible, we can find the [range – (n/2)] as the valid number of rotations.

Follow the steps to solve the problem:

  • Firstly, find the maximum element
  • Then find the maximal ranges between pairs of maximum elements.
  • A range with length m adds max(m-frac(N/2)+1, 0) to the answer.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the number of cyclic shifts
int find(int arr[], int N)
{
    int maxele = *max_element(arr, arr + N);
    int left = -1;
    int right = -1;
 
    // Placing left pointer
    // On its correct position
    for (int i = 0; i < N; i++) {
        if (arr[i] == maxele) {
            left = i;
            break;
        }
    }
 
    // Placing right pointer
    // On its correct position
    for (int i = N - 1; i >= 0; i--) {
        if (arr[i] == maxele) {
            right = i;
            break;
        }
    }
    int ans = (N / 2) - (right - left);
    if (ans <= 0) {
        return 0;
    }
    else {
        return ans;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 3, 5, 3, 3, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << find(arr, N);
    return 0;
}


Java




// Java program for the above approach.
import java.io.*;
class GFG {
 
  // Function to find the number of cyclic shifts
  static int find(int arr[], int N)
  {
    int maxele = Integer.MIN_VALUE;
    for(int i  = 0; i < N; i++){
      maxele = Math.max(arr[i], maxele);
    }
    int left = -1;
    int right = -1;
 
    // Placing left pointer
    // On its correct position
    for (int i = 0; i < N; i++) {
      if (arr[i] == maxele) {
        left = i;
        break;
      }
    }
 
    // Placing right pointer
    // On its correct position
    for (int i = N - 1; i >= 0; i--) {
      if (arr[i] == maxele) {
        right = i;
        break;
      }
    }
    int ans = (N / 2) - (right - left);
    if (ans <= 0) {
      return 0;
    }
    else {
      return ans;
    }
  }
 
  // Driver Code
  public static void main (String[] args) {
    int arr[] = { 3, 3, 5, 3, 3, 3 };
    int N = arr.length;
 
    // Function call
    System.out.print(find(arr, N));
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# Python code for the above approach
 
# Function to find the number of cyclic shifts
def find(arr, N):
    maxele = max(arr)
    left = -1
    right = -1
 
    # Placing left pointer
    # On its correct position
    for i in range(N):
        if (arr[i] == maxele):
            left = i
            break
 
    # Placing right pointer
    # On its correct position
    for i in range(N - 1, -1, -1):
        if (arr[i] == maxele):
            right = i
            break
    ans = (N // 2) - (right - left)
    if (ans <= 0):
        return 0
    else:
        return ans
 
# Driver Code
arr = [3, 3, 5, 3, 3, 3]
N = len(arr)
 
# Function call
print(find(arr, N))
 
# This code is contributed by shinjanpatra


C#




// C# program for the above approach.
using System;
class GFG {
 
    // Function to find the number of cyclic shifts
    static int find(int[] arr, int N)
    {
        int maxele = Int32.MinValue;
        for (int i = 0; i < N; i++) {
            maxele = Math.Max(arr[i], maxele);
        }
        int left = -1;
        int right = -1;
 
        // Placing left pointer
        // On its correct position
        for (int i = 0; i < N; i++) {
            if (arr[i] == maxele) {
                left = i;
                break;
            }
        }
 
        // Placing right pointer
        // On its correct position
        for (int i = N - 1; i >= 0; i--) {
            if (arr[i] == maxele) {
                right = i;
                break;
            }
        }
        int ans = (N / 2) - (right - left);
        if (ans <= 0) {
            return 0;
        }
        else {
            return ans;
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 3, 3, 5, 3, 3, 3 };
        int N = arr.Length;
 
        // Function call
        Console.Write(find(arr, N));
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find the number of cyclic shifts
       function find(arr, N) {
           let maxele = Math.max([...arr]);
           let left = -1;
           let right = -1;
 
           // Placing left pointer
           // On its correct position
           for (let i = 0; i < N; i++) {
               if (arr[i] == maxele) {
                   left = i;
                   break;
               }
           }
 
           // Placing right pointer
           // On its correct position
           for (let i = N - 1; i >= 0; i--) {
               if (arr[i] == maxele) {
                   right = i;
                   break;
               }
           }
           let ans = Math.floor(N / 2) - (right - left);
           if (ans <= 0) {
               return 0;
           }
           else {
               return ans;
           }
       }
 
       // Driver Code
 
       let arr = [3, 3, 5, 3, 3, 3];
       let N = arr.length;
 
       // Function call
       document.write(find(arr, N));
 
     // This code is contributed by Potta Lokesh
 
   </script>


 
 

Output

3

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 



Similar Reads

Count number of rotated strings which have more number of vowels in the first half than second half
Given string str of even size N consisting of lowercase English alphabets. The task is to find the number of rotated strings of str which have more vowels in the first half than the second half. Examples: Input: str = "abcd" Output: 2 Explanation:All rotated string are "abcd", "dabc", "cdab", "bcda". The first two rotated strings have more vowels i
19 min read
Find the sum of the first half and second half elements of an array
Given an array arr of size N. The task is to find the sum of the first half (N/2) elements and the second half elements (N - N/2) of an array. Examples: Input : arr[] = {20, 30, 60, 10, 25, 15, 40} Output : 110, 90 Sum of first N/2 elements 20 + 30 + 60 is 110Input : arr[] = {50, 35, 20, 15} Output : 85, 35 Approach: Initialize SumFirst and SumSeco
10 min read
Find prime numbers in the first half and second half of an array
Given an array arr of size N. The task is to find the prime numbers in the first half (up to index N/2) and the second half (all the remaining elements) of an array.Examples: Input : arr[] = {2, 5, 10, 15, 17, 21, 23 } Output :2 5 and 17 23 Prime numbers in the first half of an array are 2, 5 and in the second half are 17, 23Input : arr[] = {31, 35
7 min read
Find the XOR of first half and second half elements of an array
Given an array arr of size N. The task is to find the XOR of the first half (N/2) elements and second half elements (N - N/2) of an array.Examples: Input: arr[]={20, 30, 50, 10, 55, 15, 42} Output: 56, 24 Explanation: XOR of first half elements 20 ^ 30 ^ 50 is 56 Xor of second half elements 10 ^ 55 ^ 15 ^ 42 is 24Input: arr[]={50, 45, 36, 6, 8, 87}
4 min read
Check if array sum of first half is divisible by sum of other half or vice versa
Given an array arr[] of size N, the task is to check if the sum of the left subarray is divisible by the sum of the right subarray or vice-versa. Print Yes if it was, otherwise No. Here, the left subarray will contain the string from 0 to mid=(N-1)/2 and the right subarray will contain the string from mid+1 to N-1. Example: Input: arr[] = [1, 2, 3,
5 min read
Check if sum of digits in the left half is divisible by sum of digits in the right half in the largest permutation of N
Given a positive integer N, the task is to maximize the integer N by rearranging the digits and check if the sum of the left half digits is divisible by the sum of the right half digits or not. If found to be true, then print "Yes". Otherwise, print "No". If the number of digits(say D) in the given number N is odd, then consider any of the two poss
8 min read
Interleave the first half of the queue with second half
Given a queue of integers of even length, rearrange the elements by interleaving the first half of the queue with the second half of the queue. We are allowed to use only the queue data structure.Examples: Input : 1 2 3 4 Output : 1 3 2 4 Input : 11 12 13 14 15 16 17 18 19 20 Output : 11 16 12 17 13 18 14 19 15 20 Create two auxiliary queues q1 and
5 min read
Merge first half and reversed second half of the linked list alternatively
Given a linked list, the task is to rearrange the linked list in the following manner: Reverse the second half of given linked list. First element of the linked list is the first element of first half.Second element of the linked list is the first element of second half. Examples: Input: 1-&gt;2-&gt;3-&gt;4-&gt;5 Output: 1-&gt;5-&gt;2-&gt;4-&gt;3 I
11 min read
Sum of elements in range L-R where first half and second half is filled with odd and even numbers
Given a number N, create an array such the first half of the array is filled with odd numbers till N, and the second half of the array is filled with even numbers. Also given are L and R indices, the task is to print the sum of elements in the array in the range [L, R]. Examples: Input: N = 12, L = 1, R = 11 Output: 66 The array formed thus is {1,
23 min read
Sort first half in ascending and second half in descending order | 1
Given an array of integers, sort the first half of the array in ascending order and second half in descending order. Examples: Input : arr[] = {5, 2, 4, 7, 9, 3, 1, 6, 8} Output : arr[] = {1, 2, 3, 4, 9, 8, 7, 6, 5} Input : arr[] = {1, 2, 3, 4, 5, 6} Output : arr[] = {1, 2, 3, 6, 5, 4}Recommended PracticeSort first half in ascending and second half
10 min read