Open In App

Generate all the numbers up to N in Lexicographical Order using Stack

Last Updated : 23 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, the task is to print all numbers up to N in Lexicographical order.

Examples:

Input: N = 20
Output: 1 10 11 12 13 14 15 16 17 18 19 2 3 4 5 6 7 8 9

Input: N = 5
Output: 1 2 3 4

Input: N = 19 
Output: 1 10 11 12 13 14 15 16 17 18 2 3 4 5 6 7 8 9 

Approach:

In order to solve the problem, follow the steps below:  

  • Initialize two stacks stackA and stackB. Insert 1 in String data type to stackA.
  • Then iterate from number 2 to N ( i = 2 to N-1 )
    • For each number, convert the current number to its string equivalent and check with the element at top of the stackA.
    • If the element at the top of stackA is lexicographically less than the current number:
      •  Then pop the element from stackA and push these popped elements to stackB till the peek element of stackA is lesser than the current number or till the stackA gets empty.
      • Push the current number in String form to stackA.
      • Then, pop all the elements in stackB and push them to stackA.
  • Now all numbers up to N have been pushed to stackA in string data type. Pop all elements from stackA until stackA gets empty.
  • Now all numbers are printed in lexicographical order.

Below is the implementation of the above approach:

C++

// C++ code

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

// Function to generate all numbers up to N
// in lexicographical order using Stack
void generateNumbersLexicographically(int n)
{
  // Initializing two stacks
  stack<string> stackA; //= new Stack<>();
  stack<string> stackB; // = new Stack<>();
  stackA.push("1");

  // Iterate from number 2 to N
  for (int i = 2; i < n; i++) {
    string currStr = to_string(i);
    if (stackA.top() < (currStr)) {

      // Compare current number to
      // top element of stackA.
      while (!stackA.empty()
             && stackA.top() < (currStr)) {
        string s = stackA.top();
        stackA.pop();
        stackB.push(s);
      }
      stackA.push(currStr);

      // Pop all elements from stackB
      // till stackB gets empty and
      // push them to stackA.
      while (!stackB.empty()) {
        string ss = stackB.top();
        stackB.pop();
        stackA.push(ss);
      }
    }

    // Current number is pushed to stackA
    // in String form.
    else {
      stackA.push(currStr);
    }
  }

  // Pop all the elements from stackA.
  // This popping process generates
  // all numbers up to N in
  // lexicographical order.
  while (stackA.size() > 0) {
    string ans = stackA.top();
    cout << ans << " ";
    stackA.pop();
  }
}

int main()
{

  int N = 20;

  // Function call
  generateNumbersLexicographically(N);

  return 0;
}
// This code is contributed by ksam24000

Java

// Java code to implement the approach

import java.util.*;

class GFG {

    // Function to generate all numbers up to N
    // in lexicographical order using Stack
    public static void
    generateNumbersLexicographically(int n)
    {
        // Initializing two stacks
        Stack<String> stackA = new Stack<>();
        Stack<String> stackB = new Stack<>();
        stackA.push("1");

        // Iterate from number 2 to N
        for (int i = 2; i < n; i++) {
            String currStr = Integer.toString(i);
            if (stackA.peek().compareTo(currStr) < 0) {

                // Compare current number to
                // top element of stackA.
                while (!stackA.isEmpty()
                       && stackA.peek().compareTo(currStr)
                              < 0) {
                    stackB.push(stackA.pop());
                }
                stackA.push(currStr);

                // Pop all elements from stackB
                // till stackB gets empty and
                // push them to stackA.
                while (!stackB.isEmpty()) {
                    stackA.push(stackB.pop());
                }
            }

            // Current number is pushed to stackA
            // in String form.
            else {
                stackA.push(currStr);
            }
        }

        // Pop all the elements from stackA.
        // This popping process generates
        // all numbers up to N in
        // lexicographical order.
        while (!stackA.isEmpty()) {
            System.out.print(stackA.pop() + " ");
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        int N = 20;

        // Function call
        generateNumbersLexicographically(N);
    }
}

Python3

# Python code to implement the approach

# Function to generate all numbers up to N
# in lexicographical order using Stack
def generateNumbersLexicographically(n):
    # Initializing two stacks
    stack_a = []
    stack_b = []
    stack_a.append("1")

    # Iterate from number 2 to N
    for i in range(2, n):
        curr_str = str(i)
        if stack_a[-1] < curr_str:

            # Compare current number to
            # top element of stack_a.
            while stack_a and stack_a[-1] < curr_str:
                stack_b.append(stack_a.pop())
            stack_a.append(curr_str)

            # Pop all elements from stack_b
            # till stack_b gets empty and
            # push them to stack_a.
            while stack_b:
                stack_a.append(stack_b.pop())
        else:
            # Current number is pushed to stack_a
            # in String form.
            stack_a.append(curr_str)

    # Pop all the elements from stack_a.
    # This popping process generates
    # all numbers up to N in
    # lexicographical order.
    result = []
    while stack_a:
        result.append(stack_a.pop())
    return result


if __name__ == "__main__":
    N = 20

    # Function call
    result = generateNumbersLexicographically(N)
    for i in range(len(result)):
        print(result[i], end=" ")

# This code is contributed by lokeshmvs21.

C#

// C# code to implement the approach
using System;
using System.Collections.Generic;

class GFG
{

  // Function to generate all numbers up to N
  // in lexicographical order using Stack
  public static void
    generateNumbersLexicographically(int n)
  {

    // Initializing two stacks
    Stack<string> stackA = new Stack<string>();
    Stack<string> stackB = new Stack<string>();
    stackA.Push("1");

    // Iterate from number 2 to N
    for (int i = 2; i < n; i++)
    {
      string currStr = i.ToString();
      if (string.Compare(stackA.Peek(), currStr) < 0)
      {
        // Compare current number to
        // top element of stackA.
        while (stackA.Count > 0
               && string.Compare(stackA.Peek(), currStr)
               < 0)
        {
          stackB.Push(stackA.Pop());
        }
        stackA.Push(currStr);

        // Pop all elements from stackB
        // till stackB gets empty and
        // push them to stackA.
        while (stackB.Count > 0)
        {
          stackA.Push(stackB.Pop());
        }
      }

      // Current number is pushed to stackA
      // in String form.
      else
      {
        stackA.Push(currStr);
      }
    }

    // Pop all the elements from stackA.
    // This popping process generates
    // all numbers up to N in
    // lexicographical order.
    while (stackA.Count > 0)
    {
      Console.Write(stackA.Pop() + " ");
    }
  }

  // Driver code
  public static void Main()
  {
    int N = 20;

    // Function call
    generateNumbersLexicographically(N);
  }
}

// This code is contributed by lokesh.

Javascript

        // JavaScript code to implement the approach

        // Function to generate all numbers up to N
        // in lexicographical order using Stack
        const generateNumbersLexicographically = (n) => {
            // Initializing two stacks
            let stackA = [];
            let stackB = [];
            stackA.push("1");

            // Iterate from number 2 to N
            for (let i = 2; i < n; i++) {
                let currStr = i.toString();
                if (stackA[stackA.length - 1] < currStr) {

                    // Compare current number to
                    // top element of stackA.
                    while (stackA.length != 0
                        && stackA[stackA.length - 1] < currStr) {
                        stackB.push(stackA.pop());
                    }
                    stackA.push(currStr);

                    // Pop all elements from stackB
                    // till stackB gets empty and
                    // push them to stackA.
                    while (stackB.length != 0) {
                        stackA.push(stackB.pop());
                    }
                }

                // Current number is pushed to stackA
                // in String form.
                else {
                    stackA.push(currStr);
                }
            }

            // Pop all the elements from stackA.
            // This popping process generates
            // all numbers up to N in
            // lexicographical order.
            while (stackA.length != 0) {
                console.log(`${stackA.pop()} `);
            }
        }

        // Driver code
        let N = 20;

        // Function call
        generateNumbersLexicographically(N);

        // This code is contributed by rakeshsahni
Output

1 10 11 12 13 14 15 16 17 18 19 2 3 4 5 6 7 8 9 

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

Related Articles:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads