You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
intmyAtoi(String s) {
// Base conditionif (s.length <1) {
return0;
}
// MAX and MIN values for integersfinalint max =2147483647;
finalint min =-2147483648;
s = s.trim();
// Counterint i =0;
// Flag to indicate if the number is negativebool isNegative = s.startsWith("-");
// Flag to indicate if the number is positivebool isPositive = s.startsWith("+");
if (isNegative) {
i++;
} elseif (isPositive) {
i++;
}
// This will store the converted numberdouble number =0;
// Loop for each numeric character in the sing iff numeric characters are leading// characters in the singwhile (i < s.length &&
s[i].codeUnitAt(0) >='0'.codeUnitAt(0) &&
s[i].codeUnitAt(0) <='9'.codeUnitAt(0)) {
number = number *10+ (s[i].codeUnitAt(0) -'0'.codeUnitAt(0));
i++;
}
// Give back the sign to the converted number
number = isNegative ?-number : number;
if (number < min) {
return min;
}
if (number > max) {
return max;
}
return number.round();
}
intmaxArea(List<int> height) {
int max =0;
int left =0;
int right = height.length -1;
while (left < right) {
final res =min(height[left], height[right]) * (right - left);
if (res > max) max = res;
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return max;
}
Integer to Roman
StringintToRoman(intnum) {
// Define roman values and symbolsfinalList<int> values = [1000, 500, 100, 50, 10, 5, 1];
finalList<String> romanSymbols = ['M', 'D', 'C', 'L', 'X', 'V', 'I'];
List<String> result = [];
for (int index =0; index < values.length; index++) {
finalint romanValue = values[index];
finalint div = (num/ romanValue).floor();
if (div >0) {
num-= div * romanValue;
result.addAll(
List.generate(
div,
(i) => romanSymbols[index],
),
);
}
if (index < values.length -1) {
for (int j = index +1; j < values.length; j++) {
if (values[j].toString()[0] =='1') {
finalint nextValue = values[j];
finalint combine2Symbols = romanValue - nextValue;
if (num>= combine2Symbols &&num% combine2Symbols <= nextValue) {
num-= combine2Symbols;
result.add(romanSymbols[j]);
result.add(romanSymbols[index]);
}
}
}
}
}
return result.join();
}
Validate Stack Sequences
boolvalidateStackSequences(List<int> pushed, List<int> popped) {
List<int> current = [];
int indexPush =0;
int indexPop =0;
while (indexPush < pushed.length -1|| indexPop < popped.length -1) {
if (current.contains(popped[indexPop])) {
if (current.last == popped[indexPop]) {
current.removeLast();
indexPop++;
} else {
returnfalse;
}
} else {
current.add(pushed[indexPush]);
indexPush++;
}
}
returntrue;
}
Reverse Nodes in k-Group
ListNode?reverseKGroup(ListNode? head, int k) {
finalList<int> values =mergeValue(head, []);
finalList<List<int>> chunks = [];
for (int i =0; i < values.length; i += k) {
var end = (i + k < values.length) ? i + k : values.length;
chunks.add(values.sublist(i, end));
}
finalList<int> result = [];
chunks.forEach((e) {
if (e.length == k)
result.addAll(e.reversed);
else
result.addAll(e);
});
returnlinkedNodes(result);
}
List<int> mergeValue(ListNode? head, List<int> result) {
if (head ==null) return result;
returnmergeValue(head.next, [...result, head.val]);
}
ListNodelinkedNodes(List<int> values) {
List<ListNode> nodes = values.map((e) =>ListNode(e)).toList();
for (int i =0; i < nodes.length -1; i++) {
nodes[i].next = nodes[i +1];
}
return nodes.first;
}
Substring with Concatenation of All Words
List<int> findSubstring(String s, List<String> words) {
if (words.isEmpty || s.isEmpty || words.first.isEmpty) return [];
finalList<int> startIndexs = [];
finalint k = words.first.length;
finalint lengthOfMatchWords = words.length * k;
final listCloned = words.map((e) => e).toList();
listCloned.sort();
if (s.length < lengthOfMatchWords) return [];
for (final word in words.toSet().toList()) {
finalRegExp regExp =RegExp('(?=($word))');
finalIterable<Match> matches = regExp.allMatches(s);
if (matches.isEmpty) break;
for (final match in matches) {
if (match.start + lengthOfMatchWords <= s.length) {
finalString subString = s.substring(
match.start,
match.start + lengthOfMatchWords,
);
finalList<String> chunks = [];
for (int i =0; i < subString.length; i += k) {
var end = (i + k < subString.length) ? i + k : subString.length;
chunks.add(subString.substring(i, end));
}
chunks.sort();
// Check match with requimentsif (chunks.join() == listCloned.join() &&!startIndexs.contains(match.start)) {
startIndexs.add(match.start);
}
}
}
}
startIndexs.sort();
return startIndexs;
}
Longest Valid Parentheses
intlongestValidParentheses(String s) {
if (s.isEmpty) return0;
int longest =0;
finalList<int> stack = [-1];
for (int i =0; i < s.length; i++) {
// Openif (s[i] =='(') {
stack.add(i);
} else {
if (stack.isNotEmpty) stack.removeLast();
if (stack.isNotEmpty) {
longest =max(longest, i - stack.last);
} else {
stack.add(i);
}
}
}
return longest;
}
Merge k Sorted Lists
ListNode?mergeKLists(List<ListNode?> lists) {
List<int> merge = [];
for (final list in lists) {
merge.addAll(mergeValue(list, []));
}
merge.sort();
returnlinkedNodes(merge);
}
// UtilsList<int> mergeValue(ListNode? head, List<int> result) {
if (head ==null) return result;
returnmergeValue(head.next, [...result, head.val]);
}
ListNode?linkedNodes(List<int> values) {
if (values.isEmpty) returnnull;
List<ListNode> nodes = values.map((e) =>ListNode(e)).toList();
for (int i =0; i < nodes.length -1; i++) {
nodes[i].next = nodes[i +1];
}
return nodes.first;
}
Kids With the Greatest Number of Candies
List<bool> kidsWithCandies(List<int> candies, int extraCandies) {
finalList<int> clone = candies.map((e) => e).toList();
clone.sort((a, b) => b - a);
int greatest = clone.first;
finalList<bool> result = candies.map((e) {
return e + extraCandies >= greatest;
}).toList();
return result;
}
Sudoku Solver
voidsolveSudoku(List<List<String>> board) {
_solver(board);
}
bool_solver(List<List<String>> board) {
for (int i =0; i < board.length; i++) {
for (int j =0; j < board.length; j++) {
if (board[i][j] =='.') {
for (int k =1; k <=9; k++) {
if (_isValid(board, i, j, k)) {
board[i][j] ='$k';
if (_solver(board)) returntrue;
}
}
board[i][j] ='.';
returnfalse;
}
}
}
print(board);
returntrue;
}
bool_isValid(List<List<String>> board, int row, int col, int k) {
for (int i =0; i <9; i++) {
if (board[row][i] =='$k'|| board[i][col] =='$k') {
returnfalse;
}
}
final m = (col /3).floor() *3;
final n = (row /3).floor() *3;
for (int i =0; i <3; i++) {
for (int j =0; j <3; j++) {
if (board[n + i][m + j] =='$k') {
returnfalse;
}
}
}
returntrue;
}
First Missing Positive
intfirstMissingPositive(List<int> nums) {
nums = nums.where((e) => e >0).toSet().toList();
nums.sort();
if (nums.isEmpty || nums.first !=1) return1;
for (int index =1; index < nums.length; index++) {
if (nums[index] - nums[index -1] !=1) {
return nums[index -1] +1;
}
}
return nums.last +1;
}
Trapping rain water
inttrap(List<int> height) {
if (height.length <2) return0;
List<int> left =List.generate(height.length, (index) =>0);
List<int> right =List.generate(height.length, (index) =>0);
int result =0;
left.first = height.first;
for (int i =1; i < height.length; i++) {
left[i] =max(left[i -1], height[i]);
}
right.last = height.last;
for (int i = height.length -2; i >=0; i--) {
right[i] =max(right[i +1], height[i]);
}
for (int i =0; i < height.length; i++) {
result +=min(left[i], right[i]) - height[i];
}
return result;
}
Wildcard Matching
boolisMatch(String s, String p) {
if (p.replaceAll("*", "").length > s.length) returnfalse;
List<bool> flags =List.generate(s.length +1, (index) =>false);
flags.first =true;
for (int i =1; i < s.length; ++i) {
flags[i] =false;
}
for (int i =1; i <= p.length; ++i) {
String char = p[i -1];
if (char =='*') {
for (int j =1; j <= s.length; ++j) {
flags[j] = flags[j -1] || flags[j];
}
} else {
for (int j = s.length; j >=1; --j) {
flags[j] = flags[j -1] && (char =='?'|| char == s[j -1]);
}
}
flags[0] = flags[0] && char =='*';
}
return flags[s.length];
}
N Queens
List<List<String>> solveNQueens(int n) {
finalList<List<String>> result = [];
finalList<List<String>> board =List.generate(
n,
(index) =>List.generate(n, (index) =>"."),
);
place(0, 0, 0, 0, board, result);
return result;
}
voidplace(
int i,
int vert,
int ldiag,
int rdiag,
List<List<String>> board,
List<List<String>> result,
) {
if (i == board.length) {
List<String> res = [];
for (final row in board) res.add(row.join());
result.add(res);
return;
}
for (int j =0; j < board.length; j++) {
int verticalMask =1<< j,
leftMask =1<< (i + j),
rightMask =1<< (board.length - i -1+ j);
if ((vert & verticalMask) + (ldiag & leftMask) + (rdiag & rightMask) >0) continue;
board[i][j] ='Q';
place(i +1, vert | verticalMask, ldiag | leftMask, rdiag | rightMask, board, result);
board[i][j] ='.';
}
}
Valid number
boolisNumber(String s) {
if (s =="Infinity"|| s =="-Infinity"|| s =="+Infinity") returnfalse;
returnnum.tryParse(s) !=null;
}
Text Justification
List<String> fullJustify(List<String> words, int maxWidth) {
finalList<String> result = [];
String temp ='';
for (int index =0; index < words.length; index++) {
finalString word = words[index];
if (temp.length + word.length + (temp.isEmpty ?0:1) <= maxWidth) {
temp +='${temp.isEmpty ? '' : ' '}$word';
} else {
if (temp.trim().isNotEmpty) {
result.add(temp.trim());
}
temp = word;
}
if (index == words.length -1&& temp.isNotEmpty) {
result.add(temp.trim());
}
}
returnfillSpace(result, maxWidth);
}
List<String> fillSpace(List<String> words, int maxWidth) {
for (int i =0; i < words.length; i++) {
finalString word = words[i];
if (word.length < maxWidth) {
finalList<String> splits = word.split(' ');
if (splits.length <2|| i == words.length -1) {
words[i] =
word +List.generate(maxWidth - word.length, (index) =>' ').join();
} else {
int leftSpace = maxWidth - word.length + splits.length -1;
String temp ='';
for (int j =0; j < splits.length; j++) {
finaldouble div = leftSpace / (splits.length - j);
int avgSpace = div.round();
if (leftSpace / avgSpace >0) {
avgSpace = div.ceil();
}
if (j ==0) {
temp += splits[j];
} elseif (leftSpace >0) {
finalint cal = leftSpace < avgSpace ? leftSpace : avgSpace;
temp +='${List.generate(cal, (index) => ' ').join()}${splits[j]}';
leftSpace -= cal;
}
}
words[i] = temp;
}
}
}
return words;
}
3 Sum
List<List<int>> threeSum(List<int> nums) {
nums.sort();
finalList<List<int>> result = [];
for (int i =0; i < nums.length -2; i++) {
if (i >0&& nums[i] == nums[i -1]) continue;
int left = i +1;
int right = nums.length -1;
while (left < right) {
finalint sum = nums[i] + nums[left] + nums[right];
if (sum ==0) {
result.add([nums[i], nums[left], nums[right]]);
// remove duplicatewhile (left < nums.length -1&& nums[left] == nums[left +1]) left++;
while (right >0&& nums[right] == nums[right -1]) right--;
left++;
right--;
} elseif (sum <0) {
left++;
} else {
right--;
}
}
}
return result;
}
3 Sum Closest
intthreeSumClosest(List<int> nums, int target) {
int result =-1;
int diff =-1;
for (int i =0; i < nums.length -2; i++) {
int left = i +1;
int right = nums.length -1;
while (left < right) {
finalint sum = nums[i] + nums[left] + nums[right];
if (diff <0|| (sum - target).abs() < diff) {
diff = (sum - target).abs();
result = sum;
}
if (diff ==0) {
return result;
}
if (right == left +1) {
left++;
right = nums.length -1;
} else {
right--;
}
}
}
return result;
}
intjump(List<int> nums) {
if (nums.isEmpty) return0;
int result =0;
int maxNumber =0;
int cur =0;
for (var i =0; i < nums.length -1; i++) {
maxNumber =max(maxNumber, i + nums[i]);
if (i == cur) {
result++;
cur = maxNumber;
}
}
return result;
}