Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Sourav Singh
Wrong Solution execution for golang

Sourav Singh

Oct 6, 2024

Though the output is right, logic used for golang solution is wrong. I printed out the stack for the code for each outer for loop iteration and the output is given below:

Issue in code line: for !tmpStack.Empty() && tmp1.(int) > tmp.(int) {...

tmpStack:: {[23]} input: {[34 3 31 98 92]} tmpStack:: {[23 92]} input: {[34 3 31 98]} tmpStack:: {[23 92 98]} input: {[34 3 31]} tmpStack:: {[31]} input: {[34 3 98 92 23]} tmpStack:: {[23]} input: {[34 3 98 92 31]} tmpStack:: {[23 31]} input: {[34 3 98 92]} tmpStack:: {[23 31 92]} input: {[34 3 98]} tmpStack:: {[23 31 92 98]} input: {[34 3]} tmpStack:: {[3]} input: {[34 98 92 31 23]} tmpStack:: {[3 23]} input: {[34 98 92 31]} tmpStack:: {[3 23 31]} input: {[34 98 92]} tmpStack:: {[3 23 31 92]} input: {[34 98]} tmpStack:: {[3 23 31 92 98]} input: {[34]} tmpStack:: {[34]} input: {[98 92 31 23 3]} tmpStack:: {[3]} input: {[98 92 31 23 34]} tmpStack:: {[3 34]} input: {[98 92 31 23]} tmpStack:: {[23]} input: {[98 92 31 34 3]} tmpStack:: {[3]} input: {[98 92 31 34 23]} tmpStack:: {[3 23]} input: {[98 92 31 34]} tmpStack:: {[3 23 34]} input: {[98 92 31]} tmpStack:: {[31]} input: {[98 92 34 23 3]} tmpStack:: {[3]} input: {[98 92 34 23 31]} tmpStack:: {[3 31]} input: {[98 92 34 23]} tmpStack:: {[23]} input: {[98 92 34 31 3]} tmpStack:: {[3]} input: {[98 92 34 31 23]} tmpStack:: {[3 23]} input: {[98 92 34 31]} tmpStack:: {[3 23 31]} input: {[98 92 34]} tmpStack:: {[3 23 31 34]} input: {[98 92]} tmpStack:: {[3 23 31 34 92]} input: {[98]} tmpStack:: {[3 23 31 34 92 98]} input: {[]} Sorted Output: 98 92 34 31 23 3

Better Solution: func (s *Solution) sortStack(input Stack) Stack { tmpStack := NewStack() // ToDo: Write Your Code Here. for !input.Empty() { elem, _ := input.Pop()

for !tmpStack.Empty() {
  top, _ := tmpStack.Top()
  if top.(int) > elem.(int) {
    tmpStack.Pop()
    input.Push(top)
  } else {
    break
  }
}
tmpStack.Push(elem) 

} return tmpStack }

0

0

Comments
Comments

On this page