by teaearlgraycold · 2y ago · 0 comments
I still struggle with this. I don’t find it a blocker, though. The bottleneck is usually to understand and parse business requirements. If you know about good code practices as well, then the least of your problems is to know whether you can use ‘in’ or ‘[]’, ‘var’ or ‘let’, ‘foreach’ or ‘for’, ‘def’ or ‘fun’, etc.
Here's a log file of page accesses on our server. It's a CSV. The first column is the user, the second column is the page, and the third column is the load time for that page in milliseconds. We want to know what is the most common three page path access pattern on our site. By that I mean, if the user goes to pages A -> B -> C -> A -> B -> C the most common three page path for that user is "A -> B -> C".
user, page, load time
A, B, 500
A, C, 100
A, D, 50
B, C, 100
A, E, 200
B, A, 450
etc.
So for this first question you should give an answer in the form of "A -> B -> C with a count of N".We would have two files, one simple one that is possible to read through and calculate by hand, and one too long for that. The longer file has a "gotchya" where there's actually two paths that are tied for the highest frequency. I'd point out that they'd given an incomplete answer if they don't give all paths with the highest frequency.
The second part would be to calculate the slowest three page path using the load times.
In my opinion it's a pretty good way to filter out people that can't code at all. It's more or less a fancy fizzbuzz.
I feel like this is a fun thought experiment, but instead of thinking about "gotchas" I would be more open to having a discussion about edge cases, etc... The connotation of gotchas just seems to be like a trap where if you hit one, you've failed the interview.
That's probably doable in like 5 lines of pandas/numpy; a straight forward o(n) task really. The hard part is getting it right without googling and debugging, but a good interviewer would help you out and listen to the idea.
Maybe using Pandas is cheating since it gives you all the tools you'd want but I'd argue it's the right tool for the task and you could then go on how you'd profile and improve the code if performance were a concern.
import sys
unfinishedPaths = {} # [user] = [path1, path2, ...] = [[page1, page2], [page1]]
finishedPaths = {} # [path] = count
for line in sys.stdin:
user = line.split(',')[0].strip()
page = line.split(',')[1].strip()
if user not in unfinishedPaths:
unfinishedPaths[user] = []
deleteIndex = []
for pathindex, path in enumerate(unfinishedPaths[user]):
path.append(page)
if len(path) == 3:
deleteIndex.append(pathindex)
for pathindex in deleteIndex:
serializedPath = ' -> '.join(unfinishedPaths[user][pathindex])
if serializedPath in finishedPaths:
finishedPaths[serializedPath] += 1
else:
finishedPaths[serializedPath] = 1
del unfinishedPaths[user][pathindex]
unfinishedPaths[user].append([page])
for k in sorted(finishedPaths, key=lambda x: finishedPaths[x], reverse=True):
print(str(k) + ' with a count of ' + str(finishedPaths[k]))
Not tested properly because no expected output is given, but from concatenating your sample data a few times and introducing a third person, the output looks plausible. And I just noticed I failed because it says top 3, not just print all in order (guess I expect the user to use "| head -3" since it's a command-line program).I needed to look up the parameter/argument that turns out to be called "key" for sorted() so I didn't do it all by heart (used html docs on the local filesystem for that, no web search or LLM), and I had one bout of confusion where I thought I needed to have another for loop inside of the "for pathindex, path in ..." (thinking it was "for pathsindex, paths in", note the plural). Not sure I'd have figured that one out with interview stress.
This is definitely trickier than fizzbuzz or similar. Would budget at least 20 minutes for a great candidate having bad nerves and bad luck, which makes it fairly long given that you have follow-up questions and probably also want to get to other topics like team fit and compensation expectations at some point
edit: wait, now I need to know: did I get hired?
Major:
1. Sorting finishedPaths is unnecessary given it only asks for the most frequent one (not the top 3 btw)
2. Deleting from the middle of the unfinishedPaths list is slow because it needs to shift the subsequent elements
3. You're storing effectively the same information 3 times in unfinishedPaths ([A, B, C], [B, C], [C])
Minor:
1. line.split is called twice
2. Way too many repeated dict lookups that could be easily avoided (in particular the 'if key (not) in dict: do_something(dict[key])' stuff should be done using dict.get and dict.setdefault instead)
3. deleteIndex doesn't need to be a list, it's always at most 1 element
Here's my solution in TS.
const parseLog = (input: string) => {
const userToHistory: {[user: string]: string[] } = {}
const pageListToFrequencyCount: { [pages: string]: number } = {}
for (const [user, page, ] of input.trim().split("\n").map(row => row.split(", "))) {
userToHistory[user] = (userToHistory[user] ?? []).concat(page);
if (userToHistory[user].length >= 3) {
const path = userToHistory[user].slice(-3).join(" -> ")
pageListToFrequencyCount[path] = (pageListToFrequencyCount[path] ?? 0) + 1;
}
}
return Object.entries(pageListToFrequencyCount).sort(([, a], [, b]) => a - b);
}
It could be slow on large log files because it keeps the whole log in memory. You could speed it up significantly by doing a `.shift()` at the point when you `.slice(-3)` so that you only track the last 3 pages for any user.Unless youre talking about using tail / grepping some linux logs I've never done this once let alone on a daily basis...
But if needed frankly I would look up any needed regex / pattern for this on the job and on the fly. The topic of "log parsing" is massive anyway. What types of logs? Is this something like request logs from NGINX? Custom stderr / stdout from some cron job? Some sort of horrible XML based system dump? I could go on and on...
When you know the solution already of course its obvious.