CodeWars: Recover a secret string from random triplets Solution
It's easy to make thing more complicatedApproach: exhausive traversal with adjacent list
Build the map of letter and its adjacent letters
Traverse all the possible secret
The right secret is the one who mets the expected length
Implementation
1var recoverSecret = function (triplets) {2 const vertices = new Set(triplets.reduce((acc, el) => acc.concat(el), []))3 const secretLength = vertices.size4 const verticeEdgesMap = new Map(5 [...vertices].map(vertice => [vertice, new Set()])6 )7 const possibleSecrets = []89 for (const [v1, v2, v3] of triplets) {10 verticeEdgesMap.get(v1).add(v2)11 verticeEdgesMap.get(v2).add(v3)1213 // after this, there would be only one head left14 vertices.delete(v2)15 vertices.delete(v3)16 }1718 const recursion = (vertice, secret = "") => {19 const edges = [...verticeEdgesMap.get(vertice)]2021 if (!edges.length) {22 possibleSecrets.push(secret + vertice)23 return24 }2526 for (const adjacentVertice of edges) {27 recursion(adjacentVertice, secret + vertice)28 }29 }3031 const head = [...vertices][0]32 recursion(head)3334 return possibleSecrets.find(secret => secret.length === secretLength)35}
Approach: keep picking heads
Pick a head and remove it from the triplet. Keep doing that till all triplets are empty
There would always be a head during each process
Implementation
1var recoverSecret = function (triplets) {2 let res = ""34 while (triplets.length) {5 for (const [letter1] of triplets) {6 const isHead = triplets.every(triplet => triplet.indexOf(letter1) <= 0)78 if (!isHead) continue910 res += letter111 triplets = triplets12 .map(triplet => (triplet[0] === letter1 ? triplet.slice(1) : triplet))13 .filter(triplet => triplet.length)1415 break16 }17 }1819 return res20}
References
Comments
Loading comments...
Tags
codewars
recursion
dfs
array
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
LeetCode: Implement Queue using Stacks
Code speaks for itself
Previous Post
LeetCode: Same Tree
Recursion