Hi, Today i bring to you problem of the day from Leetcode. So after the busy day and so called "this is my new year resolution" (just kidding obviously). i am going to at least look at leetcode of the day in Leetcode rather thinking f doing minimum 5 questions a day. (gets bit tough when you are lazy).
Anyways today's problem was very cool. It was no brainier obviously f you are going for the brute force approach. But we need to optimize that brute approach as well.
So, the qs was Convert an Array Into a 2D Array With Conditions. I will go with step by step explanation for the code in a bit. But first I'd rather want my fellow ciders to at least spend 15-20 mins thinking about it.
Hint: You need only unique elements in an array. There can be multiple unique arrays and the result will be in array of arrays format.
I hope you got enough time to think about the code. Let's begin in
5
.
.
4.
.
.
3
.
.
2
.
.
1
.
.
(obviously for the dramatic effects)
So this is screenshot of my code, straight from my submissions.
Let me give you little walk through of my code. As I said the problem statement was straight forward. I have used hashmap for my solution and to return the final result i used a list.
idx = 0
hm = defaultdict(list)
`idx`
is initialized to 0, andhm
(short for hash map) is created as a defaultdict with lists as the default values. This dictionary will be used to store lists of numbers based on their index.
for num in nums:
for i in range(idx+1):
if hm[i]:
if num not in hm[i]:
hm[i].append(num)
break
else:
hm[i].append(num)
idx +=1
- The code then iterates over each element in the input list
nums
. For each number (num
), it iterates over the range from 0 toidx+1
.
Inside the nested loop, it checks if
hm[i]
(the list at indexi
in the hash map) is not empty. If it's not empty andnum
is not already present in the list, it appendsnum
to the list and breaks out of the loop.
If
hm[i]
is empty (i.e., there's no list at indexi
), it appendsnum
to a new list at indexi
and incrementsidx
.
res = []
for key, val in hm.items():
res.append(val)
return res
- Finally, the code creates an empty list
res
. It then iterates over the items in the hash map (hm
) and appends the lists as values to the result listres
. The function returns the final list of lists.
In summary, the code is grouping numbers from the input list into sublists based on their unique appearance as asked in the problem. The resulting list of lists (res
) is returned as the output.
Below is the performance of the given code.
Time complexity - O(N)
Space Complexity - O(N)
N, here is length of the array.
Hope it helps :)
Hi, thanks for reading my post, I hope you enjoyed it. So, if you want me to keep you updated with the tech references in coming future please do share your valuable comments with me and also do not forget to share it with your friends....:)
Comments
Post a Comment