AMAZON Generic Coding Question Solved

9 Live
Amazon's Alexa team is working on optimizing the customer experience for scenarios where customers ask generic questions. One example of a generic question is "What are good vegetarian restaurants nearby?" In this example, Alexa would then search for a list of vegetarian restaurants in the city and select the nearest X vegetarian restaurants relative to the customer's location. Given an array representing the locations of N vegetarian restaurants in the city, implement an algorithm to find the nearest X vegetarian restaurants to the customer's location. Input The input to the function/method consists of two arguments: - allLocations: a list of elements where each element consists of a pair of integers representing the x and y coordinates of the vegetarian restaurant in the city - numRestaurants: an integer representing the number of nearby vegetarian restaurants that would be returned to the customer (X) Output Return a list of elements where each element of the list represents the x and y integer coordinates of the nearest recommended vegetarian restaurant relative to customer's location. If there is one tie, use the location with the closest X coordinate. If no location is possible, return a list with an empty location - not just an empty list. Constraints numRestaurants ≤ size(allLocations) Note The customer begins at the location [0, 0]. The distance from the customer's current location to a recommended vegetarian restaurant location (x, y) is the square root of x² + y². If there are ties then return any of the locations as long as you satisfy returning exactly X nearby vegetarian restaurants. The returned output can be in any order. Example Input: allLocations = [[1, 2], [3, 4], [1, -1]] numRestaurants = 2 Output: [[1, -1], [1, 2]] Explanation: The distance of the customer's current location from location [1, 2] is √5 ≈ 2.236 The distance from location [3, 4] is √25 = 5 The distance from location [1, -1] is √2 ≈ 1.414 The required number of vegetarian restaurants is 2, hence the output is [1, -1] and [1, 2].

Asked in: AMAZON

Image of the Question

Question Image Question Image Question Image

All Testcases Passed ✔



Passcode Image

Solution


def findRestaurants(allLocations, numRestaurants):
    # Write your code here
    
    near_by_locations = []
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
To solve this problem, the primary goal is to identify the nearest X vegetarian restaurants from a given list of N restaurant locations relative to the customer’s starting position at (0, 0). The problem requires selecting the closest restaurants based on Euclidean distance and handling ties by using the X coordinate as a secondary sorting criterion. Let’s break down how to think about this systematically.

---

### Step 1: Understand the distance metric and constraints

- The customer starts at the origin (0,0).
- Distance to any restaurant at coordinates (x, y) is the Euclidean distance: sqrt(x² + y²).
- The problem’s output depends on sorting by proximity (shortest distance first).
- When two restaurants are equidistant, the restaurant with the smaller X coordinate should be preferred.
- The number of restaurants to return, X (numRestaurants), will always be less than or equal to the total number of restaurants N.

---

### Step 2: Visualizing the problem

Imagine a 2D plane with the origin at the center. Each restaurant location is a point on the plane. Your task is to draw a circle around the origin and include the closest X points inside that circle. Because of the tie-breaking rule, if two restaurants lie on the circle edge (same distance), the one with smaller X coordinate is favored.

---

### Step 3: Calculating distances and sorting

The natural approach is:

1. Calculate the distance for each restaurant.
2. Sort the restaurants by their distance from the origin.
3. For restaurants with equal distance, use the X coordinate as a tiebreaker.

Sorting by distance and then by X coordinate is straightforward but crucial to maintain the correct ordering, especially when distances tie.

---

### Step 4: Handling ties efficiently

When sorting, the criteria become a tuple:

- Primary key: Distance from (0, 0)
- Secondary key: X coordinate of the restaurant

This ensures if two or more restaurants have the exact same distance, they will be ordered according to the X coordinate.

---

### Step 5: Selecting the nearest X restaurants

After sorting:

- Simply take the first X restaurants from the sorted list.
- If numRestaurants is zero or no locations exist (unlikely given constraints), you return a list with a single empty location (e.g., [[]]) as specified.

---

### Step 6: Optimizing for large inputs

If the input size is very large (millions of restaurants), sorting the entire list may be costly.

Alternatives:

- Use a heap (priority queue) that maintains only the top X closest restaurants while iterating through the list. This approach ensures O(N log X) time complexity instead of O(N log N) for sorting the entire list.
- As you iterate:
- Compute the distance for the current restaurant.
- Insert it into the heap if the heap size is less than X.
- If the heap is full and the current restaurant is closer than the farthest in the heap, replace it.
- Remember to maintain the tie-breaking rules when comparing distances.

---

### Step 7: Edge cases and correctness

- If two or more restaurants have exactly the same coordinates, they have the same distance and same X coordinate, so they are equal by sorting keys. You can return any of them as long as the count X is satisfied.
- If numRestaurants equals N, simply return all restaurants sorted.
- If numRestaurants is zero (not specified, but if it happens), return the empty location list as per instructions.

---

### Step 8: Summary of the approach

1. **Compute distances:** Iterate through each location and compute the Euclidean distance squared (you can skip the square root to save computation time since sqrt is monotonic).
2. **Sort or select nearest X:** Sort the restaurants primarily by distance and secondarily by X coordinate, or maintain a max-heap of size X during iteration.
3. **Return results:** Take the first X restaurants after sorting or from the heap and return their coordinates.
4. **Handle ties:** Ensured automatically via sorting or careful heap comparison.

---

### Step 9: Why squared distance?

To optimize, notice that comparing distances by sqrt(x² + y²) or by x² + y² alone yields the same order because sqrt is monotonic. Hence, use squared distance to avoid the computational overhead of square roots.

---

### Step 10: Possible variations and considerations

- If the problem required the result to be sorted in a particular order (say ascending by distance or by X coordinate), the final list can be sorted again after extraction.
- Consider memory constraints: if allLocations is extremely large, streaming or partial sorting might be needed.
- In case of ties in both distance and X coordinate, the problem states “return any of the locations” so no further tie-breaker is necessary.

---

### Conclusion

This problem essentially boils down to sorting or selecting points based on their distance from a fixed point (origin) and applying a tie-break on the X coordinate. Efficient distance calculation and use of sorting or heap structures depending on input size are key. Handling ties correctly ensures consistency. Ultimately, after computing and sorting/selecting, returning the first X locations gives the desired output.
```


Related Questions