Skip to content

Add HashMap and QueueStack implementations#2444

Open
Balaviknesh wants to merge 1 commit intosuper30admin:masterfrom
Balaviknesh:master
Open

Add HashMap and QueueStack implementations#2444
Balaviknesh wants to merge 1 commit intosuper30admin:masterfrom
Balaviknesh:master

Conversation

@Balaviknesh
Copy link

No description provided.

@super30admin
Copy link
Owner

Strengths:

  • You have correctly understood the approach of using two stacks to implement a queue.
  • The transfer of elements from inStack to outStack when outStack is empty is correctly implemented.
  • The time and space complexity are optimal.

Areas for improvement:

  • The class should be named "MyQueue" as per the problem statement. The example code in the problem uses "MyQueue", and the test cases will expect that class name.
  • You should handle the case when the queue is empty in pop and peek. Although the problem states that all calls are valid, it is good practice to handle edge cases to avoid runtime exceptions. You can either throw an exception with a message or return a sentinel value (like -1) as in the reference solution. However, since the problem says all calls are valid, you can also assume it's safe, but without handling, it will crash.
  • There is code duplication in pop and peek for transferring elements. You can refactor by having a helper function or by having peek handle the transfer and then pop uses peek. This makes the code cleaner and avoids duplication.
  • The solution for HashMap is included in the same file, which is not required for this problem. Please ensure you only submit the relevant code for the problem.

Suggested improvements for the QueueStack class (renamed to MyQueue):

class MyQueue {
    private val inStack = mutableListOf<Int>()
    private val outStack = mutableListOf<Int>()

    fun push(x: Int) {
        inStack.add(x)
    }

    fun pop(): Int {
        peek() // Ensure outStack has the front element
        return outStack.removeAt(outStack.size - 1)
    }

    fun peek(): Int {
        if (outStack.isEmpty()) {
            while (inStack.isNotEmpty()) {
                outStack.add(inStack.removeAt(inStack.size - 1))
            }
        }
        return outStack[outStack.size - 1]
    }

    fun empty(): Boolean {
        return inStack.isEmpty() && outStack.isEmpty()
    }
}

This reduces duplication and ensures that both pop and peek behave consistently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants