Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //sum 2 numbers and return the result
- //addition of two numbers
- //input - 10, 15 //output - 25
- //input 20, 30 //output 50
- //input 20.33, 40.5345 //output - 60
- // function sum(num1, num2) {
- // //output
- // return num1 + num2
- // }
- // sum(10, 20)
- //count the character
- //input - string 'Hello' output- {h: 1, e: 1, l: 2, o: 1}
- //input - string 'greet' output- {g: 1, r: 1, e: 2, t: 1}
- //time complexity O(n)
- //space complexity O(n)
- // function countCharacter(str) {
- //creating an object for tracking the frequency of element
- // const hashMap = {}
- // looping the input anf generalize the case
- // const normalizeStr = str.toLowerCase()
- // for (let i = 0; i < normalizeStr.length; i++) {
- // if there is any space ignore it
- // const char = normalizeStr[i]
- // if (char === ' ') continue
- //ternary
- // char in hashMap ? hashMap[char] = hashMap[char] + 1 : hashMap[char] = 1
- // hashMap[char] = (hashMap[char] || 0) + 1
- // if (char in hashMap) {
- // //check if the element exists on the object increment the existent count value
- // hashMap[char] = hashMap[char] + 1
- // } else {
- // // if element not present assign the value 1
- // hashMap[char] = 1
- // }
- // }
- // return hashMap
- // }
- // console.log(countCharacter('He llo'))
- //check the element of first array 2nd array
- //if the element exists
- //return true
- //otherwise false
- // input- arr1-['a', 'b', 'c'] arr2-[1, 2, 3, 'z'] //false
- // input- arr1-['a', 'b', 'c'] arr2-[1, 2, 3, 'c'] //true
- //time complexity O(n * m)
- //space complexity O(1)
- // function isElementExists(arr1, arr2) {
- // //flag variable
- // let exists = false
- // for(let elm of arr1){
- // if(arr2.includes(elm)){
- // exists = true
- // break
- // }
- // }
- // return exists
- // }
- // time complexity O(n + m)
- //space complexity O(n)
- function isElementExists(arr1, arr2) {
- const frequencyCounter = {}
- for (let elm of arr1) {
- frequencyCounter[elm] = true
- }
- for (let elm of arr2) {
- if (elm in frequencyCounter) {
- return true
- }
- }
- }
- console.log(isElementExists(['a', 'b', 'c'], [1, 2, 3, 'b']))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement