DEV Community

Discussion on: I failed an interview because of an algorithm

Collapse
 
dannyengelman profile image
Danny Engelman • Edited

You are all still thinking in Numbers. (including those who interview)
The localCompare won't sort "2.1.0a" properly

Key is to convert Numbers to Letters, so 2.1.0a becomes cbaa and then sort

explanation:
stackoverflow.com/questions/683259...

Or in one line

const sortVersions = (x, v = (s) => s.match(/(\d+)|[a-z]/g).map(c => c == ~~c ? String.fromCharCode(97 + c) : c)) => x.sort((a, b) =>v(b) < v(a) ? 1 : -1)


`

Thread Thread
 
luiz0x29a profile image
Real AI

Or just do something like "2.1.0a" becomes " 2 1 0 a", then it will sort correctly.



const sortVersions = (unsortedVersions) => {
  const format = (n) => n.split(/[.a-z]/g).map(c => c.padStart(5)).join("");
  return unsortedVersions.sort((x, y) => {
    return format(x) >= format(y) ? 1 : -1;
  });
};

sortVersions(['2.5.10.4159', '1.0.0', '0.5', '0.4.1', '1', '1.1', '1.1a', '2.5.0', '2a', '1.1a-final', '2.5.10', '10.5', '1.25.4', '1.2.15'])
//["0.4.1","0.5","1","1.0.0","1.1","1.1a","1.1a-final","1.2.15","1.25.4","2a","2.5.0","2.5.10","2.5.10.4159","10.5"]

Thread Thread
 
dannyengelman profile image
Danny Engelman

Yes, indeed. Same concept: sort characters.
It also shows why tech interviews are required. You need a balanced team of developers to bounce ideas around like a soccer team bounces the ball around and one person (and the whole team) scores. So Raul was declined the job because:
A. He did not fit in the team (they already have enough people who can't sort)
B. They are a company who only want Guru developers (in which case they will eventually fail, because a team of Guru developers will never ask the "stupid" questions that drive innovation) Its the famous Think Different Apple video. You need misfits in a team.