Skip to content

Commit d14d202

Browse files
committedFeb 8, 2025·
Added tasks 139-206
1 parent bb21f1d commit d14d202

File tree

11 files changed

+812
-26
lines changed

11 files changed

+812
-26
lines changed
 

‎README.md

Lines changed: 73 additions & 26 deletions
Large diffs are not rendered by default.
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 139\. Word Break
5+
6+
Medium
7+
8+
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
9+
10+
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
11+
12+
**Example 1:**
13+
14+
**Input:** s = "leetcode", wordDict = ["leet","code"]
15+
16+
**Output:** true
17+
18+
**Explanation:** Return true because "leetcode" can be segmented as "leet code".
19+
20+
**Example 2:**
21+
22+
**Input:** s = "applepenapple", wordDict = ["apple","pen"]
23+
24+
**Output:** true
25+
26+
**Explanation:** Return true because "applepenapple" can be segmented as "apple pen apple".
27+
28+
Note that you are allowed to reuse a dictionary word.
29+
30+
**Example 3:**
31+
32+
**Input:** s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
33+
34+
**Output:** false
35+
36+
**Constraints:**
37+
38+
* `1 <= s.length <= 300`
39+
* `1 <= wordDict.length <= 1000`
40+
* `1 <= wordDict[i].length <= 20`
41+
* `s` and `wordDict[i]` consist of only lowercase English letters.
42+
* All the strings of `wordDict` are **unique**.
43+
44+
## Solution
45+
46+
```racket
47+
(define/contract (word-break s wordDict)
48+
(-> string? (listof string?) boolean?)
49+
(let ((memo (make-hash)))
50+
(define (dp i)
51+
(cond
52+
[(= i (string-length s)) #t]
53+
[(hash-has-key? memo i) (hash-ref memo i)]
54+
[else
55+
(let loop ((words wordDict))
56+
(if (null? words)
57+
(begin (hash-set! memo i #f) #f)
58+
(let* ((word (car words))
59+
(len (string-length word)))
60+
(if (and (<= (+ i len) (string-length s))
61+
(string=? (substring s i (+ i len)) word)
62+
(dp (+ i len)))
63+
(begin (hash-set! memo i #t) #t)
64+
(loop (cdr words))))))]))
65+
(dp 0)))
66+
```
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 146\. LRU Cache
5+
6+
Medium
7+
8+
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
9+
10+
Implement the `LRUCache` class:
11+
12+
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
13+
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
14+
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
15+
16+
The functions `get` and `put` must each run in `O(1)` average time complexity.
17+
18+
**Example 1:**
19+
20+
**Input** ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
21+
22+
**Output:** [null, null, null, 1, null, -1, null, -1, 3, 4]
23+
24+
**Explanation:**
25+
26+
LRUCache lRUCache = new LRUCache(2);
27+
28+
lRUCache.put(1, 1); // cache is {1=1}
29+
30+
lRUCache.put(2, 2); // cache is {1=1, 2=2}
31+
32+
lRUCache.get(1); // return 1
33+
34+
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
35+
36+
lRUCache.get(2); // returns -1 (not found)
37+
38+
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
39+
40+
lRUCache.get(1); // return -1 (not found)
41+
42+
lRUCache.get(3); // return 3
43+
44+
lRUCache.get(4); // return 4
45+
46+
**Constraints:**
47+
48+
* `1 <= capacity <= 3000`
49+
* <code>0 <= key <= 10<sup>4</sup></code>
50+
* <code>0 <= value <= 10<sup>5</sup></code>
51+
* At most <code>2 * 10<sup>5</sup></code> calls will be made to `get` and `put`.
52+
53+
## Solution
54+
55+
```racket
56+
(define lru-cache%
57+
(class object%
58+
(super-new)
59+
60+
(init-field capacity)
61+
62+
(define head #f)
63+
(define tail #f)
64+
(define cache (make-hash))
65+
66+
(define/private (move-to-head node)
67+
(when (not (eq? node head))
68+
(when (eq? node tail)
69+
(set! tail (hash-ref node 'prev))
70+
(when tail (hash-set! tail 'next #f)))
71+
(let ((prev (hash-ref node 'prev #f))
72+
(next (hash-ref node 'next #f)))
73+
(when prev (hash-set! prev 'next next))
74+
(when next (hash-set! next 'prev prev))
75+
(hash-set! node 'prev #f)
76+
(hash-set! node 'next head)
77+
(when head (hash-set! head 'prev node))
78+
(set! head node))))
79+
80+
(define/public (get key)
81+
(let ((node (hash-ref cache key #f)))
82+
(if node
83+
(begin (move-to-head node)
84+
(hash-ref node 'value))
85+
-1)))
86+
87+
(define/public (put key value)
88+
(let ((node (hash-ref cache key #f)))
89+
(if node
90+
(begin
91+
(hash-set! node 'value value)
92+
(move-to-head node))
93+
(begin
94+
(when (>= (hash-count cache) capacity)
95+
(when tail
96+
(hash-remove! cache (hash-ref tail 'key))
97+
(set! tail (hash-ref tail 'prev #f))
98+
(when tail (hash-set! tail 'next #f))))
99+
(let ((new-node (make-hash)))
100+
(hash-set! new-node 'key key)
101+
(hash-set! new-node 'value value)
102+
(hash-set! new-node 'prev #f)
103+
(hash-set! new-node 'next head)
104+
(when head (hash-set! head 'prev new-node))
105+
(set! head new-node)
106+
(unless tail (set! tail new-node))
107+
(hash-set! cache key new-node))))))))
108+
```
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 148\. Sort List
5+
6+
Medium
7+
8+
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg)
13+
14+
**Input:** head = [4,2,1,3]
15+
16+
**Output:** [1,2,3,4]
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg)
21+
22+
**Input:** head = [-1,5,3,4,0]
23+
24+
**Output:** [-1,0,3,4,5]
25+
26+
**Example 3:**
27+
28+
**Input:** head = []
29+
30+
**Output:** []
31+
32+
**Constraints:**
33+
34+
* The number of nodes in the list is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.
35+
* <code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code>
36+
37+
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
38+
39+
## Solution
40+
41+
```racket
42+
; Definition for singly-linked list:
43+
#|
44+
45+
; val : integer?
46+
; next : (or/c list-node? #f)
47+
(struct list-node
48+
(val next) #:mutable #:transparent)
49+
50+
; constructor
51+
(define (make-list-node [val 0])
52+
(list-node val #f))
53+
54+
|#
55+
56+
; Helper function to split the list into two halves
57+
(define (split-list head)
58+
(let loop ([slow head]
59+
[fast head]
60+
[pre #f])
61+
(cond
62+
[(or (not fast) (not (list-node-next fast)))
63+
(when pre
64+
(set-list-node-next! pre #f))
65+
slow]
66+
[else
67+
(loop (list-node-next slow)
68+
(list-node-next (list-node-next fast))
69+
slow)])))
70+
71+
; Helper function to merge two sorted lists
72+
(define (merge-lists l1 l2)
73+
(let ([dummy (list-node 1 #f)])
74+
(let loop ([curr dummy]
75+
[first l1]
76+
[second l2])
77+
(cond
78+
[(not first)
79+
(set-list-node-next! curr second)]
80+
[(not second)
81+
(set-list-node-next! curr first)]
82+
[else
83+
(if (<= (list-node-val first) (list-node-val second))
84+
(begin
85+
(set-list-node-next! curr first)
86+
(loop first (list-node-next first) second))
87+
(begin
88+
(set-list-node-next! curr second)
89+
(loop second first (list-node-next second))))])
90+
(list-node-next dummy))))
91+
92+
; Main sort-list function with contract
93+
(define/contract (sort-list head)
94+
(-> (or/c list-node? #f) (or/c list-node? #f))
95+
(cond
96+
[(or (not head) (not (list-node-next head)))
97+
head]
98+
[else
99+
(let* ([middle (split-list head)]
100+
[first (sort-list head)]
101+
[second (sort-list middle)])
102+
(merge-lists first second))]))
103+
```
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 152\. Maximum Product Subarray
5+
6+
Medium
7+
8+
Given an integer array `nums`, find a contiguous non-empty subarray within the array that has the largest product, and return _the product_.
9+
10+
The test cases are generated so that the answer will fit in a **32-bit** integer.
11+
12+
A **subarray** is a contiguous subsequence of the array.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [2,3,-2,4]
17+
18+
**Output:** 6
19+
20+
**Explanation:** [2,3] has the largest product 6.
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [-2,0,-1]
25+
26+
**Output:** 0
27+
28+
**Explanation:** The result cannot be 2, because [-2,-1] is not a subarray.
29+
30+
**Constraints:**
31+
32+
* <code>1 <= nums.length <= 2 * 10<sup>4</sup></code>
33+
* `-10 <= nums[i] <= 10`
34+
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
35+
36+
## Solution
37+
38+
```racket
39+
(define/contract (max-product nums)
40+
(-> (listof exact-integer?) exact-integer?)
41+
(let* ([n (length nums)]
42+
[min-int (- (expt 2 31))])
43+
(let loop ([i 0]
44+
[start 1]
45+
[end 1]
46+
[overall-max-prod min-int])
47+
(if (= i n)
48+
overall-max-prod
49+
(let* ([new-start (if (zero? start) 1 start)]
50+
[new-end (if (zero? end) 1 end)]
51+
[start-prod (* new-start (list-ref nums i))]
52+
[end-prod (* new-end (list-ref nums (- n i 1)))])
53+
(loop (+ i 1)
54+
start-prod
55+
end-prod
56+
(max overall-max-prod start-prod end-prod)))))))
57+
```
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 153\. Find Minimum in Rotated Sorted Array
5+
6+
Medium
7+
8+
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
9+
10+
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
11+
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
12+
13+
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
14+
15+
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
16+
17+
You must write an algorithm that runs in `O(log n) time.`
18+
19+
**Example 1:**
20+
21+
**Input:** nums = [3,4,5,1,2]
22+
23+
**Output:** 1
24+
25+
**Explanation:** The original array was [1,2,3,4,5] rotated 3 times.
26+
27+
**Example 2:**
28+
29+
**Input:** nums = [4,5,6,7,0,1,2]
30+
31+
**Output:** 0
32+
33+
**Explanation:** The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
34+
35+
**Example 3:**
36+
37+
**Input:** nums = [11,13,15,17]
38+
39+
**Output:** 11
40+
41+
**Explanation:** The original array was [11,13,15,17] and it was rotated 4 times.
42+
43+
**Constraints:**
44+
45+
* `n == nums.length`
46+
* `1 <= n <= 5000`
47+
* `-5000 <= nums[i] <= 5000`
48+
* All the integers of `nums` are **unique**.
49+
* `nums` is sorted and rotated between `1` and `n` times.
50+
51+
## Solution
52+
53+
```racket
54+
(define/contract (find-min nums)
55+
(-> (listof exact-integer?) exact-integer?)
56+
(letrec
57+
([find-min-util
58+
(lambda (nums l r)
59+
(if (= l r)
60+
(list-ref nums l)
61+
(let* ([mid (quotient (+ l r) 2)]
62+
[mid-val (list-ref nums mid)]
63+
[left-val (if (> mid 0) (list-ref nums (- mid 1)) +inf.0)]
64+
[right-val (list-ref nums r)])
65+
(cond
66+
[(and (= mid l) (< mid-val right-val)) (list-ref nums l)]
67+
[(and (>= (- mid 1) 0) (> left-val mid-val)) mid-val]
68+
[(< mid-val (list-ref nums l)) (find-min-util nums l (- mid 1))]
69+
[(> mid-val right-val) (find-min-util nums (+ mid 1) r)]
70+
[else (find-min-util nums l (- mid 1))]))))])
71+
(find-min-util nums 0 (- (length nums) 1))))
72+
```
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 155\. Min Stack
5+
6+
Easy
7+
8+
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
9+
10+
Implement the `MinStack` class:
11+
12+
* `MinStack()` initializes the stack object.
13+
* `void push(int val)` pushes the element `val` onto the stack.
14+
* `void pop()` removes the element on the top of the stack.
15+
* `int top()` gets the top element of the stack.
16+
* `int getMin()` retrieves the minimum element in the stack.
17+
18+
**Example 1:**
19+
20+
**Input**
21+
22+
["MinStack","push","push","push","getMin","pop","top","getMin"]
23+
[[],[-2],[0],[-3],[],[],[],[]]
24+
25+
**Output:** [null,null,null,null,-3,null,0,-2]
26+
27+
**Explanation:**
28+
29+
MinStack minStack = new MinStack();
30+
minStack.push(-2);
31+
minStack.push(0);
32+
minStack.push(-3);
33+
minStack.getMin(); // return -3
34+
minStack.pop();
35+
minStack.top(); // return 0
36+
minStack.getMin(); // return -2
37+
38+
**Constraints:**
39+
40+
* <code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code>
41+
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
42+
* At most <code>3 * 10<sup>4</sup></code> calls will be made to `push`, `pop`, `top`, and `getMin`.
43+
44+
## Solution
45+
46+
```racket
47+
(define min-stack%
48+
(class object%
49+
(super-new)
50+
51+
(define vals '())
52+
53+
; push : exact-integer? -> void?
54+
(define/public (push val)
55+
(let* ([cur-min (if (empty? vals) val (get-min))]
56+
[new-top (cons val (min cur-min val))])
57+
(set! vals (cons new-top vals))))
58+
59+
; pop : -> void?
60+
(define/public (pop)
61+
(define res (top))
62+
(set! vals (cdr vals))
63+
res)
64+
65+
; top : -> exact-integer?
66+
(define/public (top)
67+
(car (first vals)))
68+
69+
; get-min : -> exact-integer?
70+
(define/public (get-min)
71+
(cdr (first vals)))))
72+
73+
;; Your min-stack% object will be instantiated and called as such:
74+
;; (define obj (new min-stack%))
75+
;; (send obj push val)
76+
;; (send obj pop)
77+
;; (define param_3 (send obj top))
78+
;; (define param_4 (send obj get-min))
79+
```
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 169\. Majority Element
5+
6+
Easy
7+
8+
Given an array `nums` of size `n`, return _the majority element_.
9+
10+
The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [3,2,3]
15+
16+
**Output:** 3
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [2,2,1,1,1,2,2]
21+
22+
**Output:** 2
23+
24+
**Constraints:**
25+
26+
* `n == nums.length`
27+
* <code>1 <= n <= 5 * 10<sup>4</sup></code>
28+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
29+
30+
**Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
31+
32+
## Solution
33+
34+
```racket
35+
(define/contract (majority-element nums)
36+
(-> (listof exact-integer?) exact-integer?)
37+
(define candidate 0)
38+
(define count 0)
39+
40+
(for ([n nums])
41+
(cond
42+
[(zero? count)
43+
(set! candidate n)
44+
(set! count 1)
45+
]
46+
[(= candidate n)
47+
(set! count (+ count 1))
48+
]
49+
[else
50+
(set! count(- count 1))
51+
]
52+
)
53+
)
54+
candidate
55+
)
56+
```
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 198\. House Robber
5+
6+
Medium
7+
8+
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
9+
10+
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [1,2,3,1]
15+
16+
**Output:** 4
17+
18+
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
19+
20+
**Example 2:**
21+
22+
**Input:** nums = [2,7,9,3,1]
23+
24+
**Output:** 12
25+
26+
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
27+
28+
**Constraints:**
29+
30+
* `1 <= nums.length <= 100`
31+
* `0 <= nums[i] <= 400`
32+
33+
## Solution
34+
35+
```racket
36+
(define/contract (rob nums)
37+
(-> (listof exact-integer?) exact-integer?)
38+
(let ([n (length nums)])
39+
(cond [(= n 1) (first nums)]
40+
[(= n 2) (max (first nums) (second nums))]
41+
[(= n 3) (max (+ (first nums) (third nums)) (second nums))]
42+
[else
43+
(let-values ([(a b c d)
44+
(for/fold ([dp0 (first nums)]
45+
[dp1 (max (first nums) (second nums))]
46+
[dp2 (max (+ (first nums) (third nums)) (second nums))]
47+
[prev-elem (third nums)])
48+
([i (cdddr nums)])
49+
(values dp1 dp2 (max (+ i dp1) (+ prev-elem dp0)) i))])
50+
c)
51+
])))
52+
```
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 200\. Number of Islands
5+
6+
Medium
7+
8+
Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_.
9+
10+
An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
11+
12+
**Example 1:**
13+
14+
**Input:** grid = [
15+
16+
["1","1","1","1","0"],
17+
18+
["1","1","0","1","0"],
19+
20+
["1","1","0","0","0"],
21+
22+
["0","0","0","0","0"]
23+
24+
]
25+
26+
**Output:** 1
27+
28+
**Example 2:**
29+
30+
**Input:** grid = [
31+
32+
["1","1","0","0","0"],
33+
34+
["1","1","0","0","0"],
35+
36+
["0","0","1","0","0"],
37+
38+
["0","0","0","1","1"]
39+
40+
]
41+
42+
**Output:** 3
43+
44+
**Constraints:**
45+
46+
* `m == grid.length`
47+
* `n == grid[i].length`
48+
* `1 <= m, n <= 300`
49+
* `grid[i][j]` is `'0'` or `'1'`.
50+
51+
## Solution
52+
53+
```racket
54+
(define-syntax vref
55+
(syntax-rules ()
56+
((_ vec idx) (vector-ref vec idx))))
57+
58+
(define-syntax vlen
59+
(syntax-rules ()
60+
((_ vec) (vector-length vec))))
61+
62+
(define-syntax in?
63+
(syntax-rules ()
64+
((_ st x) (set-member? st x))))
65+
66+
(define (num-islands grid)
67+
(define g (list->vector (map list->vector grid)))
68+
69+
(define (dfs i j visited)
70+
(cond
71+
[(or (< i 0) (>= i (vlen g)) (< j 0) (>= j (vlen (vref g 0)))) visited] ; if i,j is out of bounds
72+
[(in? visited (cons i j)) visited]
73+
[(equal? (vref (vref g i) j) #\0) visited]
74+
[else (dfs i (sub1 j) (dfs (add1 i) j (dfs i (add1 j) (dfs (sub1 i) j (set-add visited (cons i j))))))])) ; explore all 4 directions
75+
76+
(for*/fold ([islands 0]
77+
[visited (set)]
78+
#:result islands)
79+
([i (vlen g)]
80+
[j (vlen (vref g 0))])
81+
(match (vref (vref g i) j)
82+
[#\0 (values islands visited)]
83+
[#\1 #:when (in? visited (cons i j)) (values islands visited)]
84+
[#\1 (values (add1 islands) (dfs i j visited))])))
85+
```
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Racket/LeetCode-in-Racket?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Racket/LeetCode-in-Racket?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Racket/LeetCode-in-Racket/fork)
3+
4+
## 206\. Reverse Linked List
5+
6+
Easy
7+
8+
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg)
13+
14+
**Input:** head = [1,2,3,4,5]
15+
16+
**Output:** [5,4,3,2,1]
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg)
21+
22+
**Input:** head = [1,2]
23+
24+
**Output:** [2,1]
25+
26+
**Example 3:**
27+
28+
**Input:** head = []
29+
30+
**Output:** []
31+
32+
**Constraints:**
33+
34+
* The number of nodes in the list is the range `[0, 5000]`.
35+
* `-5000 <= Node.val <= 5000`
36+
37+
**Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
38+
39+
## Solution
40+
41+
```racket
42+
; Definition for singly-linked list:
43+
#|
44+
45+
; val : integer?
46+
; next : (or/c list-node? #f)
47+
(struct list-node
48+
(val next) #:mutable #:transparent)
49+
50+
; constructor
51+
(define (make-list-node [val 0])
52+
(list-node val #f))
53+
54+
|#
55+
(define (reverse-list head)
56+
(define (rev ll prev)
57+
(match ll
58+
[#f prev]
59+
[(list-node val next) (rev next (list-node val prev))]))
60+
(rev head #f))
61+
```

0 commit comments

Comments
 (0)
Please sign in to comment.