Snippets


Count number of 1 bits

A brute-force approach is to simply count the number of 1’s in the binary number:

function countOneBits(num) {
  // Convert number to a base-2 string
  const binaryString = num.toString(2)

  // Remove all 0's so it returns the number of 1's
  return binaryString.replace(/0/g, '').length
}

A bit-manipulation approach is to count how many times we eliminate 1’s in the binary number:

function countOneBits(num) {
  let count = 0

  while (num !== 0) {
    // Eliminate the least significant 1
    num = num & (num - 1)
    count++
  }

  return count
}

Find majority element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1: Input: [3,2,3] Output: 3

Example 2: Input: [2,2,1,1,1,2,2] Output: 2

Use hashmap to count the frequency of each element and return the element with the highest frequency:

function findMajorityElement(arr) {
  let freq = new Map()

  for (let i = 0; i < arr.length; i++) {
    const count = freq.get(arr[i]) || 0
    freq.set(arr[i], count + 1)
  }

  let maxKey
  let maxVal = Number.MIN_SAFE_INTEGER

  for (let [key, value] of freq.entries()) {
    if (value > maxVal) {
      maxVal = value
      maxKey = key
    }
  }

  return maxKey
}

Sort the array and return the element in middle:

function findMajorityElement(arr) {
  arr.sort((a, b) => a - b)
  const mid = Math.floor(arr.length / 2)
  return arr[mid]
}

Edit