Had a phone interview with Amazon(AWS) after the preliminary online coding quiz.
The question asked was to find the Number of islands in a grid (https://leetcode.com/problems/number-of-islands/) . I solved this with a reasonable amount of time left, which was then followed up with a few interesting question as follows -
Q.) What if the island could extend to a distance of K units including water (0) as a part of it ? How would this impact the functions and base condition of recursion?
Q.) What would be the time complexity in above case ?
Q.) Can we use parllelization/ multi threading to solve this problem ?
Q) If multiple threads are used in the below example, how would you determine which thread to terminate ?
[[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,1,1,1,1,1]],
My response was as follows -
- Island within distance K could be done by modifying the helper function to take K as parameter and then decreasing K by 1 in every recursive call. All the 0's encountered within this K range should be avoided as a condition to terminate the recursion. Also, when the K reaches 0, the recursion should fold itself.
- Complexity would the same O(n2) as we are still not visiting any node/coordinate which has been visited once.
- Yes, we can use parallelization as long we keep a central storage to track what threads have visited what cells.
- Of this I was unsure but the approach I mentioned was for the threads to keep track of the size of the islands as they are explored along with the coordinates visited. If any of the other threads visits any already visited coordinates , then based on the size comparison between threads we can terminate the one which has explored smaller area.