HashTable : (First recurring char)

Run Settings
LanguageJavaScript
Language Version
Run Command
//Google Question //Given an array = [2,5,1,2,3,5,1,2,4]: //It should return 2 //Given an array = [2,1,1,2,3,5,1,2,4]: //It should return 1 //Given an array = [2,3,4,5]: //It should return undefined let array = [2,5,5,2] //We will learn more about time complaxcity of below code like what is TC for map.has() methos function firstRecurringCharacter(input) { let map = new Map(); for(let i=0;i<input.length;i++){ if(map.has(input[i])){ return input[i] }else{ map.set(input[i],true) } } return undefined } let data = firstRecurringCharacter(array) console.log(data) //we can do above thing even without using map methods. function firstRecuringCharWithSimpleObj(input){ let map = {} for(let i = 0; i < input.length ; i++){ if(map[input[i]] !== undefined){ return input[i]; }else { map[input[i]] = true } } return undefined } let mapObjSolution = firstRecuringCharWithSimpleObj([2,5,2]) console.log(mapObjSolution) // Find count of all recurring count function findAllRecurringCount(input) { let map = new Map(); console.log(input) for(let i=0;i<input.length;i++){ if(map.has(input[i])){ map.set(input[i],map.get(input[i])+1) }else{ map.set(input[i],1) } } return map; } let mapRecurring = findAllRecurringCount(array) console.log(mapRecurring) /// First recuring multi loop solution /* * In case of multiple loops always means always thing about from where we need to start loop not always from zero bhai */ function firstRecuring(input){ let maxDiff = Infinity let val = Infinity for(let i = 0 ; i < input.length ;i++){ for(let j = i+1; j < input.length ; j++){ if(input[i] === input[j]){ let currentDiff = j - i; if(currentDiff < maxDiff){ maxDiff = currentDiff; val = input[j] } } } } return val } console.log(firstRecuring([2,5,5,2])) // Good things about hashmap : Fast lookups,Fast Inserts and Flexible Keys // Bad things about hashmaps : unordered , slow key iteration
Editor Settings
Theme
Key bindings
Full width
Lines