Hackerrank: Sherlock and the Valid String Solution
Approach
Build 2 hash map of
- occurence of character
- occurence of occurence
Work on the hash map of occurence of occurence
- always YESif the hash map size is 1
- always NOif the hash map size is different from 2
With case of hash map size of 2
- always YESif one of the pair is[1, 1]
- always YESif one pair's value is one and subtract of its key and the other is 1
- the rest is NO
Implementation
1function isValid(s) {2 const charOccMap = new Map()3 const occOccMap = new Map()4 s.split("").forEach(c => charOccMap.set(c, (charOccMap.get(c) || 0) + 1))5 Array.from(charOccMap.values()).forEach(occ =>6 occOccMap.set(occ, (occOccMap.get(occ) || 0) + 1)7 )89 if (occOccMap.size === 1) {10 return "YES"11 }12 if (occOccMap.size !== 2) {13 return "NO"14 }15 const validPairCase1 = (pair1, pair2) =>16 pair1[1] === 1 && pair1[0] - pair2[0] === 117 const validPairCase2 = (pair1, pair2) =>18 (pair1[0] === 1 && pair1[1] === 1) || (pair2[0] === 1 && pair2[1] === 1)19 const [occX, occY] = Array.from(occOccMap)20 return validPairCase1(occX, occY) ||21 validPairCase1(occY, occX) ||22 validPairCase2(occX, occY)23 ? "YES"24 : "NO"25}
Comments
Loading comments...
Tags
hackerrank
string
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Hackerrank: Fraudulent Activity Notifications
Jan 28, 2021
Previous Post
Hackerrank: Mark and Toys
Jan 28, 2021