Let’s say that you have an array or a list, or
Each of these logs is a space-delimited string of words.
logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
The task is to reorder these logs and return them in the following acceptance criteria:
- The first entry (identifier) of each log is ignored but still returned
- The letter-logs are returned before the digit-logs
- The identifier is only used to sort these there is a tie
How to analyse the problem
At first glance, this appears to be something that could be easily solved by looping through each log entry and if the second part of the entry is a
string type, then adding it to a
tempA list, otherwise adding it to a
However, when it comes to the
sorting part of the return type, this will get complicated fast.
Instead, it would be a much easier path to a resolution if we used the built-in
sorted() Python function and created a custom sorting algorithm to address our acceptance criteria requirements.
How to code the solution
Code language: Python (python)
def reorderLogFiles(logs: List[str]) -> List[str]: def sorty(i): first, second = i.split(" ", 1) if second.isalpha(): return [0, second, first] return [1,] return sorted(logs, key=sorty)
Analyse the time-space complexity
The time-space complexity is
O(n) in this case, as we are simply filtering through a single list and returning new index reshuffling order, as opposed to breaking the original list into additional lists and looping through those, before completing the return.