Skip to content

Commit 1844dc6

Browse files
author
ayoubzulfiqar
committed
leetcode
1 parent fb1487b commit 1844dc6

7 files changed

+323
-1
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ This repo contain leetcode solution using DART and GO programming language. Most
7272
- [**203.** Remove Linked List Elements](RemoveLinkedListElements/remove_linked_list_elements.dart)
7373
- [**1578.** Minimum Time to Make Rope Colorful](MinimumTimeToMakeRopeColorful/minimum_time_to_make_rope_colorful.dart)
7474
- [**205.** Isomorphic Strings](IsomorphicStrings/isomorphic_strings.dart)
75-
- [**623.** Add One Row to Tree](AddOneRowToTree/add_one_row_to_tree.dart)
75+
- [**623.** Add One Row to Tree](AddOneRowToTree/add_one_row_to_tree.dart)
7676
- [**981.** Time Based Key-Value Store](TimeBasedKeyValueStore/time_based_key_value_store.dart)
7777
- [**732.** My Calendar III](MyCalendar-III/my_calendar_III.dart)
7878
- [**206.** Reverse Linked List](ReverseLinkedList/reverse_linked_list.dart)
@@ -145,6 +145,8 @@ This repo contain leetcode solution using DART and GO programming language. Most
145145
- [**295.** Find Median from Data Stream](FindMedianFromDataStream/find_median_from_data_stream.dart)
146146
- [**279.** Perfect Squares](PerfectSquares/perfect_squares.dart)
147147
- [**36.** Valid Sudoku](ValidSudoku/valid_sudoku.dart)
148+
- [**79.** Word Search](WordSearch/word_search.dart)
149+
- [**907.** Sum of Sub-Array Minimums](SumOfSubarrayMinimums\sum_of_subarray_minimums.dart)
148150

149151
## Reach me via
150152

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/*
2+
3+
- * 907. Sum of Sub-array Minimums *-
4+
5+
6+
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
7+
8+
9+
10+
Example 1:
11+
12+
Input: arr = [3,1,2,4]
13+
Output: 17
14+
Explanation:
15+
Sub-arrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
16+
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
17+
Sum is 17.
18+
Example 2:
19+
20+
Input: arr = [11,81,94,43,3]
21+
Output: 444
22+
23+
24+
Constraints:
25+
26+
1 <= arr.length <= 3 * 104
27+
1 <= arr[i] <= 3 * 104
28+
29+
30+
*/
31+
32+
import 'dart:collection';
33+
import 'dart:math';
34+
35+
class A {
36+
// MonoStack
37+
int sumSubarrayMins(List<int> arr) {
38+
int res = 0;
39+
int sz = arr.length;
40+
int mod = 1000000007;
41+
List<int> ms = [-1];
42+
for (int i = 0; i <= sz; ++i) {
43+
while (ms.last != -1 && (i == sz || arr[i] <= arr[ms.last])) {
44+
int j = ms.last;
45+
ms.removeLast();
46+
res = (res + arr[j] * (j - ms.last) * (i - j)) % mod;
47+
}
48+
ms.add(i);
49+
}
50+
return res;
51+
}
52+
}
53+
54+
class B {
55+
int sumSubarrayMins(List<int> arr) {
56+
int res = 0;
57+
int n = arr.length;
58+
int mod = (1e9 + 7).toInt();
59+
for (int end = 0; end < n; end++) {
60+
for (int start = 0; start <= end; start++) {
61+
int mini = double.maxFinite.toInt();
62+
for (int i = start; i <= end; i++) mini = min(mini, arr[i]);
63+
res = (res + mini) % mod;
64+
}
65+
}
66+
return res;
67+
}
68+
}
69+
70+
class C {
71+
int sumSubarrayMins(List<int> arr) {
72+
int n = arr.length;
73+
List<int> leftMin = List.filled(n,
74+
0); //store no. elements between current element and left smaller element.
75+
List<int> rightMin = List.filled(n,
76+
0); //store no. elements between current element and right smaller element.
77+
int mod = (1e9 + 7).toInt();
78+
Queue<int> ind = Queue();
79+
for (int i = 0; i < n; i++) {
80+
while (ind.isNotEmpty && arr[ind.last] > arr[i]) ind.removeLast();
81+
leftMin[i] = ind.isEmpty ? i + 1 : i - ind.last;
82+
ind.add(i);
83+
}
84+
ind = Queue();
85+
for (int i = n - 1; i >= 0; i--) {
86+
while (ind.isNotEmpty && arr[ind.last] >= arr[i]) ind.removeLast();
87+
rightMin[i] = ind.isEmpty ? n - i : ind.last - i;
88+
ind.add(i);
89+
}
90+
int res = 0;
91+
for (int i = 0; i < n; i++)
92+
res = (res + arr[i] * leftMin[i] * rightMin[i]) %
93+
mod; //finding sum of minimum of all possible subarrays with current element as minimum.
94+
return res;
95+
}
96+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package main
2+
3+
func sumSubarrayMins(arr []int) int {
4+
arr = append(arr, 0)
5+
stack, res, j := []int{-1}, 0, 0
6+
for i, n := range arr {
7+
for len(stack) > 1 && arr[stack[len(stack)-1]] > n {
8+
j, stack = stack[len(stack)-1], stack[:len(stack)-1]
9+
res += (j - stack[len(stack)-1]) * (i - j) * arr[j]
10+
res %= 1_000_000_007
11+
}
12+
stack = append(stack, i)
13+
}
14+
return res
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# 🔥 Sum of Sub-array Minimums 🔥 || 3 Solutions || Simple Fast and Easy || with Explanation
2+
3+
## Solution - 1 MonoStack
4+
5+
### Monotonic stack
6+
7+
A function is said to be monotonic if it preserves a given order. A monotonically increasing function never decreases. Likewise, a monotonically decreasing function never increases.
8+
Similarly, a monotonic stack contains elements that preserve a given order. A monotone increasing stack contains elements that never decrease. Likewise, a monotone decreasing stack contains elements that never increase.
9+
10+
[1,1,1,2,3,4,5,6,7,8,8,9,9,9,10] Monotone Increasing stack
11+
12+
[10,10,9,8,7,6,5,4,4,3,2,1,1,1] Monotone Decreasing stack
13+
14+
```dart
15+
class Solution {
16+
int sumSubarrayMins(List<int> arr) {
17+
int res = 0;
18+
int sz = arr.length;
19+
int mod = 1000000007;
20+
List<int> ms = [-1];
21+
for (int i = 0; i <= sz; ++i) {
22+
while (ms.last != -1 && (i == sz || arr[i] <= arr[ms.last])) {
23+
int j = ms.last;
24+
ms.removeLast();
25+
res = (res + arr[j] * (j - ms.last) * (i - j)) % mod;
26+
}
27+
ms.add(i);
28+
}
29+
return res;
30+
}
31+
}
32+
```
33+
34+
## Solution - 2 Brute Force
35+
36+
optimization of above problem: time O(n^2)
37+
in previous solution , we are creating sub-arrays from start to end.
38+
now we will start creating sub-arrays from end to start .
39+
we will create sub-arrays like end to end , end-1 to end , then end-2 to end .....start to end.In this process we are calculating min also.
40+
so no need to calculate min individually
41+
42+
```dart
43+
class Solution {
44+
int sumSubarrayMins(List<int> arr) {
45+
int res = 0;
46+
int n = arr.length;
47+
int mod = (1e9 + 7).toInt();
48+
for (int end = 0; end < n; end++) {
49+
for (int start = 0; start <= end; start++) {
50+
int mini = double.maxFinite.toInt();
51+
for (int i = start; i <= end; i++) mini = min(mini, arr[i]);
52+
res = (res + mini) % mod;
53+
}
54+
}
55+
return res;
56+
}
57+
}
58+
```
59+
60+
## Solution - 3 Queue
61+
62+
most Optimized solution: time O(n)
63+
64+
- for each element do :
65+
66+
1. use a stack to find no. of elements in between current element and smaller element(than current) on both left and right side. (Save them in array)
67+
2. after finding above numbers , we will find number of sub-arrays for which current element is minimum (no of elements on left\*no of elements on right).
68+
3. after finding no. of such sub-arrays multiply it with value of current element to get sum of minimum of all sub-arrays with current element as its minimum.
69+
Note: I know this solution is not intuitive...I also didn't think of this solution on first place.I came up with O(n^2) solution,
70+
then I took hints from youtube videos. (Not the code but some thinking).So its fine if you aren't able to solve this problem in first go.
71+
If you still not able to get it , dry run below code and you will able to it.
72+
73+
```dart
74+
class Solution {
75+
int sumSubarrayMins(List<int> arr) {
76+
int n = arr.length;
77+
List<int> leftMin = List.filled(n,
78+
0); //store no. elements between current element and left smaller element.
79+
List<int> rightMin = List.filled(n,
80+
0); //store no. elements between current element and right smaller element.
81+
int mod = (1e9 + 7).toInt();
82+
Queue<int> ind = Queue();
83+
for (int i = 0; i < n; i++) {
84+
while (ind.isNotEmpty && arr[ind.last] > arr[i]) ind.removeLast();
85+
leftMin[i] = ind.isEmpty ? i + 1 : i - ind.last;
86+
ind.add(i);
87+
}
88+
ind = Queue();
89+
for (int i = n - 1; i >= 0; i--) {
90+
while (ind.isNotEmpty && arr[ind.last] >= arr[i]) ind.removeLast();
91+
rightMin[i] = ind.isEmpty ? n - i : ind.last - i;
92+
ind.add(i);
93+
}
94+
int res = 0;
95+
for (int i = 0; i < n; i++)
96+
res = (res + arr[i] * leftMin[i] * rightMin[i]) %
97+
mod; //finding sum of minimum of all possible sub-arrays with current element as minimum.
98+
return res;
99+
}
100+
}
101+
```

WordSearch/word_search.dart

+107
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
/*
2+
3+
-* 79. Word Search *-
4+
5+
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
6+
7+
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
8+
9+
10+
11+
Example 1:
12+
13+
14+
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
15+
Output: true
16+
Example 2:
17+
18+
19+
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
20+
Output: true
21+
Example 3:
22+
23+
24+
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
25+
Output: false
26+
27+
28+
Constraints:
29+
30+
m == board.length
31+
n = board[i].length
32+
1 <= m, n <= 6
33+
1 <= word.length <= 15
34+
board and word consists of only lowercase and uppercase English letters.
35+
36+
37+
Follow up: Could you use search pruning to make your solution faster with a larger board?
38+
39+
40+
*/
41+
42+
class A {
43+
late List<List<bool>> visited;
44+
late int n;
45+
late int m;
46+
47+
bool exist(List<List<String>> board, String word) {
48+
n = board.length;
49+
m = board[0].length;
50+
visited = List.filled(n, false).map((e) => List.filled(m, false)).toList();
51+
52+
for (int i = 0; i < n; i++) {
53+
for (int j = 0; j < m; j++) {
54+
if (board[i][j] == word[0]) {
55+
if (valid(i, j, 0, board, word)) {
56+
return true;
57+
}
58+
}
59+
}
60+
}
61+
return false;
62+
}
63+
64+
bool valid(int i, int j, int count, List<List<String>> board, String word) {
65+
/*-------------base conditions-------------*/
66+
//out of bound
67+
if (i < 0 || i >= n || j < 0 || j >= m) {
68+
return false;
69+
}
70+
71+
//if already visited
72+
if (visited[i][j]) {
73+
return false;
74+
}
75+
76+
//mismatch
77+
if (word[count] != board[i][j]) {
78+
return false;
79+
}
80+
81+
//if word is found
82+
if (count == word.length - 1) {
83+
return true;
84+
}
85+
86+
/*----------------calculation and recursive calls----------*/
87+
88+
//mark current visited
89+
visited[i][j] = true;
90+
91+
//inc count
92+
count++;
93+
94+
//down,right,up,left search
95+
if (valid(i + 1, j, count, board, word) ||
96+
valid(i, j + 1, count, board, word) ||
97+
valid(i - 1, j, count, board, word) ||
98+
valid(i, j - 1, count, board, word)) {
99+
return true;
100+
}
101+
102+
//mark current cell unvisited
103+
visited[i][j] = false;
104+
105+
return false;
106+
}
107+
}

WordSearch/word_search.go

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package main

WordSearch/word_search.md

Whitespace-only changes.

0 commit comments

Comments
 (0)