Related Articles

Related Articles

Sort the given stack elements based on their modulo with K
  • Difficulty Level : Basic
  • Last Updated : 11 Nov, 2020

Given a stack of integers and an integer K, the task is to sort the elements of the given stack using another stack in the increasing order of their modulo with K. If two numbers have the same remainder then the smaller number should come first.
Examples 

Input: stack = {10, 3, 2, 6, 12}, K = 4 
Output: 12 2 6 10 3 
{12, 2, 6, 10, 3} is the required sorted order as the modulo 
of these elements with K = 4 is {2, 3, 2, 2, 0}

Input: stack = {3, 4, 5, 10, 11, 1}, K = 3 
Output: 3 1 4 10 5 11 
 

Approach: An approach to sort the elements of the stack using another temporary stack has been discussed in this article, the same approach can be used here to sort the elements based on their modulo with K, the only difference is that when the elements being compared give the same modulo value then they will be compared based on their values.

Below is the implementation of the above approach:  

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the
// above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the stack using
// another stack based on the
// values of elements modulo k
void sortStack(stack<int>& input, int k)
{
    stack<int> tmpStack;
 
    while (!input.empty()) {
 
        // Pop out the first element
        int tmp = input.top();
        input.pop();
 
        // While temporary stack is not empty
        while (!tmpStack.empty()) {
            int tmpStackMod = tmpStack.top() % k;
            int tmpMod = tmp % k;
 
            // The top of the stack modulo k is
            // greater than (temp & k) or if they
            // are equal then compare the values
            if ((tmpStackMod > tmpMod)
                || (tmpStackMod == tmpMod
                    && tmpStack.top() > tmp)) {
 
                // Pop from temporary stack and push
                // it to the input stack
                input.push(tmpStack.top());
                tmpStack.pop();
            }
            else
                break;
        }
 
        // Push temp in tempory of stack
        tmpStack.push(tmp);
    }
 
    // Push all the elements in the original
    // stack to get the ascending order
    while (!tmpStack.empty()) {
        input.push(tmpStack.top());
        tmpStack.pop();
    }
 
    // Print the sorted elements
    while (!input.empty()) {
        cout << input.top() << " ";
        input.pop();
    }
}
 
// Driver code
int main()
{
    stack<int> input;
    input.push(10);
    input.push(3);
    input.push(2);
    input.push(6);
    input.push(12);
 
    int k = 4;
 
    sortStack(input, k);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the
// above approach
import java.io.*;
import java.util.*;
 
class GFG{
   
// Function to sort the stack using
// another stack based on the
// values of elements modulo k
static void sortStack(Stack<Integer> input, int k)
{
    Stack<Integer> tmpStack = new Stack<Integer>();
 
    while (!input.isEmpty())
    {
         
        // Pop out the first element
        int tmp = input.peek();
        input.pop();
 
        // While temporary stack is not empty
        while (!tmpStack.isEmpty())
        {
            int tmpStackMod = tmpStack.peek() % k;
            int tmpMod = tmp % k;
 
            // The top of the stack modulo k is
            // greater than (temp & k) or if they
            // are equal then compare the values
            if ((tmpStackMod > tmpMod) ||
                (tmpStackMod == tmpMod &&
                 tmpStack.peek() > tmp))
            {
                 
                // Pop from temporary stack and push
                // it to the input stack
                input.push(tmpStack.peek());
                tmpStack.pop();
            }
            else
                break;
        }
 
        // Push temp in tempory of stack
        tmpStack.push(tmp);
    }
 
    // Push all the elements in the original
    // stack to get the ascending order
    while (!tmpStack.isEmpty())
    {
        input.push(tmpStack.peek());
        tmpStack.pop();
    }
 
    // Print the sorted elements
    while (!input.empty())
    {
        System.out.print(input.peek() + " ");
        input.pop();
    }
}
 
// Driver code
public static void main(String args[])
{
    Stack<Integer> input = new Stack<Integer>();
    input.push(10);
    input.push(3);
    input.push(2);
    input.push(6);
    input.push(12);
 
    int k = 4;
 
    sortStack(input, k);
}
}
 
// This code is contributed by adityapande88

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the
# above approach
 
# Function to sort the stack using
# another stack based on the
# values of elements modulo k
def sortStack(input1, k):
 
    tmpStack = []
 
    while (len(input1) != 0):
 
        # Pop out the first element
        tmp = input1[-1]
        input1.pop()
 
        # While temporary stack is
        # not empty
        while (len(tmpStack) != 0):
            tmpStackMod = tmpStack[-1] % k
            tmpMod = tmp % k
 
            # The top of the stack modulo
            # k is greater than (temp & k)
            # or if they are equal then
            # compare the values
            if ((tmpStackMod > tmpMod) or
                (tmpStackMod == tmpMod and
                 tmpStack[-1] > tmp)):
 
                # Pop from temporary stack
                # and push it to the input
                # stack
                input1.append(tmpStack[-1])
                tmpStack.pop()
            else:
                break
 
        # Push temp in tempory of stack
        tmpStack.append(tmp)
 
    # Push all the elements in
    # the original stack to get
    # the ascending order
    while (len(tmpStack) != 0):
        input1.append(tmpStack[-1])
        tmpStack.pop()
 
    # Print the sorted elements
    while (len(input1) != 0):
        print(input1[-1], end = " ")
        input1.pop()
 
# Driver code
if __name__ == "__main__":
 
    input1 = []
    input1.append(10)
    input1.append(3)
    input1.append(2)
    input1.append(6)
    input1.append(12)
    k = 4
    sortStack(input1, k)
 
# This code is contributed by Chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the
// above approach
using System;
using System.Collections;
class GFG{
   
// Function to sort the stack using
// another stack based on the
// values of elements modulo k
static void sortStack(Stack input,
                      int k)
{
  Stack tmpStack = new Stack();
 
  while(input.Count != 0)
  {
    // Pop out the first element
    int tmp = (int)input.Peek();
    input.Pop();
 
    // While temporary stack is not empty
    while (tmpStack.Count != 0)
    {
      int tmpStackMod = (int)tmpStack.Peek() % k;
      int tmpMod = tmp % k;
 
      // The top of the stack modulo k is
      // greater than (temp & k) or if they
      // are equal then compare the values
      if ((tmpStackMod > tmpMod) ||
          (tmpStackMod == tmpMod &&
          (int)tmpStack.Peek() > tmp))
      {
        // Pop from temporary stack and push
        // it to the input stack
        input.Push((int)tmpStack.Peek());
        tmpStack.Pop();
      }
      else
        break;
    }
 
    // Push temp in tempory of stack
    tmpStack.Push(tmp);
  }
 
  // Push all the elements in the original
  // stack to get the ascending order
  while (tmpStack.Count != 0)
  {
    input.Push((int)tmpStack.Peek());
    tmpStack.Pop();
  }
 
  // Print the sorted elements
  while (input.Count != 0)
  {
    Console.Write((int)input.Peek() + " ");
    input.Pop();
  }
}
 
// Driver Code
public static void Main(string[] args)
{
  Stack input = new Stack();
  input.Push(10);
  input.Push(3);
  input.Push(2);
  input.Push(6);
  input.Push(12);
  int k = 4;
  sortStack(input, k);
}
}
 
// This code is contributed by rutvik_56

chevron_right


Output: 

12 2 6 10 3







 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :