Discover the beauty of data structure stack

Time:2021-4-14

Discover the beauty of data structure stack

In the world of code, stack is a very important data structure no matter what language it is.
Stack overflow, the world-famous code query community, takes stack overflow as a part of the website name.
In the process of writing code or debugging, I believe you have felt the joy of skipping in the world of function call stack.
In the school brush OJ, brush leetcode, enter the society to participate in the written interview process, I believe you also feel the stack powerful and easy to use.

This blog is very suitable for students with very weak data structure foundation. Students with solid foundation are also welcome to correct and exchange.
This blog post will be great if you’ve never felt it before~

  • What is stack?

    • Data structure diagram
    • Stack in and stack out diagram
  • Stack in JavaScript

    • How to find out the characteristics of LIFO stack in JS?
    • How to realize a minimum stack?
    • Graphical function call stack
  • Leetcode stack solution problem

    • 20. Effective brackets (easy)
    • Sum (easy. 67)
    • 905. Sort arrays by parity (easy)
    • 56. Medium
    • 75. Color classification (medium)
    • 228. Medium
    • 739. Daily temperature (medium)
  • How to solve interview questions

    • Implement a bigint

What is stack?

  • Stack is a last in first out (LIFO) data structure
  • The stack is usually traversed by DFS (depth first search)
  • You can usually use top / bottom to represent the top and bottom of the stack

Data structure diagram

Discover the beauty of data structure stack

Stack in and stack out diagram

Discover the beauty of data structure stack

Stack in JavaScript

How to find out the characteristics of LIFO stack in JS?

We are familiar with the following structure, which instantly reflects the characteristics of LIFO stack.

//Define a stack
let stack = [1,2,3];
//Enter the stack
stack.push(4); // stack [1,2,3,4]
//Out of the stack
stack.pop(); // 4 stack [1,2,3]

How to realize a minimum stack?

Design a stack that supports push, pop, top operations and can retrieve the smallest elements in a constant time.

Push (x) - push element x onto the stack.
Pop () -- delete the elements at the top of the stack.
Top () -- get the top element of the stack.
Getmin () -- retrieve the smallest element in the stack.
var MinStack = function() {
  this.stack = [];
};
MinStack.prototype.push = function(x) {
  this.stack.push(x);
};
MinStack.prototype.pop = function() {
  return this.stack.pop();
};
MinStack.prototype.top = function() {
  return this.stack[this.stack.length - 1];
};
MinStack.prototype.getMin = function() {
  return Math.min(...this.stack);
};

Title:https://leetcode-cn.com/probl…
Solution:https://github.com/FrankKai/l…

Graphical function call stack

Discover the beauty of data structure stack
Function is called from frames stack.

function foo(){
    let a = 10;
    return a + b + 11
}
function bar(x){
    let y = 3;
    return foo(x*y);
}
console.log (bar (7)); // returns 42

Process disassembly:

  • When the bar is called, the first frame containing the arguments of the bar and the local variables is created
  • When bar calls foo, the second frame containing foo arguments and local variables is created successfully and pushed to the top
  • When foo returns, the top frame element pops out of the stack (leaving the bar in the stack)
  • When the bar returns, the stack is cleared

Visual disassembly:

Discover the beauty of data structure stack

Discover the beauty of data structure stack

Discover the beauty of data structure stack

Leetcode stack solution problem

  • 20. Effective brackets (easy)
  • Sum (easy. 67)
  • 905. Sort arrays by parity (easy)
  • 56. Medium
  • 75. Color classification (medium)
  • 228. Medium
  • 739. Daily temperature (medium)

20. Effective brackets (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

/**
   *Solution 2: stack
   *1. Build a stack
   *2. Stack all open brackets in turn
   *3. Match with the open bracket at the top of the stack when the closed bracket is encountered
   *3.1 if the match is up, exit the stack and continue
   *3.2 does not match, return false
   *4. The stack after traversal should be empty, otherwise it is invalid
   */
var isValid = function(s) {
  var bracketsMap = {
    "(": ")",
    "{": "}",
    "[": "]"
  };
  var openBrackets = Object.keys(bracketsMap);
  var closeBrackets = Object.values(bracketsMap);
  var stack = [];
  var sArr = s.split("");
  for (var i = 0; i < sArr.length; i++) {
    if (openBrackets.indexOf(sArr[i]) !== -1) {
      stack.push(sArr[i]);
    } else if (closeBrackets.indexOf(sArr[i]) !== -1) {
      var top = stack[stack.length - 1];
      if (sArr[i] === bracketsMap[top]) {
        stack.pop();
      } else {
        return false;
      }
    }
  }
  return stack.length === 0;
}

Sum (easy. 67)

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function (a, b) {
    /**
     *Solution 2: stack
     *Time complexity: O (n)
     *Performance: 56ms, 35.5mb
     */
    let aArr = a.split("");
    let bArr = b.split("");
    let stack = [];
    let count = 0;
    while (aArr.length !== 0 || bArr.length !== 0) {
        let aPop = aArr.pop() || 0;
        let bPop = bArr.pop() || 0;
        let stackBottom = 0;
        if (stack.length > count) {
            stackBottom = stack.shift() || 0;
        }
        let sum = parseInt(aPop) + parseInt(bPop) + parseInt(stackBottom)
        if (sum <= 1) {
            stack.unshift(sum);
        } else {
            stack.unshift(sum - 2);
            stack.unshift(1);
        }
        count++;
    }
    return stack.join("");
};

905. Sort arrays by parity (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

/**
 * @param {number[]} A
 * @return {number[]}
 */
var sortArrayByParity = function (A) {
  /**
   *The solution of stack head and stack tail is enough
   *Even stack bottom push unshift
   *Odd top push
   */
  var stack = [];
  for (var i = 0; i < A.length; i++) {
    if (A[i] % 2 === 0) {
      stack.unshift(A[i]);
    } else {
      stack.push(A[i]);
    }
  }
  return stack;
};

56. Medium

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function (intervals) {
  /**
   *Solution 1: sort + stack
   *Performance: 88ms 36.3mb
   *Thinking:
   *Push interval empty stack or arr [0] is greater than the last interval closed stack
   *The overlay arr [0] is less than the last interval of the stack
   *  */
  intervals.sort((a, b) => a[0] - b[0]);
  let stack = [];
  for (let i = 0; i < intervals.length; i++) {
    let currrentInterval = intervals[i];
    let stackLastItem = stack[stack.length - 1];
    if (stack.length === 0 || currrentInterval[0] > stackLastItem[1]) {
      stack.push(currrentInterval);
    } else if (currrentInterval[0] <= stackLastItem[1]) {
      stackLastItem[1] = Math.max(stackLastItem[1], currrentInterval[1]);
    }
  }
  return stack;
};

75. Color classification (medium)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var sortColors = function (nums) {
  /**
   *Solution 1: recursive stack
   *Performance: 64ms 35.1mb
   */
  var length = nums.length;
  var countHead = arguments[1] || 0;
  var countTail = arguments[2] || 0;
  for (var i = countHead || 0; i < length - countTail; i++) {
    if (nums[i] === 0) {
      countHead++;
      nums.unshift ( nums.splice (I, 1)); // increasing if (I! = = 0) will reduce 10ms performance
      return sortColors(nums, countHead, countTail);
    } else if (nums[i] === 2) {
      countTail++;
      nums.push(nums.splice(i, 1));
      return sortColors(nums, countHead, countTail);
    }
  }
  return nums;
}

228. Medium

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

/**
 * @param {number[]} nums
 * @return {string[]}
 */
var summaryRanges = function (nums) {
  /**
   *Solution 1: sort + stack
   *Performance: 52ms 33.7mb
   */
  nums.sort((a, b) => a - b);
  let stack = [];
  let result = [];
  for (let i = 0; i < nums.length; i++) {
    if (stack.length === 0 || nums[i] - stack[stack.length - 1] === 1) {
      stack.push(nums[i]);
    } else {
      stackToResult();
      stack = [];
      stack.push(nums[i]);
    }
    if (i === nums.length - 1) {
      stackToResult();
    }
  }
  function stackToResult() {
    if (stack.length > 1) {
      result.push(`${stack[0]}->${stack[stack.length - 1]}`);
    } else {
      result.push(`${stack[0]}`);
    }
  }
  return result;
};

739. Daily temperature (medium)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

/**
   *Solution 2: stack + recursion 1132ms 19.96% 59.2mb 11.76%
   *Thinking:
   *1. Get the bottom of stack elements by shift
   *2. Traverse the remaining temperature in the stack
   *If the temperature is higher than the stack bottom temperature
   *Storage I + 1
   *Recursive next stack
   *If the temperature is less than or equal to the stack bottom temperature
   *If traversal to the last one does not appear larger
   *Storage 0
   *Next stack
   *3. The last temperature must be 0 in any case
   */
var dailyTemperatures = function(T) {
  if (T.length < 1 || T.length > 30000) return false;
  var result = arguments[1] || [];
  var bottom = T.shift();
  for (var i = 0; i < T.length; i++) {
    var t = T[i];
    if (t > bottom) {
      result.push(i + 1);
      return dailyTemperatures(T, result);
    } else {
      if (i === T.length - 1) {
        result.push(0);
        return dailyTemperatures(T, result);
      }
    }
  }
  result.push(0);
  return result;
}

How to solve interview questions

Implement a bigint

Realize the addition of large integers, greater than Number.MAX_ Value, bigint cannot be used directly.

/**
*Please implement large integers (possibly larger than Number.MAX_ Value (large) addition
// your code goes here
var bigint1 = new BigInt('1231230');
var bigint2 = new BigInt('12323123999999999999999999999999999999999999999999999991');
console.log(bigint1.plus(bigint2))
*/
function BigInt(value) {
  this.value = value;
}

BigInt.prototype.plus = function (bigint) {
  let aArr = this.value.split("");
  let bArr = bigint.value.split("");
  let stack = [];
  let count = 0;
  while (aArr.length !== 0 || bArr.length !== 0) {
    let aPop = aArr.pop() || 0;
    let bPop = bArr.pop() || 0;
    let stackBottom = 0;
    if (stack.length > count) {
      stackBottom = stack.shift();
    }
    let sum = parseInt(aPop) + parseInt(bPop) + parseInt(stackBottom);
    if (sum < 10) {
      stack.unshift(sum);
    } else if (sum >= 10) {
      stack.unshift(sum - 10);
      stack.unshift(1);
    }
    count++;
  }
  return stack.join("");
};

We are looking forward to communicating with you and making progress together. Welcome to join the technical discussion group which is closely related to front-end development

Discover the beauty of data structure stack

Strive to be an excellent front end engineer!

Recommended Today

Libp2p RS version 0.3.0 introduction

V0.3.0 released on 4.23, usingAsyncRead & AsyncWriteTo replace ourReadEx & WriteEx & SplitEx; SimplifiedKad/DHTImplementation logic. modify ReadEx & WriteEx & SplitEx: At first we tried to useasync-traitTo define their own IO operationsTraitFor more pure useasync/awaitTo write code. withReadExFor example, it is roughly as follows: #[async_trait] pub trait ReadEx { async fn read(&mut self, buf: &mut […]