The Wayback Machine - https://web.archive.org/web/20241006201130/https://www.geeksforgeeks.org/move-zeroes-end-array/
Open In App

Move all zeros to end of array

Last Updated : 24 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of integers arr[], the task is to move all the zeros to the end of the array while maintaining the relative order of all non-zero elements.

Examples: 

Input: arr[] = {1, 2, 0, 4, 3, 0, 5, 0}
Output: arr[] = {1, 2, 4, 3, 5, 0, 0, 0}
Explanation: There are three 0s that are moved to the end.

Input: arr[] = {10, 20, 30}
Output: arr[] = {10, 20, 30}
Explanation: No change in array as there are no 0s.

Input: arr[] = {0, 0}
Output: arr[] = {0, 0}
Explanation: No change in array as there are all 0s.

[Naive Approach] Using Temporary Array – O(n) Time and O(n) Space

The idea is to create a temporary array of same size as the input array arr[].

  • First, copy all non-zero elements from arr[] to the temporary array.
  • Then, fill all the remaining positions in temporary array with 0.
  • Finally, copy all the elements from temporary array to arr[].

Working:


Below is the implementation of the algorithm:

C++
// C++ Program to move all zeros to end using temporary array

#include <bits/stdc++.h>
using namespace std;

// function to move all zeros to the end
void pushZerosToEnd(vector<int> &arr) {
    int n = arr.size();
    vector<int> temp(n);

    // to keep track of the index in temp[]
    int j = 0;

    // Copy non-zero elements to temp[]
    for (int i = 0; i < n; i++) {
        if (arr[i] != 0)
            temp[j++] = arr[i];
    }

    // Fill remaining positions in temp[] with zeros
    while (j < n) {
        temp[j++] = 0;
    }

    // Copy all the elements from temp[] to arr[]
    for (int i = 0; i < n; i++)
        arr[i] = temp[i];
}

int main() {
    vector<int> arr = {1, 2, 0, 4, 3, 0, 5, 0};
    pushZerosToEnd(arr);

    // Print the modified array
    for (int num : arr) {
        cout << num << " ";
    }
    return 0;
}
C
// C Program to move all zeros to end using temporary array

#include <stdio.h>

// function to move all zeros to the end
void pushZerosToEnd(int *arr, int n) {
    int temp[n];
    
    // to keep track of the index in temp[]
    int j = 0;

    // Copy non-zero elements to temp[]
    for (int i = 0; i < n; i++) {
        if (arr[i] != 0)
            temp[j++] = arr[i];
    }

    // Fill remaining positions in temp[] with zeros
    while (j < n)
        temp[j++] = 0;

    // Copy all the elements from temp[] to arr[]
    for (int i = 0; i < n; i++)
        arr[i] = temp[i];
}

int main() {
    int arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    pushZerosToEnd(arr, n);

    // Print the modified array
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Java
// Java Program to move all zeros to end using temporary array

import java.util.Arrays;

class GfG {
    
    // function to move all zeros to the end
    static void pushZerosToEnd(int[] arr) {
        int n = arr.length;
        int[] temp = new int[n];

        // to keep track of the index in temp[]
        int j = 0;

        // Copy non-zero elements to temp[]
        for (int i = 0; i < n; i++) {
            if (arr[i] != 0)
                temp[j++] = arr[i];
        }

        // Fill remaining positions in temp[] with zeros
        while (j < n)
            temp[j++] = 0;

        // Copy all the elements from temp[] to arr[]
        for (int i = 0; i < n; i++)
            arr[i] = temp[i];
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 0, 4, 3, 0, 5, 0};
        pushZerosToEnd(arr);

        // Print the modified array
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Python
# Python Program to move all zeros to the end

# function to move all zeroes to the end
def pushZerosToEnd(arr):
    n = len(arr)
    temp = [0] * n  
    
    # to keep track of the index in temp[]
    j = 0

    # Copy non-zero elements to temp[]
    for i in range(n):
        if arr[i] != 0:
            temp[j] = arr[i]
            j += 1

    # Fill remaining positions in temp[] with zeros
    while j < n:
        temp[j] = 0
        j += 1

    # Copy all the elements from temp[] to arr[]
    for i in range(n):
        arr[i] = temp[i]

if __name__ == "__main__":
    arr = [1, 2, 0, 4, 3, 0, 5, 0]
    pushZerosToEnd(arr)

    # Print the modified array
    for num in arr:
        print(num, end=" ")
C#
// C# Program to move all zeros to end using temporary array

using System;

class GfG {
    
    // function to move all zeros to the end
    static void pushZerosToEnd(int[] arr) {
        int n = arr.Length;
        int[] temp = new int[n];

        // to keep track of the index in temp[]
        int j = 0;

        // Copy non-zero elements to temp[]
        for (int i = 0; i < n; i++) {
            if (arr[i] != 0)
                temp[j++] = arr[i];
        }

        // Fill remaining positions in temp[] with zeros
        while (j < n)
            temp[j++] = 0;

        // Copy all the elements from temp[] to arr[]
        for (int i = 0; i < n; i++)
            arr[i] = temp[i];
    }

    static void Main(string[] args) {
        int[] arr = {1, 2, 0, 4, 3, 0, 5, 0};
        pushZerosToEnd(arr);

        // Print the modified array
        foreach (int num in arr)
            Console.Write(num + " ");
    }
}
JavaScript
// JavaScript Program to move all zeros to end using temporary array

// function to move all zeros to the end
function pushZerosToEnd(arr) {
    const n = arr.length;
    const temp = new Array(n);

    // to keep track of the index in temp[]
    let j = 0;

    // Copy non-zero elements to temp[]
    for (let i = 0; i < n; i++) {
        if (arr[i] !== 0) {
            temp[j++] = arr[i];
        }
    }

    // Fill remaining positions in temp[] with zeros
    while (j < n)
        temp[j++] = 0;

    // Copy all the elements from temp[] to arr[]
    for (let i = 0; i < n; i++)
        arr[i] = temp[i];
}

const arr = [1, 2, 0, 4, 3, 0, 5, 0];
pushZerosToEnd(arr);

// Print the modified array
console.log(arr.join(" "));

Output
1 2 4 3 5 0 0 0 

Time complexity: O(n), as we are traversing the array three times.
Auxiliary Space : O(n), as we are using a temp[] array to move all the zeros.

[Better Approach] Two Traversals – O(n) Time and O(1) Space

The idea is to move all the zeros by traversing the array twice.

First Traversal: Shift non-zero elements

  • Traverse the array and maintain the count of non-zero elements. This count is initialized with 0 and keeps track of where the next non-zero element should be placed in the array.
  • If the element is non-zero, place it at arr[count] and increment count by 1.
  • After traversing all the elements, all non-zero elements will be shifted to the front while maintaining their original order.

Second Traversal: Fill remaining positions with zeros

  • After the first traversal, all non-zero elements will be at the start of the array and count will store the index where the first zero should be placed.
  • Iterate from count to the end of array and fill all indices with 0.

Working:


Below is the implementation of the algorithm:

C++
// C++ Program to move all zeros to end using two traversals

#include <bits/stdc++.h>
using namespace std;

// Function which pushes all zeros to end 
void pushZerosToEnd(vector<int>& arr) {
    
    // Count of non-zero elements
    int count = 0;  

    // If the element is non-zero, replace the element at
    // index 'count' with this element and increment count
    for (int i = 0; i < arr.size(); i++) {
        if (arr[i] != 0)
            arr[count++] = arr[i];
    }

    // Now all non-zero elements have been shifted to
    // the front. Make all elements 0 from count to end.
    while (count < arr.size())
        arr[count++] = 0;
}

int main() {
    vector<int> arr = {1, 2, 0, 4, 3, 0, 5, 0};
    pushZerosToEnd(arr);
    for (int num : arr) {
        cout << num << " ";
    }
    return 0;
}
C
// C Program to move all zeros to end using two traversals

#include <stdio.h>

// Function which pushes all zeros to end 
void pushZerosToEnd(int* arr, int n) {
    
    // Count of non-zero elements
    int count = 0;  

    // If the element is non-zero, replace the element at
    // index 'count' with this element and increment count
    for (int i = 0; i < n; i++) {
        if (arr[i] != 0)
            arr[count++] = arr[i];
    }

    // Now all non-zero elements have been shifted to
    // the front. Make all elements 0 from count to end.
    while (count < n)
        arr[count++] = 0;
}

int main() {
    int arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
    int size = sizeof(arr) / sizeof(arr[0]);
    pushZerosToEnd(arr, size);
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Java
// Java Program to move all zeros to end using two traversals

class GfG {

    // Function which pushes all zeros to end of an array
    static void pushZerosToEnd(int[] arr) {
        
        // Count of non-zero elements
        int count = 0;  

        // If the element is non-zero, replace the element at
        // index 'count' with this element and increment count
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != 0)
                arr[count++] = arr[i];
        }

        // Now all non-zero elements have been shifted to
        // the front. Make all elements 0 from count to end.
        while (count < arr.length)
            arr[count++] = 0;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 0, 4, 3, 0, 5, 0};
        pushZerosToEnd(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Python
# Python Program to move all zeros to end using two traversals

# Function which pushes all zeros to end
def pushZerosToEnd(arr):
    
    # Count of non-zero elements
    count = 0  

    # If the element is non-zero, replace the element at
    # index 'count' with this element and increment count
    for i in range(len(arr)):
        if arr[i] != 0:
            arr[count] = arr[i]
            count += 1

    # Now all non-zero elements have been shifted to
    # the front. Make all elements 0 from count to end.
    while count < len(arr):
        arr[count] = 0
        count += 1

if __name__ == "__main__":
    arr = [1, 2, 0, 4, 3, 0, 5, 0]
    pushZerosToEnd(arr)
    for num in arr:
        print(num, end=" ")
C#
// C# Program to move all zeros to end using two traversals

using System;

class GfG {

    // Function which pushes all zeros to end of an array
    static void pushZerosToEnd(int[] arr) {
        
        // Count of non-zero elements
        int count = 0;  

        // If the element is non-zero, replace the element at
        // index 'count' with this element and increment count
        for (int i = 0; i < arr.Length; i++) {
            if (arr[i] != 0)
                arr[count++] = arr[i];
        }

        // Now all non-zero elements have been shifted to
        // the front. Make all elements 0 from count to end.
        while (count < arr.Length)
            arr[count++] = 0;
    }

    static void Main() {
        int[] arr = { 1, 2, 0, 4, 3, 0, 5, 0 };
        pushZerosToEnd(arr);
        foreach (int num in arr) {
            Console.Write(num + " ");
        }
    }
}
JavaScript
// JavaScript Program to move all zeros to end using two traversals

// Function which pushes all zeros to end of an array
function pushZerosToEnd(arr) {
    
    // Count of non-zero elements
    let count = 0;  

    // If the element is non-zero, replace the element at
    // index 'count' with this element and increment count
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] !== 0)
            arr[count++] = arr[i];
    }

    // Now all non-zero elements have been shifted to
    // the front. Make all elements 0 from count to end.
    while (count < arr.length)
        arr[count++] = 0;
}

// Driver Code
const arr = [1, 2, 0, 4, 3, 0, 5, 0];
pushZerosToEnd(arr);
console.log(arr.join(" "));

Output
1 2 4 3 5 0 0 0 

Time Complexity: O(n), as we are traversing the array only twice.
Auxiliary Space: O(1)

[Expected Approach] One Traversal – O(n) Time and O(1) Space

The idea is similar to the previous approach where we took a pointer, say count to track where the next non-zero element should be placed. However, on encountering a non-zero element, instead of directly placing the non-zero element at arr[count], we will swap the non-zero element with arr[count]. This will ensure that if there is any zero present at arr[count], it is pushed towards the end of array and is not overwritten.

Working:


Below is the implementation of the algorithm

C++
// C++ Program to move all zeros to end using one traversal

#include <bits/stdc++.h>
using namespace std;

// Function which pushes all zeros to end of array
void pushZerosToEnd(vector<int>& arr) {
  
    // Pointer to track the position for next non-zero element
    int count = 0;
     
    for (int i = 0; i < arr.size(); i++) {

        // If the current element is non-zero
        if (arr[i] != 0) {
          
            // Swap the current element with the 0 at index 'count'
            swap(arr[i], arr[count]);
            // Move 'count' pointer to the next position
            count++;
        }
    }
}

int main() {
    vector<int> arr = {1, 2, 0, 4, 3, 0, 5, 0};
    pushZerosToEnd(arr);
    for (int num : arr) {
        cout << num << " ";
    }
    return 0;
}
C
// C Program to move all zeros to end using one traversal

#include <stdio.h>

// Function which pushes all zeros to end of array
void pushZerosToEnd(int arr[], int n) {
  
    // Pointer to track the position for next non-zero element
    int count = 0;
     
    for (int i = 0; i < n; i++) {

        // If the current element is non-zero
        if (arr[i] != 0) {
          
            // Swap the current element with the 0 at index 'count'
            int temp = arr[i];
            arr[i] = arr[count];
            arr[count] = temp;
          
            // Move 'count' pointer to the next position
            count++;
        }
    }
}

int main() {
    int arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    pushZerosToEnd(arr, size);
    
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}
Java
// Java Program to move all zeros to end using one traversal

import java.util.Arrays;

class GfG {

    // Function which pushes all zeros to end of array
    static void pushZerosToEnd(int[] arr) {

        // Pointer to track the position for next non-zero element
        int count = 0;

        for (int i = 0; i < arr.length; i++) {

            // If the current element is non-zero
            if (arr[i] != 0) {

                // Swap the current element with the 0 at index 'count'
                int temp = arr[i];
                arr[i] = arr[count];
                arr[count] = temp;

                // Move 'count' pointer to the next position
                count++;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 0, 4, 3, 0, 5, 0};
        pushZerosToEnd(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Python
# Python Program to move all zeros to end using one traversal

# Function which pushes all zeros to end of array
def pushZerosToEnd(arr):
    
    # Pointer to track the position for next non-zero element
    count = 0
    
    for i in range(len(arr)):
        
        # If the current element is non-zero
        if arr[i] != 0:
            
            # Swap the current element with the 0 at index 'count'
            arr[i], arr[count] = arr[count], arr[i]
            
            # Move 'count' pointer to the next position
            count += 1

if __name__ == "__main__":
    arr = [1, 2, 0, 4, 3, 0, 5, 0]
    pushZerosToEnd(arr)
    for num in arr:
        print(num, end=" ")
C#
// C# Program to move all zeros to end using one traversal

using System;

class GfG {
    
    // Function which pushes all zeros to end of array
    static void pushZerosToEnd(int[] arr) {
        
        // Pointer to track the position for next non-zero element
        int count = 0;

        for (int i = 0; i < arr.Length; i++) {
            
            // If the current element is non-zero
            if (arr[i] != 0) {
              
                // Swap the current element with the 0 at index 'count'
                int temp = arr[i];
                arr[i] = arr[count];
                arr[count] = temp;

                // Move 'count' pointer to the next position
                count++;
            }
        }
    }

    static void Main() {
        int[] arr = { 1, 2, 0, 4, 3, 0, 5, 0 };
        pushZerosToEnd(arr);
        foreach (int num in arr) {
            Console.Write(num + " ");
        }
    }
}
JavaScript
// JavaScript Program to move all zeros to end using one traversal

// Function which pushes all zeros to end of array
function pushZerosToEnd(arr) {
    
    // Pointer to track the position for next non-zero element
    let count = 0;
    
    for (let i = 0; i < arr.length; i++) {
        
        // If the current element is non-zero
        if (arr[i] !== 0) {
            
            // Swap the current element with the 0 at index 'count'
            [arr[i], arr[count]] = [arr[count], arr[i]];
            
            // Move 'count' pointer to the next position
            count++;
        }
    }
}

const arr = [1, 2, 0, 4, 3, 0, 5, 0];
pushZerosToEnd(arr);
console.log(arr.join(" "));

Output
1 2 4 3 5 0 0 0 

Time Complexity: O(n), as we are traversing the array only once.
Auxiliary Space: O(1)

Using Library Methods

In C++, there exists a method stable_parition() that we can directly use here to implement the above method.

C++
// C++ Program to move zeros to the end using Library Methods

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

void pushZerosToEnd(vector<int> &arr) {
    stable_partition(arr.begin(), arr.end(), [](int n) { 
                                       return n != 0; });
}

int main() {
    vector<int> arr = {1, 2, 0, 4, 3, 0, 5, 0};
    pushZerosToEnd(arr);
    for (int i : arr)
        cout << i << ' ';
    return 0;
}

Output
1 2 4 3 5 0 0 0 




Previous Article
Next Article

Similar Reads

Move all zeros to start and ones to end in an Array of random integers
Given an array arr[] of random integers, the task is to push all the zero's in the array to the start and all the one's to the end of the array. Note that the order of all the other elements should be the same.Example: Input: arr[] = {1, 2, 0, 4, 3, 0, 5, 0} Output: 0 0 0 2 4 3 5 1 Input: arr[] = {1, 2, 0, 0, 0, 3, 6}; Output: 0 0 0 2 3 6 1 Approac
10 min read
Move all zeros to front of array
Given an array arr[] of integers, the task is to move all the zeros to the front of the array while preserving the order of non-zero elements. Modify the given array inplace. Examples: Input: arr[] = {1, 0, 20, 4, 3, 0, 0, 5}Output: 0 0 0 1 20 4 3 5 Input: arr[] = {1, 0, 2, 0, 3, 0}Output: 0 0 0 1 2 3 Move all zeros to front of array using Linear S
8 min read
Move all zeros to the front of the linked list
Given a linked list. the task is to move all 0's to the front of the linked list. The order of all other elements except 0 should be the same after rearrangement. Examples: Input : 0 1 0 1 2 0 5 0 4 0 Output :0 0 0 0 0 1 1 2 5 4 Input :1 1 2 3 0 0 0 Output :0 0 0 1 1 2 3Recommended PracticeMove all zeros to the front of the linked listTry It! A sim
11 min read
Move all zeroes to end of array | Set-2 (Using single traversal)
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples: Input : arr[] = {1, 2, 0, 0, 0, 3, 6} Output : 1 2 3 6 0 0 0 Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9} Output: 1 9 8 4 2 7 6 9 0 0 0 0 0 Algo
7 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
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 ar
7 min read
POTD Solutions | 31 Oct’ 23 | Move all zeroes to end of array
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Two Pointers but will also help you build up problem-solving skills. We recommend you to try this problem
6 min read
Move all zeroes to end of array using List Comprehension in Python
Given an array of random numbers, Push all the zeros of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1). Examples: Input : a
2 min read
Javascript Program to Move all zeroes to end of array | Set-2 (Using single traversal)
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required. Examples: Input : arr[] = {1, 2, 0, 0, 0, 3, 6}Output : 1 2 3 6 0 0 0Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}Output: 1 9 8 4 2 7 6 9 0 0 0 0 0Algorit
2 min read
Javascript Program to Move all zeroes to end of array
Given an array of random numbers, Push all the zero's of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1). Example: Input : a
3 min read
Move all occurrence of letter 'x' from the string s to the end using Recursion
Given a string s, our task is to move all the occurrence of letter x to the end of the string s using recursion.Note: If there are only letter x in the given string then return the string unaltered. Examples: Input: s= "geekxsforgexxeksxx" Output: geeksforgeeksxxxxx Explanation: All occurrence of letter 'x' is moved to the end. Input: s = "xxxxx" O
8 min read
Move all occurrences of an element to end in a linked list
Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7 -> 6 -> 3 -> 10 key = 6 Output : 7 ->
15+ min read
Move all zeroes to end of number
Given a number N, the task is to move all zeroes in the number to the end. Examples: Input: N = 230404Output: 234400Explanation: After moving all the zeros to the end, 230404 becomes 234400 Input: N = 1004Output: 1400Explanation: After moving all the zeros to the end, 1004 becomes 1400. Approach: To solve the problem, follow the below idea: Find th
3 min read
Move all negative numbers to beginning and positive to end with constant extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers. Examples : Input: -12, 11, -13, -5, 6, -7, 5, -3, -6Output: -12 -13 -5 -7 -3 -6 11 6 5 Note: Order of elements is not important here. Naive approach: The idea is to sort the array of ele
15+ min read
Minimum move to end operations to make all strings equal
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end. Examples: Input: n = 2, arr[] = {"molzv", "lzvmo"}Output: 2Explanation: In first string, we remove first element("m") from first string and append it end. Then we move second chara
13 min read
Move all negative elements to end in order with extra space allowed
Given an unsorted array arr[] of both negative and positive integer. The task is place all negative element at the end of array without changing the order of positive element and negative element. Examples: Input : arr[] = {1, -1, 3, 2, -7, -5, 11, 6 }Output : 1 3 2 11 6 -1 -7 -5 Input : arr[] = {-5, 7, -3, -4, 9, 10, -1, 11}Output : 7 9 10 11 -5 -
11 min read
Javascript Program for Minimum move to end operations to make all strings equal
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end. Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"}Output : 2Explanation: In first string, we removefirst element("m") from first string and append it end. Then we move second chara
2 min read
Check if a king can move a valid move or not when N nights are there in a modified chessboard
Given an infinite chessboard with the same rules as that of chess. Also given are N knights coordinates on the infinite chessboard(-10^9 <= x, y <= 10^9) and the king's coordinate, the task is to check if the King is checkmate or not. Examples: Input: a[] = { {1, 0}, {0, 2}, {2, 5}, {4, 4}, {5, 0}, {6, 2} } king -> {3, 2} Output: Yes The k
10 min read
Numbers whose factorials end with n zeros
Given an integer n, we need to find the number of positive integers whose factorial ends with n zeros.Examples: Input : n = 1 Output : 5 6 7 8 9 Explanation: Here, 5! = 120, 6! = 720, 7! = 5040, 8! = 40320 and 9! = 362880. Input : n = 2 Output : 10 11 12 13 14 Recommended PracticeN trailing zeroes in factorialsTry It! Prerequisite : Trailing zeros
6 min read
Minimize cost to reach end of an array by two forward jumps or one backward jump in each move
Given an array arr[] consisting of N positive integers, the task is to find the minimum cost required to either cross the array or reach the end of the array by only moving to indices (i + 2) and (i - 1) from the ith index. Examples: Input: arr[] = {5, 1, 2, 10, 100}Output: 18Explanation:Optimal cost path (0 based indexing): 0 ? 2 ? 1 ? 3 ? 5Theref
11 min read
Move first element to end of a given Linked List
Write a C function that moves first element to end in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 2->3->4->5->1. Algorithm: Traverse the list till last node. Use two pointers: one to store the address of last node(last) and other for address
14 min read
Double the first element and move zero to end
For a given array of n integers and assume that '0' is an invalid number and all others a valid number. Convert the array in such a way that if both current and next element is valid and both have same value then double current value and replace the next number with 0. After the modification, rearrange the array such that all 0’s shift to the end.
14 min read
Move the Kth Element in a Doubly Linked List to the End
Given a doubly linked list and an integer K, you need to move the Kth element to the end of the list while maintaining the order of the other elements. Examples: Input: DLL: 2 <-> 6 <-> 3 <-> 8 <-> 11 <-> 23 <-> 7 -> NULL, K = 1Output: 6 <-> 3 <-> 8 <-> 11 <-> 23 <-> 7 <-> 2
13 min read
Move the First Fibonacci Number to the End of a Linked List
Given a singly linked list, the task is to identify the first Fibonacci number in the list and move that node to the end of the linked list. Examples: Input: 10 -> 15 -> 8 -> 13 -> 21 -> 5 -> 2 -> NULLOutput: 10 -> 15 -> 13 -> 21 -> 5 -> 2 -> 8 -> NULLExplanation: In the given list, the Fibonacci numbers ar
12 min read
Move the Kth Prime Number Node to the End of the Linked List
Given a singly linked list, the task is to move the Kth prime number node to the end of the list while preserving the order of other nodes. Examples: Input: 4 -> 7 -> 11 -> 3 -> 14 -> 2 -> NULL, K = 2Output: 4 -> 7 -> 3 -> 14 -> 2 -> 11 -> NULLExplanation: In the given list, the prime number nodes are 7, 11, 3, a
13 min read
Move the Kth Largest Fibonacci Number Node to the End of a Singly Linked List
Given a singly linked list containing integer values. The task is to find the Kth largest Fibonacci number within this list and move it to the end of the list. Examples: Input: 12 -> 11 -> 0 -> 5 -> 8 -> 13 -> 17 -> 21 -> NULL, K = 3Output: 12 -> 11 -> 0 -> 5 -> 13 -> 17 -> 21 -> 8 -> NULLExplanation:
12 min read
Why start + (end - start)/2 is preferable method for calculating middle of an array over (start + end)/2 ?
I am very sure that everyone is able to find middle index of array once you know start index and end index of array, but there are certain benefits of using start + (end - start)/2 over (start + end)/2, which are described below : The very first way of finding middle index is mid = (start + end)/2But there is a problem with this approach, what if t
8 min read
Sum of all elements in an array between zeros
Given an array arr[] of N integers, the task is to find the sum of all elements between two zeros in the given array. If possible, then print all the sum, else print "-1".Note: There is no continuous zero in the given array. Examples: Input: arr[] = { 1, 0, 3, 4, 0, 4, 4, 0, 2, 1, 4, 0, 3 } Output: 7 8 7 Explanation: The sum of elements between eve
7 min read
Minimum number of operations to move all uppercase characters before all lower case characters
Given a string str, containing upper case and lower case characters. In a single operations, any lowercase character can be converted to an uppercase character and vice versa. The task is to print the minimum number of such operations required so that the resultant string consists of zero or more upper case characters followed by zero or more lower
8 min read
Find the other end point of a line with given one end and mid
Given a midpoint of line(m1, m2) and one coordinate of a line (x1, y1), find the other end point(x2, y2) of a line. Examples: Input : x1 = –1, y1 = 2, and m1 = 3, m2 = –6 Output : x2 = 7, y2 = 10 Input : x1 = 6.4, y1 = 3 and m1 = –10.7, m2 = 4 Output : x2 = 3, y2 = 4 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the poi
4 min read