Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Rearrange array elements to maximize the sum of MEX of all prefix arrays
Next article icon

Rearrange the given array to minimize the indices with prefix sum at least arr[i]

Last Updated : 02 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N positive integers, rearrange the array to minimize the number of indices i such that the prefix sum from index 1 to index i-1 is greater than or equal to the current element arr[i] i.e. arr[1]+arr[2]+...+arr[i-1] >= arr[i].

Examples:

Input: arr[] = [4, 2, 1]
Output:
0
1 2 4
Explanation: If we arrange array as [1, 2, 4], there will be no indices following the criteria.
At index 1, there is no prefix sum.
At index 2, prefix sum = 1 < 2 hence not included in answer.
At index 3, prefix sum= 3 < 4 hence not included in answer.

Input: arr[] = [4, 7, 5, 10]
Output:
1
4 5 10 7
Explanation: If we arrange array as [4 5 10 7],
At index 1, there is no prefix sum.
At index 2, prefix sum=4 < 5 hence not included in answer.
At index 3, prefix sum= 9<10 hence not included in answer.
At index 4, prefix sum= 19>=7 hence included in answer.
There can be no other combination which can minimize answer.

Approach: To solve the problem, follow the below idea,

While the initial intuition might suggest sorting the array, it is not an optimal strategy. For example, consider the array [4, 5, 7, 10]. A direct sort could result in two indices following the condition. However, by rearranging the array as [4, 5, 10, 7], the number of indices is minimized to one.

A better approach involves systematically checking each index element that it is possible to add the current element to ans[] vector such that it exceeds its prefix sum. Additionally, any skipped elements between successful additions are included in the final result.

Step-by-step algorithm:

  • Sort the array and initialize count = 0.
  • Add first element to ans vector.
  • Now you just have to iterate over the sorted array.
  • If the current element is greater than prefix_sum then you have to just add that element into the answer array otherwise you have to skip that element.
  • The ans[] vector contains all the elements not satisfying the condition. Hence the remaining elements are included in count i.e. n-ans.size().
  • Push back all the skipped elements (use boolean array for tracking skipped elements).
  • Finally print the count and ans array.

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 number of // required indices and print the rearranged array int Rearrange_array(int arr[], int N) {      // initialising prefix sum     long long int prefix = 0;      vector<int> ans;     vector<bool> checked(N, true);      // sort the array     sort(arr, arr + N);     ans.push_back(arr[0]);     prefix += arr[0];     for (int i = 1; i < N; i++) {         if (arr[i] > prefix) {             prefix += arr[i];             ans.push_back(arr[i]);             checked[i] = false;         }     }      // the count of required numbers     int count = N - ans.size();     for (int i = 1; i < N; i++) {         if (checked[i])             ans.push_back(arr[i]);     }     cout << count << endl;     for (auto x : ans) {         cout << x << " ";     }     cout << endl; }  // Driver Code int main() {     int arr[] = { 4, 7, 5, 10 };     int N = sizeof(arr) / sizeof(arr[0]);     Rearrange_array(arr, N);      return 0; } 
Java
// java program for the above approach  import java.util.ArrayList; import java.util.Arrays; import java.util.List;  public class Solution {      // Function to find the number of required indices     // and print the rearranged array     static void rearrangeArray(int[] arr, int N) {         // Initializing prefix sum         long prefix = 0;          List<Integer> ans = new ArrayList<>();         boolean[] checked = new boolean[N];         Arrays.fill(checked, true);          // Sort the array         Arrays.sort(arr);         ans.add(arr[0]);         prefix += arr[0];          for (int i = 1; i < N; i++) {             if (arr[i] > prefix) {                 prefix += arr[i];                 ans.add(arr[i]);                 checked[i] = false;             }         }          // The count of required numbers         int count = N - ans.size();          for (int i = 1; i < N; i++) {             if (checked[i]) {                 ans.add(arr[i]);             }         }          System.out.println(count);          for (int x : ans) {             System.out.print(x + " ");         }         System.out.println();     }      // Main function     public static void main(String[] args) {         int[] arr = {4, 7, 5, 10};         int N = arr.length;         rearrangeArray(arr, N);     } } 
Python3
# Python program for the above approach def rearrange_array(arr, N):     # Initializing prefix sum     prefix = 0      ans = []     checked = [True] * N      # Sort the array     arr.sort()     ans.append(arr[0])     prefix += arr[0]      for i in range(1, N):         if arr[i] > prefix:             prefix += arr[i]             ans.append(arr[i])             checked[i] = False      # The count of required numbers     count = N - len(ans)      for i in range(1, N):         if checked[i]:             ans.append(arr[i])      print(count)      for x in ans:         print(x, end=" ")      print()  # Main function if __name__ == "__main__":     arr = [4, 7, 5, 10]     N = len(arr)     rearrange_array(arr, N) 
C#
//// c# program for the above approach using System; using System.Collections.Generic;  public class Solution {     // Function to find the number of required indices     // and print the rearranged array     static void RearrangeArray(int[] arr, int N)     {         // Initializing prefix sum         long prefix = 0;          List<int> ans = new List<int>();         bool[] checkedArray = new bool[N];         Array.Fill(checkedArray, true);          // Sort the array         Array.Sort(arr);         ans.Add(arr[0]);         prefix += arr[0];          for (int i = 1; i < N; i++)         {             if (arr[i] > prefix)             {                 prefix += arr[i];                 ans.Add(arr[i]);                 checkedArray[i] = false;             }         }          // The count of required numbers         int count = N - ans.Count;          for (int i = 1; i < N; i++)         {             if (checkedArray[i])             {                 ans.Add(arr[i]);             }         }          Console.WriteLine(count);          foreach (int x in ans)         {             Console.Write(x + " ");         }         Console.WriteLine();     }      // Main function     public static void Main(string[] args)     {         int[] arr = { 4, 7, 5, 10 };         int N = arr.Length;         RearrangeArray(arr, N);     } } 
JavaScript
// Javascript program for the above approach // Function to find the number of required indices // and print the rearranged array function rearrangeArray(arr, N) {     // Initializing prefix sum     let prefix = 0;      let ans = [];     let checkedArray = new Array(N).fill(true);      // Sort the array     arr.sort((a, b) => a - b);     ans.push(arr[0]);     prefix += arr[0];      for (let i = 1; i < N; i++) {         if (arr[i] > prefix) {             prefix += arr[i];             ans.push(arr[i]);             checkedArray[i] = false;         }     }      // The count of required numbers     let count = N - ans.length;      for (let i = 1; i < N; i++) {         if (checkedArray[i]) {             ans.push(arr[i]);         }     }      console.log(count);     console.log(ans.join(" ")); }  // Main function let arr = [4, 7, 5, 10]; let N = arr.length; rearrangeArray(arr, N); 

Output
1 4 5 10 7 

Time Complexity: O(N*logN), where N is the size of input array arr[].
Auxiliary Space: O(N)


Next Article
Rearrange array elements to maximize the sum of MEX of all prefix arrays

S

surbhisharmaias
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Arrays
  • prefix-sum
  • Arrays
  • DSA-Blogs
  • Geeks Premier League 2023
  • Connect through Content 2023
Practice Tags :
  • Arrays
  • Arrays
  • prefix-sum

Similar Reads

  • Rearrange given array to obtain positive prefix sums at exactly X indices
    Given an array arr[] consisting of N integers whose absolute values are distinct and an integer K, the task is to find such an arrangement of the given array by the following operations, such that it has positive prefix sum at exactly K places: Choose two integers i, j and swap the values of the ele
    8 min read
  • Minimum value to be added to the prefix sums at each array indices to make them positive
    Given an array arr[] consisting of N of integers, the task is to find the minimum positive value S that needs to be added such that the prefix sum at each index of the given array after adding S is always positive. Examples: Input: arr[] = {-3, 2, -3, 4, 2}Output: 5Explanation:For S = 5, prefix sums
    5 min read
  • Rearrange array elements to maximize the sum of MEX of all prefix arrays
    Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
    7 min read
  • Queries to minimize sum added to given ranges in an array to make their Bitwise AND non-zero
    Given an array arr[] consisting of N integers an array Q[][] consisting of queries of the form {l, r}. For each query {l, r}, the task is to determine the minimum sum of all values that must be added to each array element in that range such that the Bitwise AND of all numbers in that range exceeds 0
    10 min read
  • Find the indices which will hold the Array sum after given operations
    Given an array arr[], the task is to print the indices that have the highest probability of holding the entire sum of the array after performing the given operations: Choose any two elements say arr[i] and arr[j], store their sum in a variable KAssign K at index of max(arr[i], arr[j]) and assign 0 a
    10 min read
  • Minimize sum of distinct elements of all prefixes by rearranging Array
    Given an array arr[] with size N, the task is to find the minimum possible sum of distinct elements over all the prefixes of the array that can be obtained by rearranging the elements of the array. Examples: Input: arr[] = {3, 3, 2, 2, 3}, N = 5Output: 7Explanation: The permutation arr[] = {3, 3, 3,
    8 min read
  • Minimize cost for reducing array by replacing two elements with sum at most K times for any index
    Given an array arr[] of size N and an integer K. The task is to find the minimum cost required to collect the sum of the array. The sum of the array is collected by picking any element and adding it to an element of any index in the array. The addition of elements at the same index is allowed for at
    11 min read
  • Reverse a subarray of the given array to minimize the sum of elements at even position
    Given an array arr[] of positive integers. The task is to reverse a subarray to minimize the sum of elements at even places and print the minimum sum. Note: Perform the move only one time. Subarray might not be reversed. Example: Input: arr[] = {1, 2, 3, 4, 5} Output: 7 Explanation: Sum of elements
    15 min read
  • Minimize count of flips required to make sum of the given array equal to 0
    Given an array arr[] consisting of N integers, the task is to minimize the count of elements required to be multiplied by -1 such that the sum of array elements is 0. If it is not possible to make the sum 0, print "-1". Examples: Input: arr[] = {2, 3, 1, 4}Output: 2Explanation: Multiply arr[0] by -1
    15+ min read
  • Rearrange an array to minimize sum of product of consecutive pair elements
    We are given an array of even size, we have to sort the array in such a way that the sum of product of alternate elements is minimum also we have to find that minimum sum. Examples: Input : arr[] = {9, 2, 8, 4, 5, 7, 6, 0} Output : Minimum sum of the product of consecutive pair elements: 74 Sorted a
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences