Skip to content

Instantly share code, notes, and snippets.

@Oliver-ke
Last active April 8, 2022 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oliver-ke/bc5cfb569a8b7552dbb63aaeb11ce8c5 to your computer and use it in GitHub Desktop.
Save Oliver-ke/bc5cfb569a8b7552dbb63aaeb11ce8c5 to your computer and use it in GitHub Desktop.
My daily kata

Two Sums

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

var twoSum = function(nums, target) {
    for (let i = 0; i < nums.length; i++) {
        const num = nums[i];
        const rest = nums.slice(i+1);
        for(let m = 0; m < rest.length; m++) {
            const subNum = rest[m];
            if(subNum + num === target) {
                const subIdx = m+i+1;
                return [i, subIdx];
            }
        }
    }
    return [];
};

Binary Search, firrst implementation

this assumes target must be in the array

const binarySeach = (list, target) => {
  let start = 0;
  let end = list.length - 1;
  let itemFound = false;
 
  
  while(start <= end) {
    const range = start + end;
    let midIdx = Math.round(range / 2);
    const value = list[midIdx];
    if(value === target) return midIdx;
    if(value > target) {
      end = midIdx;
    }
    if(value < target) {
      start = midIdx;
    }
  }
}

console.log(binarySeach([4,6,9,10,15,20,30], 1))

// keeping baseball game score /**

  1. read the current value,
  2. if value is int add to result and to cache
  3. else run conditions
  4. for "+", record the sum of the previous two scores
  5. for "D", record new score that is double the privouse score
  6. for "C", invalidate the previous score **/
const calPoint = (ops) => {
  const scores = [];
  const exceptions = ['+', 'D', 'C'];
  ops.forEach(val => {
    if(exceptions.includes(val)) {
      if(val === '+') {
        const twoItem = scores.slice(scores.length - 2);
        const sum = twoItem.reduce((a,b) => a + b);
        return scores.push(sum);
      }
      if(val === 'D') {
        const prevScore = scores[scores.length - 1];
        const double = prevScore * 2;
        return scores.push(double);
      }
      if(val === 'C') {
        return scores.pop();
      }
    }
    scores.push(val);
  });
  const result = scores.reduce((a,b) => a+b);
  return result;
}

// const res = calPoint([5, 2, 'C', 'D', '+']);
// console.log(res);

valid parenthesis

const isValid = (s) => {
    let map = {
        ")": "(",
        "}": "{",
        "]": "[",
    }
    const stack = [];
    const openings = ['[', '{', "("];
    for(let i = 0; i < s.length; i++) {
      if(openings.includes(s[i])) {
        stack.push(s[i]);
      } else if(stack[stack.length -1] === map[s[i]]) {
        stack.pop();
      } else return false;
    }
  return stack.length ? false : true;
}

const res = isValid('()');
console.log(res);

sock machant

function sockMerchant(n, ar) {
    // Write your code here
    let pairs = 0;
    const map = {};
    for(let i = 0; i < ar.length; i++) {
        map[ar[i]] = (map[ar[i]] || 0) + 1;
        if(map[ar[i]] === 2) {
            pairs += 1;
            map[ar[i]] = 0;
        } 
    }
    console.log(map);
    return pairs;
}

Class Implementation of Stack

class Stack {
  constructor() {
    this.top = 0;
    this.stack = [];
  }

  push(value) {
    this.stack[this.top] = value
    this.top++
  }

  pop() {
    if (this.top === 0) {
      return 'Stack is Empty'
    }
    this.top--
    const result = this.stack[this.top]
    this.stack = this.stack.splice(0, this.top)
    return result
  }

  size() {
    return this.top
  }

  peek() {
    return this.stack[this.top - 1]
  }

  view(output = value => console.log(value)) {
    for (let i = 0; i < this.top; i++) {
      output(this.stack[i])
    }
  }
}

Queue implementation with classes

class Queue {
  constructor(existing=[]) {
    this.length = existing.length;
    this.queue = existing;
  }

  enQueue(value) {
    this.length++
    this.queue.push(value);
  }

  deQueue() {
    if(!this.queue.length) {
      return 'No item in queue'
    }
    this.length--
    const qCopy = [...this.queue];
    qCopy.shift()
    this.queue = [...qCopy] ;
  }

  view() {
    return this.queue;
  }
}

An avid hiker keeps meticulous records of their hikes, path = [DDDUUUDDD]

function countingValleys(steps, path) {
    // Write your code here
    let strArr = path.split('')
    let count = 0
    let result = 0
    for(let step=0; step<steps; step++){
        if(count == 0 && strArr[step] === 'D'){
            count -= 1
            result += 1
        } else if(strArr[step] === 'D'){
            count -= 1
        } else {
            count += 1
        }
    }
    return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment