Advertisement
samimwebdev

Problem solving approach

Jun 17th, 2022
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //sum 2 numbers and return the result
  2. //addition of two numbers
  3. //input - 10, 15 //output - 25
  4. //input 20, 30  //output 50
  5. //input 20.33, 40.5345 //output - 60
  6.  
  7. // function sum(num1, num2) {
  8. //   //output
  9. //   return num1 + num2
  10. // }
  11. // sum(10, 20)
  12.  
  13. //count the character
  14. //input - string 'Hello' output- {h: 1, e: 1, l: 2, o: 1}
  15. //input - string 'greet' output- {g: 1, r: 1, e: 2, t: 1}
  16.  
  17. //time complexity O(n)
  18. //space complexity O(n)
  19. // function countCharacter(str) {
  20. //creating an object for tracking the frequency of element
  21. //   const hashMap = {}
  22.  
  23. // looping the input anf generalize the case
  24. //   const normalizeStr = str.toLowerCase()
  25. //   for (let i = 0; i < normalizeStr.length; i++) {
  26. // if there is any space ignore it
  27. // const char = normalizeStr[i]
  28. // if (char === ' ') continue
  29. //ternary
  30. // char in hashMap ?  hashMap[char] = hashMap[char] + 1 : hashMap[char] = 1
  31. // hashMap[char] = (hashMap[char] || 0) + 1
  32. // if (char in hashMap) {
  33. //   //check if the element exists on the object increment the existent count value
  34. //   hashMap[char] = hashMap[char] + 1
  35. // } else {
  36. //   // if element not present assign the value 1
  37. //   hashMap[char] = 1
  38. // }
  39. //   }
  40. //   return hashMap
  41. // }
  42. // console.log(countCharacter('He llo'))
  43.  
  44. //check the element of first array 2nd array
  45. //if the element exists
  46. //return true
  47. //otherwise false
  48.  
  49. // input- arr1-['a', 'b', 'c'] arr2-[1, 2, 3, 'z'] //false
  50. // input- arr1-['a', 'b', 'c'] arr2-[1, 2, 3, 'c'] //true
  51. //time complexity O(n * m)
  52. //space complexity O(1)
  53. // function isElementExists(arr1, arr2) {
  54. //     //flag variable
  55. //     let exists = false
  56. //     for(let elm of arr1){
  57. //        if(arr2.includes(elm)){
  58. //         exists = true
  59. //         break
  60. //        }
  61. //     }
  62.  
  63. //     return exists
  64. //   }
  65.  
  66. // time complexity O(n + m)
  67. //space complexity O(n)
  68. function isElementExists(arr1, arr2) {
  69.   const frequencyCounter = {}
  70.   for (let elm of arr1) {
  71.     frequencyCounter[elm] = true
  72.   }
  73.  
  74.   for (let elm of arr2) {
  75.     if (elm in frequencyCounter) {
  76.       return true
  77.     }
  78.   }
  79. }
  80.  
  81. console.log(isElementExists(['a', 'b', 'c'], [1, 2, 3, 'b']))
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement