Move all values equal to K to the end of the Array

Given an array arr[] of size N and an integer K, the task is to print the array after moving all value equal to K at the end of the array.

Examples:

Input: arr = [2, 1, 2, 2, 2, 3, 4, 2], K = 2
Output: [4, 1, 3, 2, 2, 2, 2, 2]
Explanation:
2 is the number which has to be moved to the end of the array arr[]. Therefore, after making the change the array is [4, 1, 3, 2, 2, 2, 2, 2]. The numbers 4, 1, and 3 could be ordered differently.

Input: arr = [1, 1, 3, 5, 6], K = 1
Output: [6, 5, 3, 1, 1 ]
Explanation:
1 is the number which has to be moved to the end of the array arr[]. Therefore, after making the change the array is [6, 5, 3, 1, 1 ].

Approach: To solve the problem mentioned above we use Two Pointer Technique.



  1. Initialize two pointers where the left pointer marks the start of the array and the other one that is right one marks the end of the array, respectively.
  2. Decrement the count of right pointer long as it points to K, and increment the left pointer as long as it doesn’t point to the integer m.
  3. When both pointers aren’t moving, swap their values in place.
  4. Repeat this process until the pointers pass each other.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to move all values
// equal to K to the end of the Array
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to move the element to the end
vector<int> moveElementToEnd(
    vector<int> array, int toMove)
{
    // Mark left pointer
    int i = 0;
  
    // Mark the right pointer
    int j = array.size() - 1;
  
    // Iterate untill left pointer
    // crosses the right pointer
    while (i < j) {
  
        while (i < j && array[j] == toMove)
  
            // decrement right pointer
            j--;
  
        if (array[i] == toMove)
  
            // swap the two elements
            // in the array
            swap(array[i], array[j]);
  
        // increment left pointer
        i++;
    }
  
    // return the result
    return array;
}
  
// Driver code
int main(int argc, char* argv[])
{
  
    vector<int> arr = { 1, 1, 3, 5, 6 };
    int K = 1;
  
    vector<int> ans
        = moveElementToEnd(arr, K);
  
    for (int i = 0; i < arr.size(); i++)
        cout << ans[i] << " ";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to move all values
// equal to K to the end of the Array
class GFG{
  
// Function to move the element to the end
static int[] moveElementToEnd(int []array,
                              int toMove)
{
    // Mark left pointer
    int i = 0;
  
    // Mark the right pointer
    int j = array.length - 1;
  
    // Iterate untill left pointer
    // crosses the right pointer
    while (i < j)
    {
        while (i < j && array[j] == toMove)
  
            // Decrement right pointer
            j--;
  
        if (array[i] == toMove)
  
            // Swap the two elements
            // in the array
            swap(array, i, j);
  
        // Increment left pointer
        i++;
    }
  
    // Return the result
    return array;
}
  
static int[] swap(int []arr, int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
  
// Driver code
public static void main(String[] args)
{
    int []arr = { 1, 1, 3, 5, 6 };
    int K = 1;
    int []ans = moveElementToEnd(arr, K);
  
    for(int i = 0; i < arr.length; i++)
       System.out.print(ans[i] + " ");
}
}
  
// This code is contributed by Princi Singh

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to move all values
# equal to K to the end of the Array
   
# Function to move the element to the end
def moveElementToEnd(array, toMove):
      
    # Mark left pointer
    i = 0
   
    # Mark the right pointer
    j = len(array) - 1
   
    # Iterate untill left pointer
    # crosses the right pointer
    while (i < j):
   
        while (i < j and array[j] == toMove):
   
            # decrement right pointer
            j-=1
   
        if (array[i] == toMove):
   
            # swap the two elements
            # in the array
            array[i], array[j] = array[j] , array[i]
   
        # increment left pointer
        i += 1
   
    # return the result
    return array
   
# Driver code
if __name__ =="__main__":
   
    arr = [ 1, 1, 3, 5, 6 ]
    K = 1
    ans = moveElementToEnd(arr, K)
    for i in range(len(arr)):
        print(ans[i] ,end= " ")
   
# This code is contributed by chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to move all values
// equal to K to the end of the Array
using System;
class GFG{
  
// Function to move the element to the end
static int[] moveElementToEnd(int []array,
                              int toMove)
{
    // Mark left pointer
    int i = 0;
  
    // Mark the right pointer
    int j = array.Length - 1;
  
    // Iterate untill left pointer
    // crosses the right pointer
    while (i < j)
    {
        while (i < j && array[j] == toMove)
  
            // Decrement right pointer
            j--;
  
        if (array[i] == toMove)
  
            // Swap the two elements
            // in the array
            swap(array, i, j);
  
        // Increment left pointer
        i++;
    }
  
    // Return the result
    return array;
}
  
static int[] swap(int []arr, int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
  
// Driver code
public static void Main(string[] args)
{
    int []arr = { 1, 1, 3, 5, 6 };
    int K = 1;
    int []ans = moveElementToEnd(arr, K);
  
    for(int i = 0; i < arr.Length; i++)
    Console.Write(ans[i] + " ");
}
}
  
// This code is contributed by rock_cool

chevron_right


Output:

6 5 3 1 1

Time complexity: O(N), where N is the length of the array.

Space complexity: O(1)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.