Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b2fe2ea

Browse files
committedNov 7, 2024·
Added tasks 148-239
1 parent 17d1e76 commit b2fe2ea

File tree

21 files changed

+1866
-0
lines changed

21 files changed

+1866
-0
lines changed
 

‎README.md

Lines changed: 65 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
42+
#include <stdio.h>
43+
#include <stdlib.h>
44+
45+
/**
46+
* Definition for singly-linked list.
47+
* struct ListNode {
48+
* int val;
49+
* struct ListNode *next;
50+
* };
51+
*/
52+
// Helper function to create a new ListNode
53+
struct ListNode* createNode(int val) {
54+
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
55+
node->val = val;
56+
node->next = NULL;
57+
return node;
58+
}
59+
60+
// Helper function to merge two sorted linked lists
61+
struct ListNode* merge(struct ListNode* l1, struct ListNode* l2) {
62+
struct ListNode dummy;
63+
struct ListNode* tail = &dummy;
64+
dummy.next = NULL;
65+
66+
while (l1 != NULL && l2 != NULL) {
67+
if (l1->val <= l2->val) {
68+
tail->next = l1;
69+
l1 = l1->next;
70+
} else {
71+
tail->next = l2;
72+
l2 = l2->next;
73+
}
74+
tail = tail->next;
75+
}
76+
77+
if (l1 != NULL) tail->next = l1;
78+
if (l2 != NULL) tail->next = l2;
79+
80+
return dummy.next;
81+
}
82+
83+
// Function to sort the linked list using merge sort
84+
struct ListNode* sortList(struct ListNode* head) {
85+
if (head == NULL || head->next == NULL) {
86+
return head;
87+
}
88+
89+
// Split the list into two halves
90+
struct ListNode *slow = head, *fast = head, *pre = NULL;
91+
while (fast != NULL && fast->next != NULL) {
92+
pre = slow;
93+
slow = slow->next;
94+
fast = fast->next->next;
95+
}
96+
pre->next = NULL; // Break the list into two halves
97+
98+
// Recursively sort both halves
99+
struct ListNode* left = sortList(head);
100+
struct ListNode* right = sortList(slow);
101+
102+
// Merge the sorted halves
103+
return merge(left, right);
104+
}
105+
```
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
39+
#include <stdio.h>
40+
#include <limits.h>
41+
42+
// Function to get the maximum of two integers
43+
int max(int a, int b) {
44+
return (a > b) ? a : b;
45+
}
46+
47+
// Function to get the minimum of two integers
48+
int min(int a, int b) {
49+
return (a < b) ? a : b;
50+
}
51+
52+
// Function to find the maximum product subarray
53+
int maxProduct(int* nums, int numsSize) {
54+
if (numsSize == 0) return 0;
55+
56+
int currentMaxProd = nums[0];
57+
int currentMinProd = nums[0];
58+
int overAllMaxProd = nums[0];
59+
60+
for (int i = 1; i < numsSize; i++) {
61+
if (nums[i] < 0) {
62+
// Swap currentMaxProd and currentMinProd
63+
int temp = currentMaxProd;
64+
currentMaxProd = currentMinProd;
65+
currentMinProd = temp;
66+
}
67+
68+
// Update the current maximum and minimum products
69+
currentMaxProd = max(nums[i], nums[i] * currentMaxProd);
70+
currentMinProd = min(nums[i], nums[i] * currentMinProd);
71+
72+
// Update the overall maximum product
73+
overAllMaxProd = max(overAllMaxProd, currentMaxProd);
74+
}
75+
76+
return overAllMaxProd;
77+
}
78+
```
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
54+
#include <stdio.h>
55+
56+
// Helper function to find the minimum element in a rotated sorted array
57+
int findMinUtil(int* nums, int l, int r) {
58+
if (l == r) {
59+
return nums[l];
60+
}
61+
62+
int mid = (l + r) / 2;
63+
64+
// If array is not rotated or only two elements left
65+
if (mid == l && nums[mid] < nums[r]) {
66+
return nums[l];
67+
}
68+
69+
// Check if the middle element is the minimum
70+
if (mid - 1 >= 0 && nums[mid - 1] > nums[mid]) {
71+
return nums[mid];
72+
}
73+
74+
// Decide which half to search
75+
if (nums[mid] < nums[l]) {
76+
return findMinUtil(nums, l, mid - 1);
77+
} else if (nums[mid] > nums[r]) {
78+
return findMinUtil(nums, mid + 1, r);
79+
}
80+
81+
// If there’s ambiguity, search the left half
82+
return findMinUtil(nums, l, mid - 1);
83+
}
84+
85+
// Function to initialize the search for minimum in the rotated sorted array
86+
int findMin(int* nums, int numsSize) {
87+
int l = 0;
88+
int r = numsSize - 1;
89+
return findMinUtil(nums, l, r);
90+
}
91+
```
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
47+
#include <stdio.h>
48+
#include <stdlib.h>
49+
#include <limits.h>
50+
51+
// Define the structure for a node in the stack
52+
typedef struct Node {
53+
int min;
54+
int data;
55+
struct Node* nextNode;
56+
struct Node* previousNode;
57+
} Node;
58+
59+
// Define the structure for MinStack
60+
typedef struct {
61+
Node* currentNode;
62+
} MinStack;
63+
64+
// Function to create a new node
65+
Node* createNode(int min, int data, Node* previousNode, Node* nextNode) {
66+
Node* node = (Node*)malloc(sizeof(Node));
67+
node->min = min;
68+
node->data = data;
69+
node->previousNode = previousNode;
70+
node->nextNode = nextNode;
71+
return node;
72+
}
73+
74+
// Initialize MinStack
75+
MinStack* minStackCreate() {
76+
MinStack* stack = (MinStack*)malloc(sizeof(MinStack));
77+
stack->currentNode = NULL;
78+
return stack;
79+
}
80+
81+
// Push a value onto the MinStack
82+
void minStackPush(MinStack* obj, int val) {
83+
if (obj->currentNode == NULL) {
84+
obj->currentNode = createNode(val, val, NULL, NULL);
85+
} else {
86+
obj->currentNode->nextNode = createNode(
87+
(val < obj->currentNode->min) ? val : obj->currentNode->min,
88+
val,
89+
obj->currentNode,
90+
NULL
91+
);
92+
obj->currentNode = obj->currentNode->nextNode;
93+
}
94+
}
95+
96+
// Pop the top element from the MinStack
97+
void minStackPop(MinStack* obj) {
98+
if (obj->currentNode != NULL) {
99+
Node* temp = obj->currentNode;
100+
obj->currentNode = obj->currentNode->previousNode;
101+
free(temp);
102+
}
103+
}
104+
105+
// Get the top element of the MinStack
106+
int minStackTop(MinStack* obj) {
107+
if (obj->currentNode != NULL) {
108+
return obj->currentNode->data;
109+
}
110+
return INT_MIN; // Or an error code if stack is empty
111+
}
112+
113+
// Get the minimum element in the MinStack
114+
int minStackGetMin(MinStack* obj) {
115+
if (obj->currentNode != NULL) {
116+
return obj->currentNode->min;
117+
}
118+
return INT_MIN; // Or an error code if stack is empty
119+
}
120+
121+
// Free the MinStack
122+
void minStackFree(MinStack* obj) {
123+
while (obj->currentNode != NULL) {
124+
minStackPop(obj);
125+
}
126+
free(obj);
127+
}
128+
129+
/**
130+
* Your MinStack struct will be instantiated and called as such:
131+
* MinStack* obj = minStackCreate();
132+
* minStackPush(obj, val);
133+
134+
* minStackPop(obj);
135+
136+
* int param_3 = minStackTop(obj);
137+
138+
* int param_4 = minStackGetMin(obj);
139+
140+
* minStackFree(obj);
141+
*/
142+
```
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 160\. Intersection of Two Linked Lists
5+
6+
Easy
7+
8+
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
9+
10+
For example, the following two linked lists begin to intersect at node `c1`:
11+
12+
![](https://assets.leetcode.com/uploads/2021/03/05/160_statement.png)
13+
14+
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
15+
16+
**Note** that the linked lists must **retain their original structure** after the function returns.
17+
18+
**Custom Judge:**
19+
20+
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
21+
22+
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
23+
* `listA` - The first linked list.
24+
* `listB` - The second linked list.
25+
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
26+
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
27+
28+
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
29+
30+
**Example 1:**
31+
32+
![](https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png)
33+
34+
**Input:** intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
35+
36+
**Output:** Intersected at '8'
37+
38+
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
39+
40+
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory.
41+
42+
**Example 2:**
43+
44+
![](https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png)
45+
46+
**Input:** intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
47+
48+
**Output:** Intersected at '2'
49+
50+
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
51+
52+
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
53+
54+
**Example 3:**
55+
56+
![](https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png)
57+
58+
**Input:** intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
59+
60+
**Output:** No intersection
61+
62+
**Explanation:** From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null.
63+
64+
**Constraints:**
65+
66+
* The number of nodes of `listA` is in the `m`.
67+
* The number of nodes of `listB` is in the `n`.
68+
* <code>1 <= m, n <= 3 * 10<sup>4</sup></code>
69+
* <code>1 <= Node.val <= 10<sup>5</sup></code>
70+
* `0 <= skipA < m`
71+
* `0 <= skipB < n`
72+
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
73+
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
74+
75+
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
76+
77+
## Solution
78+
79+
```c
80+
#include <stdio.h>
81+
#include <stdlib.h>
82+
83+
/**
84+
* Definition for singly-linked list.
85+
* struct ListNode {
86+
* int val;
87+
* struct ListNode *next;
88+
* };
89+
*/
90+
// Function to find the intersection node of two linked lists
91+
struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {
92+
struct ListNode* node1 = headA;
93+
struct ListNode* node2 = headB;
94+
95+
// Loop until the two pointers meet at the intersection or both become NULL
96+
while (node1 != node2) {
97+
// If node1 reaches the end of list A, switch to the head of list B
98+
node1 = (node1 == NULL) ? headB : node1->next;
99+
// If node2 reaches the end of list B, switch to the head of list A
100+
node2 = (node2 == NULL) ? headA : node2->next;
101+
}
102+
103+
// Both pointers will either meet at the intersection node or at NULL if no intersection exists
104+
return node1;
105+
}
106+
```
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
35+
#include <stdio.h>
36+
37+
// Function to find the majority element in an array
38+
int majorityElement(int* arr, int arrSize) {
39+
int count = 1;
40+
int majority = arr[0];
41+
42+
// First pass to find a potential majority element using Boyer-Moore Voting Algorithm
43+
for (int i = 1; i < arrSize; i++) {
44+
if (arr[i] == majority) {
45+
count++;
46+
} else {
47+
if (count > 1) {
48+
count--;
49+
} else {
50+
majority = arr[i];
51+
count = 1;
52+
}
53+
}
54+
}
55+
56+
// Second pass to confirm if the candidate is indeed the majority element
57+
count = 0;
58+
for (int i = 0; i < arrSize; i++) {
59+
if (arr[i] == majority) {
60+
count++;
61+
}
62+
}
63+
64+
// Check if the majority element appears more than n/2 times
65+
if (count >= (arrSize / 2) + 1) {
66+
return majority;
67+
} else {
68+
return -1;
69+
}
70+
}
71+
```
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 189\. Rotate Array
5+
6+
Medium
7+
8+
Given an array, rotate the array to the right by `k` steps, where `k` is non-negative.
9+
10+
**Example 1:**
11+
12+
**Input:** nums = [1,2,3,4,5,6,7], k = 3
13+
14+
**Output:** [5,6,7,1,2,3,4]
15+
16+
**Explanation:**
17+
18+
rotate 1 steps to the right: [7,1,2,3,4,5,6]
19+
20+
rotate 2 steps to the right: [6,7,1,2,3,4,5]
21+
22+
rotate 3 steps to the right: [5,6,7,1,2,3,4]
23+
24+
**Example 2:**
25+
26+
**Input:** nums = [-1,-100,3,99], k = 2
27+
28+
**Output:** [3,99,-1,-100]
29+
30+
**Explanation:**
31+
32+
rotate 1 steps to the right: [99,-1,-100,3]
33+
34+
rotate 2 steps to the right: [3,99,-1,-100]
35+
36+
**Constraints:**
37+
38+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
39+
* <code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code>
40+
* <code>0 <= k <= 10<sup>5</sup></code>
41+
42+
**Follow up:**
43+
44+
* Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem.
45+
* Could you do it in-place with `O(1)` extra space?
46+
47+
## Solution
48+
49+
```c
50+
#include <stdio.h>
51+
52+
// Helper function to reverse a subarray in place
53+
void reverse(int* nums, int l, int r) {
54+
while (l < r) {
55+
int temp = nums[l];
56+
nums[l] = nums[r];
57+
nums[r] = temp;
58+
l++;
59+
r--;
60+
}
61+
}
62+
63+
// Function to rotate the array to the right by k steps
64+
void rotate(int* nums, int numsSize, int k) {
65+
int n = numsSize;
66+
k = k % n; // Handle cases where k is greater than n
67+
int t = n - k;
68+
69+
// Reverse different parts of the array in three steps
70+
reverse(nums, 0, t - 1); // Reverse the first part (0 to t - 1)
71+
reverse(nums, t, n - 1); // Reverse the second part (t to n - 1)
72+
reverse(nums, 0, n - 1); // Reverse the whole array (0 to n - 1)
73+
}
74+
```
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
36+
#include <stdio.h>
37+
38+
// Helper function to find the maximum of two integers
39+
int max(int a, int b) {
40+
return (a > b) ? a : b;
41+
}
42+
43+
// Function to calculate the maximum profit from robbing houses
44+
int rob(int* nums, int numsSize) {
45+
if (numsSize == 0) {
46+
return 0;
47+
}
48+
if (numsSize == 1) {
49+
return nums[0];
50+
}
51+
if (numsSize == 2) {
52+
return max(nums[0], nums[1]);
53+
}
54+
55+
// Array to store the maximum profit up to each house
56+
int profit[numsSize];
57+
profit[0] = nums[0];
58+
profit[1] = max(nums[1], nums[0]);
59+
60+
// Fill in the profit array using dynamic programming
61+
for (int i = 2; i < numsSize; i++) {
62+
profit[i] = max(profit[i - 1], nums[i] + profit[i - 2]);
63+
}
64+
65+
// The last element in the profit array contains the maximum profit
66+
return profit[numsSize - 1];
67+
}
68+
```
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
54+
void DFS(int row, int col, int m, int n, char** grid) {
55+
if (row < 0 || row >= m || col < 0 || col >= n || grid[row][col] == '0') {
56+
return;
57+
}
58+
59+
grid[row][col] = '0'; // Mark the current cell as visited
60+
61+
// Visit the neighboring cells
62+
DFS(row + 1, col, m, n, grid);
63+
DFS(row - 1, col, m, n, grid);
64+
DFS(row, col + 1, m, n, grid);
65+
DFS(row, col - 1, m, n, grid);
66+
}
67+
68+
int numIslands(char** grid, int gridSize, int* gridColSize) {
69+
if (gridSize == 0) {
70+
return 0;
71+
}
72+
73+
int m = gridSize; // ROW
74+
int n = *gridColSize; // COL
75+
int numIslands = 0;
76+
77+
for (int i = 0; i < m; i++) {
78+
for (int j = 0; j < n; j++) {
79+
if (grid[i][j] == '1') { // grid[row][col]
80+
numIslands++;
81+
DFS(i, j, m, n, grid);
82+
}
83+
}
84+
}
85+
86+
return numIslands;
87+
}
88+
```
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-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/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+
```c
42+
#include <stdio.h>
43+
#include <stdlib.h>
44+
45+
/**
46+
* Definition for singly-linked list.
47+
* struct ListNode {
48+
* int val;
49+
* struct ListNode *next;
50+
* };
51+
*/
52+
// Function to reverse a linked list
53+
struct ListNode* reverseList(struct ListNode* head) {
54+
struct ListNode* prev = NULL; // Pointer to the previous node
55+
struct ListNode* curr = head; // Pointer to the current node
56+
57+
while (curr != NULL) {
58+
struct ListNode* next = curr->next; // Store the next node
59+
curr->next = prev; // Reverse the current node's pointer
60+
prev = curr; // Move prev to the current node
61+
curr = next; // Move to the next node
62+
}
63+
64+
return prev; // New head of the reversed list
65+
}
66+
```
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 207\. Course Schedule
5+
6+
Medium
7+
8+
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you **must** take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.
9+
10+
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
11+
12+
Return `true` if you can finish all courses. Otherwise, return `false`.
13+
14+
**Example 1:**
15+
16+
**Input:** numCourses = 2, prerequisites = \[\[1,0]]
17+
18+
**Output:** true
19+
20+
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
21+
22+
**Example 2:**
23+
24+
**Input:** numCourses = 2, prerequisites = \[\[1,0],[0,1]]
25+
26+
**Output:** false
27+
28+
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
29+
30+
**Constraints:**
31+
32+
* `1 <= numCourses <= 2000`
33+
* `0 <= prerequisites.length <= 5000`
34+
* `prerequisites[i].length == 2`
35+
* <code>0 <= a<sub>i</sub>, b<sub>i</sub> < numCourses</code>
36+
* All the pairs prerequisites[i] are **unique**.
37+
38+
## Solution
39+
40+
```c
41+
typedef struct node {
42+
int V;
43+
struct node* next;
44+
} node;
45+
46+
bool dfs(node** adjlist, bool* visited, bool* recStack, int current);
47+
48+
bool canFinish(int numCourses, int** prerequisites, int prerequisitesSize, int* prerequisitesColSize) {
49+
node** adjlist = malloc(sizeof(node*) * numCourses);
50+
for (int i = 0; i < numCourses; i++) {
51+
adjlist[i] = NULL;
52+
}
53+
for (int i = 0; i < prerequisitesSize; i++) {
54+
node* Node = malloc(sizeof(node));
55+
Node->V = prerequisites[i][0];
56+
Node->next = adjlist[prerequisites[i][1]];
57+
adjlist[prerequisites[i][1]] = Node;
58+
}
59+
60+
bool* visited = calloc(sizeof(bool), numCourses);
61+
bool* recStack = calloc(sizeof(bool), numCourses);
62+
63+
for (int V = 0; V < numCourses; V++) {
64+
if (dfs(adjlist, visited, recStack, V)) {
65+
return false;
66+
}
67+
}
68+
return true;
69+
}
70+
71+
bool dfs(node** adjlist, bool* visited, bool* recStack, int current) {
72+
if (recStack[current]) {
73+
return true;
74+
}
75+
if (visited[current]) {
76+
return false;
77+
}
78+
visited[current] = true;
79+
recStack[current] = true;
80+
81+
for (node* Node = adjlist[current]; Node; Node = Node->next) {
82+
if (dfs(adjlist, visited, recStack, Node->V)) {
83+
return true;
84+
}
85+
}
86+
87+
recStack[current] = false;
88+
return false;
89+
}
90+
```
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 208\. Implement Trie (Prefix Tree)
5+
6+
Medium
7+
8+
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
9+
10+
Implement the Trie class:
11+
12+
* `Trie()` Initializes the trie object.
13+
* `void insert(String word)` Inserts the string `word` into the trie.
14+
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
15+
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
16+
17+
**Example 1:**
18+
19+
**Input** ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
20+
21+
**Output:** [null, null, true, false, true, null, true]
22+
23+
**Explanation:**
24+
25+
Trie trie = new Trie();
26+
27+
trie.insert("apple");
28+
29+
trie.search("apple"); // return True
30+
31+
trie.search("app"); // return False
32+
33+
trie.startsWith("app"); // return True
34+
35+
trie.insert("app");
36+
37+
trie.search("app"); // return True
38+
39+
**Constraints:**
40+
41+
* `1 <= word.length, prefix.length <= 2000`
42+
* `word` and `prefix` consist only of lowercase English letters.
43+
* At most <code>3 * 10<sup>4</sup></code> calls **in total** will be made to `insert`, `search`, and `startsWith`.
44+
45+
## Solution
46+
47+
```c
48+
#include <stdio.h>
49+
#include <stdlib.h>
50+
#include <stdbool.h>
51+
#include <string.h>
52+
53+
#define ALPHABET_SIZE 26
54+
55+
typedef struct TrieNode {
56+
struct TrieNode* children[ALPHABET_SIZE];
57+
bool isWord;
58+
} TrieNode;
59+
60+
typedef struct Trie {
61+
TrieNode* root;
62+
} Trie;
63+
64+
// Helper function to create a new TrieNode
65+
TrieNode* createTrieNode() {
66+
TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
67+
for (int i = 0; i < ALPHABET_SIZE; i++) {
68+
node->children[i] = NULL;
69+
}
70+
node->isWord = false;
71+
return node;
72+
}
73+
74+
// Function to create a new Trie
75+
Trie* trieCreate() {
76+
Trie* trie = (Trie*)malloc(sizeof(Trie));
77+
trie->root = createTrieNode();
78+
return trie;
79+
}
80+
81+
// Function to insert a word into the Trie
82+
void trieInsert(Trie* obj, char* word) {
83+
TrieNode* node = obj->root;
84+
for (int i = 0; i < strlen(word); i++) {
85+
int index = word[i] - 'a';
86+
if (node->children[index] == NULL) {
87+
node->children[index] = createTrieNode();
88+
}
89+
node = node->children[index];
90+
}
91+
node->isWord = true;
92+
}
93+
94+
// Recursive helper function to search for a word or prefix
95+
bool trieSearchHelper(TrieNode* node, char* word, bool checkPrefix) {
96+
for (int i = 0; i < strlen(word); i++) {
97+
int index = word[i] - 'a';
98+
if (node->children[index] == NULL) {
99+
return false;
100+
}
101+
node = node->children[index];
102+
}
103+
return checkPrefix || node->isWord;
104+
}
105+
106+
// Function to search for a complete word in the Trie
107+
bool trieSearch(Trie* obj, char* word) {
108+
return trieSearchHelper(obj->root, word, false);
109+
}
110+
111+
// Function to check if any word in the Trie starts with the given prefix
112+
bool trieStartsWith(Trie* obj, char* prefix) {
113+
return trieSearchHelper(obj->root, prefix, true);
114+
}
115+
116+
// Recursive function to free all TrieNodes
117+
void trieFreeNode(TrieNode* node) {
118+
if (node == NULL) return;
119+
for (int i = 0; i < ALPHABET_SIZE; i++) {
120+
trieFreeNode(node->children[i]);
121+
}
122+
free(node);
123+
}
124+
125+
// Function to free the entire Trie
126+
void trieFree(Trie* obj) {
127+
trieFreeNode(obj->root);
128+
free(obj);
129+
}
130+
131+
/**
132+
* Your Trie struct will be instantiated and called as such:
133+
* Trie* obj = trieCreate();
134+
* trieInsert(obj, word);
135+
136+
* bool param_2 = trieSearch(obj, word);
137+
138+
* bool param_3 = trieStartsWith(obj, prefix);
139+
140+
* trieFree(obj);
141+
*/
142+
```
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 215\. Kth Largest Element in an Array
5+
6+
Medium
7+
8+
Given an integer array `nums` and an integer `k`, return _the_ <code>k<sup>th</sup></code> _largest element in the array_.
9+
10+
Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.
11+
12+
You must solve it in `O(n)` time complexity.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [3,2,1,5,6,4], k = 2
17+
18+
**Output:** 5
19+
20+
**Example 2:**
21+
22+
**Input:** nums = [3,2,3,1,2,4,5,5,6], k = 4
23+
24+
**Output:** 4
25+
26+
**Constraints:**
27+
28+
* <code>1 <= k <= nums.length <= 10<sup>5</sup></code>
29+
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
30+
31+
## Solution
32+
33+
```c
34+
#include <stdbool.h>
35+
#include <stdlib.h>
36+
37+
int findKthLargest(int* nums, int numsSize, int k) {
38+
int positiveArr[10001] = {0};
39+
int negativeArr[10001] = {0};
40+
int cumulativeCount = 0;
41+
int result = 0;
42+
bool found = false;
43+
44+
// Count occurrences of each element
45+
for (int i = 0; i < numsSize; i++) {
46+
if (nums[i] >= 0) {
47+
positiveArr[nums[i]]++;
48+
} else {
49+
negativeArr[abs(nums[i])]++;
50+
}
51+
}
52+
53+
// Search for the k-th largest in positive numbers
54+
for (int i = 10000; i >= 0; i--) {
55+
cumulativeCount += positiveArr[i];
56+
if (cumulativeCount >= k) {
57+
result = i;
58+
found = true;
59+
break;
60+
}
61+
}
62+
63+
// If k-th largest is not found in positive numbers, search in negative numbers
64+
if (!found) {
65+
for (int i = 1; i <= 10000; i++) {
66+
cumulativeCount += negativeArr[i];
67+
if (cumulativeCount >= k) {
68+
result = -i;
69+
break;
70+
}
71+
}
72+
}
73+
74+
return result;
75+
}
76+
```
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 221\. Maximal Square
5+
6+
Medium
7+
8+
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg)
13+
14+
**Input:** matrix = \[\["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
15+
16+
**Output:** 4
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg)
21+
22+
**Input:** matrix = \[\["0","1"],["1","0"]]
23+
24+
**Output:** 1
25+
26+
**Example 3:**
27+
28+
**Input:** matrix = \[\["0"]]
29+
30+
**Output:** 0
31+
32+
**Constraints:**
33+
34+
* `m == matrix.length`
35+
* `n == matrix[i].length`
36+
* `1 <= m, n <= 300`
37+
* `matrix[i][j]` is `'0'` or `'1'`.
38+
39+
## Solution
40+
41+
```c
42+
#include <stdio.h>
43+
#include <stdlib.h>
44+
45+
int min(int a, int b) {
46+
return a < b ? a : b;
47+
}
48+
49+
int min3(int a, int b, int c) {
50+
return min(a, min(b, c));
51+
}
52+
53+
int maximalSquare(char** matrix, int matrixSize, int* matrixColSize) {
54+
if (matrixSize == 0 || matrixColSize[0] == 0) {
55+
return 0;
56+
}
57+
58+
int m = matrixSize;
59+
int n = matrixColSize[0];
60+
61+
// Create a dynamic programming (dp) array initialized to 0
62+
int** dp = (int**)malloc((m + 1) * sizeof(int*));
63+
for (int i = 0; i <= m; i++) {
64+
dp[i] = (int*)calloc(n + 1, sizeof(int));
65+
}
66+
67+
int max = 0;
68+
69+
// Fill the dp array based on the matrix values
70+
for (int i = 1; i <= m; i++) {
71+
for (int j = 1; j <= n; j++) {
72+
if (matrix[i - 1][j - 1] == '1') {
73+
dp[i][j] = 1 + min3(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
74+
if (dp[i][j] > max) {
75+
max = dp[i][j];
76+
}
77+
}
78+
}
79+
}
80+
81+
// Free allocated memory for dp array
82+
for (int i = 0; i <= m; i++) {
83+
free(dp[i]);
84+
}
85+
free(dp);
86+
87+
return max * max;
88+
}
89+
```
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 226\. Invert Binary Tree
5+
6+
Easy
7+
8+
Given the `root` of a binary tree, invert the tree, and return _its root_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg)
13+
14+
**Input:** root = [4,2,7,1,3,6,9]
15+
16+
**Output:** [4,7,2,9,6,3,1]
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg)
21+
22+
**Input:** root = [2,1,3]
23+
24+
**Output:** [2,3,1]
25+
26+
**Example 3:**
27+
28+
**Input:** root = []
29+
30+
**Output:** []
31+
32+
**Constraints:**
33+
34+
* The number of nodes in the tree is in the range `[0, 100]`.
35+
* `-100 <= Node.val <= 100`
36+
37+
## Solution
38+
39+
```c
40+
/**
41+
* Definition for a binary tree node.
42+
* struct TreeNode {
43+
* int val;
44+
* struct TreeNode *left;
45+
* struct TreeNode *right;
46+
* };
47+
*/
48+
#include <stdio.h>
49+
#include <stdlib.h>
50+
51+
// Function to invert a binary tree
52+
struct TreeNode* invertTree(struct TreeNode* root) {
53+
if (root == NULL) {
54+
return NULL;
55+
}
56+
// Swap the left and right children
57+
struct TreeNode* temp = root->left;
58+
root->left = invertTree(root->right);
59+
root->right = invertTree(temp);
60+
return root;
61+
}
62+
63+
// Helper function to create a new tree node
64+
struct TreeNode* createNode(int val) {
65+
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
66+
newNode->val = val;
67+
newNode->left = NULL;
68+
newNode->right = NULL;
69+
return newNode;
70+
}
71+
72+
// Helper function to print the tree in order (for testing purposes)
73+
void printInOrder(struct TreeNode* root) {
74+
if (root == NULL) return;
75+
printInOrder(root->left);
76+
printf("%d ", root->val);
77+
printInOrder(root->right);
78+
}
79+
80+
// Helper function to free the tree memory
81+
void freeTree(struct TreeNode* root) {
82+
if (root == NULL) return;
83+
freeTree(root->left);
84+
freeTree(root->right);
85+
free(root);
86+
}
87+
```
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 230\. Kth Smallest Element in a BST
5+
6+
Medium
7+
8+
Given the `root` of a binary search tree, and an integer `k`, return _the_ <code>k<sup>th</sup></code> _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg)
13+
14+
**Input:** root = [3,1,4,null,2], k = 1
15+
16+
**Output:** 1
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg)
21+
22+
**Input:** root = [5,3,6,2,4,null,null,1], k = 3
23+
24+
**Output:** 3
25+
26+
**Constraints:**
27+
28+
* The number of nodes in the tree is `n`.
29+
* <code>1 <= k <= n <= 10<sup>4</sup></code>
30+
* <code>0 <= Node.val <= 10<sup>4</sup></code>
31+
32+
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
33+
34+
## Solution
35+
36+
```c
37+
/**
38+
* Definition for a binary tree node.
39+
* struct TreeNode {
40+
* int val;
41+
* struct TreeNode *left;
42+
* struct TreeNode *right;
43+
* };
44+
*/
45+
#include <stdio.h>
46+
#include <stdlib.h>
47+
48+
// Helper struct to hold state across recursive calls
49+
struct Solution {
50+
int k;
51+
int count;
52+
int val;
53+
};
54+
55+
// Function to create a new tree node
56+
struct TreeNode* createNode(int val) {
57+
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
58+
newNode->val = val;
59+
newNode->left = NULL;
60+
newNode->right = NULL;
61+
return newNode;
62+
}
63+
64+
// Helper function to perform in-order traversal and find the k-th smallest element
65+
void calculate(struct Solution* sol, struct TreeNode* node) {
66+
if (node == NULL || sol->count >= sol->k) {
67+
return;
68+
}
69+
70+
if (node->left != NULL) {
71+
calculate(sol, node->left);
72+
}
73+
74+
sol->count++;
75+
if (sol->count == sol->k) {
76+
sol->val = node->val;
77+
return;
78+
}
79+
80+
if (node->right != NULL) {
81+
calculate(sol, node->right);
82+
}
83+
}
84+
85+
// Function to find the k-th smallest element in the BST
86+
int kthSmallest(struct TreeNode* root, int k) {
87+
struct Solution sol = {k, 0, 0};
88+
calculate(&sol, root);
89+
return sol.val;
90+
}
91+
92+
// Helper function to free the tree memory
93+
void freeTree(struct TreeNode* root) {
94+
if (root == NULL) return;
95+
freeTree(root->left);
96+
freeTree(root->right);
97+
free(root);
98+
}
99+
```
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 234\. Palindrome Linked List
5+
6+
Easy
7+
8+
Given the `head` of a singly linked list, return `true` _if it is a palindrome or_ `false` _otherwise_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg)
13+
14+
**Input:** head = [1,2,2,1]
15+
16+
**Output:** true
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg)
21+
22+
**Input:** head = [1,2]
23+
24+
**Output:** false
25+
26+
**Constraints:**
27+
28+
* The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.
29+
* `0 <= Node.val <= 9`
30+
31+
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
32+
33+
## Solution
34+
35+
```c
36+
/**
37+
* Definition for singly-linked list.
38+
* struct ListNode {
39+
* int val;
40+
* struct ListNode *next;
41+
* };
42+
*/
43+
#include <stdbool.h>
44+
45+
// Function to check if the linked list is a palindrome
46+
bool isPalindrome(struct ListNode* head) {
47+
if (head == NULL || head->next == NULL) {
48+
return true;
49+
}
50+
51+
// Step 1: Calculate the length of the list
52+
int len = 0;
53+
struct ListNode* right = head;
54+
while (right != NULL) {
55+
right = right->next;
56+
len++;
57+
}
58+
59+
// Step 2: Find the middle of the list and reverse the right half
60+
len = len / 2;
61+
right = head;
62+
for (int i = 0; i < len; i++) {
63+
right = right->next;
64+
}
65+
66+
// Reverse the right half of the list
67+
struct ListNode* prev = NULL;
68+
while (right != NULL) {
69+
struct ListNode* next = right->next;
70+
right->next = prev;
71+
prev = right;
72+
right = next;
73+
}
74+
75+
// Step 3: Compare the left half and the reversed right half
76+
struct ListNode* left = head;
77+
while (prev != NULL) {
78+
if (left->val != prev->val) {
79+
return false;
80+
}
81+
left = left->next;
82+
prev = prev->next;
83+
}
84+
85+
return true;
86+
}
87+
```
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-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 236\. Lowest Common Ancestor of a Binary Tree
5+
6+
Medium
7+
8+
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
9+
10+
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): “The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**).”
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)
15+
16+
**Input:** root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
17+
18+
**Output:** 3
19+
20+
**Explanation:** The LCA of nodes 5 and 1 is 3.
21+
22+
**Example 2:**
23+
24+
![](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)
25+
26+
**Input:** root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
27+
28+
**Output:** 5
29+
30+
**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
31+
32+
**Example 3:**
33+
34+
**Input:** root = [1,2], p = 1, q = 2
35+
36+
**Output:** 1
37+
38+
**Constraints:**
39+
40+
* The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.
41+
* <code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code>
42+
* All `Node.val` are **unique**.
43+
* `p != q`
44+
* `p` and `q` will exist in the tree.
45+
46+
## Solution
47+
48+
```c
49+
/**
50+
* Definition for a binary tree node.
51+
* struct TreeNode {
52+
* int val;
53+
* struct TreeNode *left;
54+
* struct TreeNode *right;
55+
* };
56+
*/
57+
#include <stdio.h>
58+
#include <stdlib.h>
59+
60+
// Function to find the lowest common ancestor of two nodes in the binary tree
61+
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
62+
// Base case: if the root is NULL or root matches either p or q
63+
if (root == NULL || root == p || root == q) {
64+
return root;
65+
}
66+
67+
// Recursively find the LCA in the left and right subtrees
68+
struct TreeNode* left = lowestCommonAncestor(root->left, p, q);
69+
struct TreeNode* right = lowestCommonAncestor(root->right, p, q);
70+
71+
// If both left and right are non-null, the current root is the LCA
72+
if (left != NULL && right != NULL) {
73+
return root;
74+
}
75+
76+
// Otherwise, return the non-null child (if both are NULL, return NULL)
77+
return left != NULL ? left : right;
78+
}
79+
```
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 238\. Product of Array Except Self
5+
6+
Medium
7+
8+
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
9+
10+
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
11+
12+
You must write an algorithm that runs in `O(n)` time and without using the division operation.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [1,2,3,4]
17+
18+
**Output:** [24,12,8,6]
19+
20+
**Example 2:**
21+
22+
**Input:** nums = [-1,1,0,-3,3]
23+
24+
**Output:** [0,0,9,0,0]
25+
26+
**Constraints:**
27+
28+
* <code>2 <= nums.length <= 10<sup>5</sup></code>
29+
* `-30 <= nums[i] <= 30`
30+
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
31+
32+
**Follow up:** Can you solve the problem in `O(1) `extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
33+
34+
## Solution
35+
36+
```c
37+
#include <stdio.h>
38+
39+
/**
40+
* Note: The returned array must be malloced, assume caller calls free().
41+
*/
42+
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
43+
int* ans = (int*)malloc(numsSize * sizeof(int));
44+
int product = 1;
45+
46+
// Calculate the product of all elements
47+
for (int i = 0; i < numsSize; i++) {
48+
product *= nums[i];
49+
}
50+
51+
// Calculate the result for each element
52+
for (int i = 0; i < numsSize; i++) {
53+
if (nums[i] != 0) {
54+
ans[i] = product / nums[i];
55+
} else {
56+
int p = 1;
57+
for (int j = 0; j < numsSize; j++) {
58+
if (j != i) {
59+
p *= nums[j];
60+
}
61+
}
62+
ans[i] = p;
63+
}
64+
}
65+
66+
*returnSize = numsSize;
67+
return ans;
68+
}
69+
```
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-C/LeetCode-in-C?label=Stars&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-C/LeetCode-in-C?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-C/LeetCode-in-C/fork)
3+
4+
## 239\. Sliding Window Maximum
5+
6+
Hard
7+
8+
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
9+
10+
Return _the max sliding window_.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [1,3,-1,-3,5,3,6,7], k = 3
15+
16+
**Output:** [3,3,5,5,6,7]
17+
18+
**Explanation:**
19+
20+
Window position Max
21+
22+
--------------- -----
23+
24+
[1 3 -1] -3 5 3 6 7 **3**
25+
26+
1 [3 -1 -3] 5 3 6 7 **3**
27+
28+
1 3 [-1 -3 5] 3 6 7 **5**
29+
30+
1 3 -1 [-3 5 3] 6 7 **5**
31+
32+
1 3 -1 -3 [5 3 6] 7 **6**
33+
34+
1 3 -1 -3 5 [3 6 7] **7**
35+
36+
**Example 2:**
37+
38+
**Input:** nums = [1], k = 1
39+
40+
**Output:** [1]
41+
42+
**Constraints:**
43+
44+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
45+
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
46+
* `1 <= k <= nums.length`
47+
48+
## Solution
49+
50+
```c
51+
/**
52+
* Note: The returned array must be malloced, assume caller calls free().
53+
*/
54+
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) {
55+
if (k == 1) {
56+
*returnSize = numsSize;
57+
return nums;
58+
}
59+
60+
int *queue = malloc(sizeof(int) * numsSize);
61+
int *res = malloc(sizeof(int) * (numsSize - k + 1));
62+
int rear = -1;
63+
int qLen = 0;
64+
int front = 0;
65+
int i = 0;
66+
int resCount = 0;
67+
68+
for (i = 0; i < numsSize; i++) {
69+
// Remove elements that are out of the window
70+
while (qLen > 0 && i - queue[front] >= k) {
71+
front++;
72+
qLen--;
73+
}
74+
75+
// Remove elements from the back of the queue that are less than the current element
76+
while (qLen > 0 && nums[i] > nums[queue[rear]]) {
77+
rear--;
78+
qLen--;
79+
}
80+
81+
// Add the current element index to the queue
82+
queue[++rear] = i;
83+
qLen++;
84+
85+
// Once we have a complete window, add the maximum element (from the front of the queue) to the result
86+
if (i >= k - 1) {
87+
res[resCount++] = nums[queue[front]];
88+
}
89+
}
90+
91+
*returnSize = resCount;
92+
return res;
93+
}
94+
```

0 commit comments

Comments
 (0)
Please sign in to comment.