Unit 10 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
n[i][j] == 1
indicates that there is a direct flight from destination i
to destination j
, and n[i][j] == 0
means no flight exists.source
destination.HAPPY CASE
Input: flights = [
[0, 1, 1, 0],
[1, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 0, 0]
], source = 2
Output: [0, 1, 3]
Explanation: From destination 2, there are direct flights to destinations 0, 1, and 3.
EDGE CASE
Input: flights = [
[0, 1, 1, 0],
[1, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 0, 0]
], source = 3
Output: []
Explanation: Destination 3 has no outgoing flights, so the result is an empty list.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Graph Representation problems, we want to consider the following approaches:
source
node to find all direct connections.Plan the solution with appropriate visualizations and pseudocode.
General Idea: We are given an adjacency matrix and asked to return all direct flights from a given source
destination. This means checking the row corresponding to source
in the matrix and finding all columns where the value is 1
, which represents a direct flight.
1) Create an empty list `direct_flights` to store the result.
2) Iterate over each destination (column) in the `flights[source]` row.
3) If `flights[source][destination] == 1`, append `destination` to `direct_flights`.
4) Return the list `direct_flights`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def get_direct_flights(flights, source):
direct_flights = []
n = len(flights) # Number of destinations (matrix is n x n)
# Iterate over all possible destinations from the source
for destination in range(n):
if flights[source][destination] == 1: # If there is a direct flight
direct_flights.append(destination)
return direct_flights
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
flights = [
[0, 1, 1, 0],
[1, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 0, 0]
]
print(get_direct_flights(flights, 2))
print(get_direct_flights(flights, 3))
[0, 1, 3]
[]
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
O(n)
, where n
is the number of destinations. We only need to check one row of the adjacency matrix.O(n)
as we store the list of direct flights.