Kony India Private Limited Interview Question for Software Engineer / Developers


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
0
of 0 vote

The idea is that when you push a new item, add a variable to store the max seen thus far for that current point in time. That way each item in stack has maxSoFar variable which you can query. In javascript code:

function Stack() {
  this.stack = [];
  this._maxSoFar = -Infinity;
}

Stack.prototype.push = function(x) {
  this.stack.push( {
    value: x,
    max: Math.max(x, this._maxSoFar)
  });
  
  this._maxSoFar = Math.max(x, this._maxSoFar)
}

Stack.prototype.pop = function() {
  return this.stack.pop();
}

Stack.prototype.getMax = function() {
  return this.stack.length ? this.stack[this.stack.length - 1].max : -Infinity;
}

Stack.prototype._debugGetStackValues = function() {
  return this.stack.map(function(item) { return item.value; })
}

var tests = [
  {value: 1, maxExpected: 1},
  {value: 2, maxExpected: 2},
  {value: 5, maxExpected: 5},
  {value: 3, maxExpected: 5},
  {value: 2, maxExpected: 5},
  {value: 9, maxExpected: 9},
  {value: 2, maxExpected: 9},
];


var stack = new Stack();
tests.forEach(function(item) {
  stack.push(item.value);
});

tests.reverse().forEach(function(item) {
  console.log(stack._debugGetStackValues() + ': max =>' + stack.getMax());
  stack.pop();
});

/* output
 "1,2,5,3,2,9,2: max =>9"
 "1,2,5,3,2,9: max =>9"
 "1,2,5,3,2: max =>5"
 "1,2,5,3: max =>5"
 "1,2,5: max =>5"
 "1,2: max =>2"
 "1: max =>1"
*/

- tnutty2k8 September 20, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More