Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Last active July 28, 2023 05:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpaul/0ececa9bf6c42974693be4dcf9dbcfba to your computer and use it in GitHub Desktop.
Save alexpaul/0ececa9bf6c42974693be4dcf9dbcfba to your computer and use it in GitHub Desktop.
HackerRank Practice Questions

HackerRank Questions / Solutions

Swift Solution

// https://www.hackerrank.com/challenges/missing-numbers/problem

func missingNumbers(arr: [Int], brr: [Int]) -> [Int] {
  guard !arr.isEmpty else {
    return Array(Set(brr)).sorted()
  }
  
  var result:[Int] = [Int]()
  
  var brrDictionary = [Int: Int]()
  var arrDictionary = [Int: Int]()
  
  for num in brr {
    if let count = brrDictionary[num] {
      brrDictionary[num] = count + 1
    } else {
      brrDictionary[num] = 1
    }
  }
  
  
  for num in arr {
    if let count = arrDictionary[num] {
      arrDictionary[num] = count + 1
    } else {
      arrDictionary[num] = 1
    }
  }
  
  for (key,value) in brrDictionary {
    if arrDictionary[key] == nil {
      result.append(key)
    } else {
      if arrDictionary[key] != value{
        result.append(key)
      }
    }
  }
  
  return result.sorted()
}

JavaScript Solution

function missingNumbers(arr, brr) {
  const brrFreq = {}
  for (let num of brr) {
    if (!brrFreq.hasOwnProperty(num)) {
      brrFreq[num] = 1
    } else {
      brrFreq[num]++
    }
  }
  // substract the elements that are present in arr from brrFreq
  for (let num of arr) {
    brrFreq[num]--
  }
  const missing = []
  for (let numKey in brrFreq) {
    if (brrFreq[numKey] !== 0) { // if there's any number whose count is not 0 then its missing
      missing.push(numKey)
    }
  }
  return missing.sort((a, b) => a - b)
}

Swift Solution

// https://www.hackerrank.com/challenges/icecream-parlor/problem

func icecreamParlor(m: Int, arr: [Int]) -> [Int] {
  var dict = [Int: Int]()
  for i in 0..<arr.count {
    let currentValue = arr[i]
    if let index = dict[m - currentValue] {
      return [index + 1, i + 1 ]
    }else {
      dict[currentValue] = i
    }
  }
  
  return []
}

JavaScript Solution

function icecreamParlor(m, arr) {
  const seen = {}
  for (let i = 0; i < arr.length; i++) {
    let num = arr[i]
    let diff = m - num;
    if (seen.hasOwnProperty(diff)) {
      return [seen[diff] + 1, i + 1]
    } else {
      seen[num] = i
    }
  }
}

Resources

@fluushx
Copy link

fluushx commented Aug 12, 2021

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment