Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 72d7625

Browse files
added Course Schedule II and Reconstruct Itinerary (Medium)
1 parent d484c9a commit 72d7625

File tree

6 files changed

+169
-1
lines changed

6 files changed

+169
-1
lines changed

‎Medium/CourseSchedule2/README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Course Schedule II
2+
3+
[Leetcode Link](https://leetcode.com/problems/course-schedule-ii/)
4+
5+
## Problem:
6+
7+
There are a total of `n` courses you have to take labelled from `0` to `n - 1`.
8+
9+
Some courses may have `prerequisites`, for example, if `prerequisites[i] = [ai, bi]` this means you must take the course bi before the course ai.
10+
11+
Given the total number of courses `numCourses` and a list of the `prerequisite` pairs, return the ordering of courses you should take to finish all courses.
12+
13+
If there are many valid answers, return _any_ of them. If it is impossible to finish all courses, return _an empty array_.
14+
15+
## Example:
16+
17+
```
18+
Input: numCourses = 2, prerequisites = [[1,0]]
19+
Output: [0,1]
20+
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
21+
```
22+
23+
```
24+
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
25+
Output: [0,2,1,3]
26+
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
27+
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
28+
```
29+
30+
```
31+
Input: numCourses = 1, prerequisites = []
32+
Output: [0]
33+
```
34+
35+
## Note:
36+
37+
- 1 <= numCourses <= 2000
38+
- 0 <= prerequisites.length <= numCourses \* (numCourses - 1)
39+
- prerequisites[i].length == 2
40+
- 0 <= ai, bi < numCourses
41+
- ai != bi
42+
- All the pairs [ai, bi] are distinct.

‎Medium/CourseSchedule2/solution.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import List
2+
from collections import defaultdict, deque
3+
4+
# this method does not work if there's cyclic dependency (ie. a course A with prereq B that has prereq A)
5+
6+
7+
class Solution:
8+
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
9+
availableCourses = defaultdict(list)
10+
for course, prereq in prerequisites:
11+
availableCourses[course].append(prereq)
12+
13+
def takeCourse(course):
14+
if not availableCourses[course]:
15+
if course not in courses:
16+
courses.append(course)
17+
return
18+
19+
for c in availableCourses[course]:
20+
takeCourse(c)
21+
if course not in courses:
22+
courses.append(course)
23+
24+
courses = list()
25+
for i in range(0, numCourses):
26+
takeCourse(i)
27+
return courses
28+
29+
30+
sol = Solution()
31+
numCourses = 6
32+
prereq = [[1, 0], [2, 0], [3, 1], [3, 2], [3, 5]]
33+
print(sol.findOrder(numCourses, prereq))
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from typing import List
2+
from collections import defaultdict
3+
4+
5+
class Solution:
6+
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
7+
indegree = [0]*numCourses
8+
topological_list = list()
9+
queue = list()
10+
# associate indegree and prereq for each courses
11+
graph = defaultdict(list)
12+
for course, prereq in prerequisites:
13+
graph[prereq].append(course)
14+
indegree[course] += 1
15+
print(graph)
16+
# start by adding all courses from 0 that have indegree of 0
17+
for i in range(numCourses):
18+
# add all the courses with indegree of 0
19+
if indegree[i] == 0:
20+
queue.append(i)
21+
while queue:
22+
print("Indegree:", indegree)
23+
print("Queue:", queue)
24+
currentCourse = queue.pop(0)
25+
topological_list.append(currentCourse)
26+
# for each course that needs currentCourse as prereq, decrement indegree by 1 (since currentCourse is "completed"), when indegree of course == 0, then add to queue to be added in topological order
27+
for course in graph[currentCourse]:
28+
indegree[course] -= 1
29+
if indegree[course] == 0:
30+
queue.append(course)
31+
32+
return topological_list if len(topological_list) == numCourses else []
33+
34+
35+
sol = Solution()
36+
numCourses = 3
37+
prereq = [[1, 0], [1, 2], [0, 1]]
38+
print(sol.findOrder(numCourses, prereq))

‎Medium/ReconstructItinerary/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Reconstruct Itinerary
2+
3+
[Leetcode Link](https://leetcode.com/problems/reconstruct-itinerary/)
4+
5+
## Problem:
6+
7+
Given a list of airline tickets represented by pairs of departure and arrival airports `[from, to]`, reconstruct the itinerary in order. All of the tickets belong to a man who departs from `JFK`. Thus, the itinerary must begin with `JFK`.
8+
9+
## Example:
10+
11+
```
12+
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
13+
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
14+
```
15+
16+
```
17+
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
18+
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
19+
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
20+
But it is larger in lexical order.
21+
```
22+
23+
## Note:
24+
25+
1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
26+
2. All airports are represented by three capital letters (IATA code).
27+
3. You may assume all tickets form at least one valid itinerary.
28+
4. One must use all the tickets once and only once.

‎Medium/ReconstructItinerary/solution.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List
2+
from collections import defaultdict
3+
4+
5+
class Solution:
6+
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
7+
destinations = defaultdict(list)
8+
for departure, destination in sorted(tickets, reverse=True):
9+
destinations[departure] += destination,
10+
print(destinations)
11+
route = []
12+
13+
def visit(airport):
14+
while destinations[airport]:
15+
visit(destinations[airport].pop())
16+
route.append(airport)
17+
18+
visit('JFK')
19+
route.reverse()
20+
return route
21+
22+
23+
sol = Solution()
24+
tickets = [["JFK", "KUL"], ["JFK", "NRT"], ["NRT", "JFK"]]
25+
print(sol.findItinerary(tickets))

‎README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ Languages used: Java and Python
4848
- [Invert Binary Tree](Easy/InvertBinaryTree)
4949
- Medium
5050
- [Minimum Add to Make Parentheses Valid](Medium/MinimumAddtoMakeParenthesesValid)
51-
- [Distribute Coins in Binary Tree](Medium/DistributionCoinsInBinaryTree)
51+
- [Distribute Coins in Binary Tree](Medium/DistributeCoinsInBinaryTree)
5252
- [Find Minimum Number of Fibonacci Numbers Whose Sum is K](Medium/FindMinNumFibNumSumK)
5353
- [Find the Duplicate Number](Medium/FindDuplicateNumber)
5454
- [Unique Paths](Medium/UniquePaths)
@@ -91,6 +91,8 @@ Languages used: Java and Python
9191
- [Number of Islands](Medium/NumberOfIslands)
9292
- [Reverse Linked List II](Medium/ReverseLinkedList2)
9393
- [Binary Tree Postorder Traversal](Medium/BinaryPostorder)
94+
- [Reconstruct Itinerary](Medium/ReconstructItinerary)
95+
- [Course Schedule II](Medium/CourseSchedule2)
9496
- Hard
9597

9698
- [Maximum Score Words Formed by Letters](Hard/MaximumScoreWords)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /