id
int64
1
3.63k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
Go
func isValid(s string) bool { stk := []rune{} for _, c := range s { if c == '(' || c == '{' || c == '[' { stk = append(stk, c) } else if len(stk) == 0 || !match(stk[len(stk)-1], c) { return false } else { stk = stk[:len(stk)-1] } } return len(stk) == 0 } func match(l, r rune) bool { return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}') }
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
Java
class Solution { public boolean isValid(String s) { Deque<Character> stk = new ArrayDeque<>(); for (char c : s.toCharArray()) { if (c == '(' || c == '{' || c == '[') { stk.push(c); } else if (stk.isEmpty() || !match(stk.pop(), c)) { return false; } } return stk.isEmpty(); } private boolean match(char l, char r) { return (l == '(' && r == ')') || (l == '{' && r == '}') || (l == '[' && r == ']'); } }
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
JavaScript
/** * @param {string} s * @return {boolean} */ var isValid = function (s) { let stk = []; for (const c of s) { if (c == '(' || c == '{' || c == '[') { stk.push(c); } else if (stk.length == 0 || !match(stk[stk.length - 1], c)) { return false; } else { stk.pop(); } } return stk.length == 0; }; function match(l, r) { return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); }
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
PHP
class Solution { /** * @param string $s * @return boolean */ function isValid($s) { $stack = []; $brackets = [ ')' => '(', '}' => '{', ']' => '[', ]; for ($i = 0; $i < strlen($s); $i++) { $char = $s[$i]; if (array_key_exists($char, $brackets)) { if (empty($stack) || $stack[count($stack) - 1] !== $brackets[$char]) { return false; } array_pop($stack); } else { array_push($stack, $char); } } return empty($stack); } }
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
Python
class Solution: def isValid(self, s: str) -> bool: stk = [] d = {'()', '[]', '{}'} for c in s: if c in '({[': stk.append(c) elif not stk or stk.pop() + c not in d: return False return not stk
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
Ruby
# @param {String} s # @return {Boolean} def is_valid(s) stack = '' s.split('').each do |c| if ['{', '[', '('].include?(c) stack += c else if c == '}' && stack[stack.length - 1] == '{' stack = stack.length > 1 ? stack[0..stack.length - 2] : "" elsif c == ']' && stack[stack.length - 1] == '[' stack = stack.length > 1 ? stack[0..stack.length - 2] : "" elsif c == ')' && stack[stack.length - 1] == '(' stack = stack.length > 1 ? stack[0..stack.length - 2] : "" else return false end end end stack == '' end
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
Rust
use std::collections::HashMap; impl Solution { pub fn is_valid(s: String) -> bool { let mut map = HashMap::new(); map.insert('(', ')'); map.insert('[', ']'); map.insert('{', '}'); let mut stack = vec![]; for c in s.chars() { if map.contains_key(&c) { stack.push(map[&c]); } else if stack.pop().unwrap_or(' ') != c { return false; } } stack.len() == 0 } }
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
TypeScript
const map = new Map([ ['(', ')'], ['[', ']'], ['{', '}'], ]); function isValid(s: string): boolean { const stack = []; for (const c of s) { if (map.has(c)) { stack.push(map.get(c)); } else if (stack.pop() !== c) { return false; } } return stack.length === 0; }
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { if (!list1) return list2; if (!list2) return list1; if (list1->val <= list2->val) { list1->next = mergeTwoLists(list1->next, list2); return list1; } else { list2->next = mergeTwoLists(list1, list2->next); return list2; } } };
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode MergeTwoLists(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } if (list1.val <= list2.val) { list1.next = MergeTwoLists(list1.next, list2); return list1; } else { list2.next = MergeTwoLists(list1, list2.next); return list2; } } }
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { if list1 == nil { return list2 } if list2 == nil { return list1 } if list1.Val <= list2.Val { list1.Next = mergeTwoLists(list1.Next, list2) return list1 } else { list2.Next = mergeTwoLists(list1, list2.Next) return list2 } }
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } if (list1.val <= list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; } } }
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} list1 * @param {ListNode} list2 * @return {ListNode} */ var mergeTwoLists = function (list1, list2) { if (!list1 || !list2) { return list1 || list2; } if (list1.val <= list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; } };
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
PHP
/** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val = 0, $next = null) { * $this->val = $val; * $this->next = $next; * } * } */ class Solution { /** * @param ListNode $list1 * @param ListNode $list2 * @return ListNode */ function mergeTwoLists($list1, $list2) { if (is_null($list1)) { return $list2; } if (is_null($list2)) { return $list1; } if ($list1->val <= $list2->val) { $list1->next = $this->mergeTwoLists($list1->next, $list2); return $list1; } else { $list2->next = $this->mergeTwoLists($list1, $list2->next); return $list2; } } }
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists( self, list1: Optional[ListNode], list2: Optional[ListNode] ) -> Optional[ListNode]: if list1 is None or list2 is None: return list1 or list2 if list1.val <= list2.val: list1.next = self.mergeTwoLists(list1.next, list2) return list1 else: list2.next = self.mergeTwoLists(list1, list2.next) return list2
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
Ruby
# Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val = 0, _next = nil) # @val = val # @next = _next # end # end # @param {ListNode} list1 # @param {ListNode} list2 # @return {ListNode} def merge_two_lists(list1, list2) if list1.nil? return list2 end if list2.nil? return list1 end if list1.val <= list2.val list1.next = merge_two_lists(list1.next, list2) return list1 else list2.next = merge_two_lists(list1, list2.next) return list2 end end
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn merge_two_lists( list1: Option<Box<ListNode>>, list2: Option<Box<ListNode>>, ) -> Option<Box<ListNode>> { match (list1, list2) { (None, None) => None, (Some(list), None) => Some(list), (None, Some(list)) => Some(list), (Some(mut list1), Some(mut list2)) => { if list1.val < list2.val { list1.next = Self::merge_two_lists(list1.next, Some(list2)); Some(list1) } else { list2.next = Self::merge_two_lists(Some(list1), list2.next); Some(list2) } } } } }
21
Merge Two Sorted Lists
Easy
<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p> <p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p> <p>Return <em>the head of the merged linked list</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/images/merge_ex1.jpg" style="width: 662px; height: 302px;" /> <pre> <strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4] <strong>Output:</strong> [1,1,2,3,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> list1 = [], list2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> <li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li> </ul>
Recursion; Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { if (list1 == null || list2 == null) { return list1 || list2; } if (list1.val < list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; } }
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
C++
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> ans; function<void(int, int, string)> dfs = [&](int l, int r, string t) { if (l > n || r > n || l < r) return; if (l == n && r == n) { ans.push_back(t); return; } dfs(l + 1, r, t + "("); dfs(l, r + 1, t + ")"); }; dfs(0, 0, ""); return ans; } };
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
C#
public class Solution { private List<string> ans = new List<string>(); private int n; public List<string> GenerateParenthesis(int n) { this.n = n; Dfs(0, 0, ""); return ans; } private void Dfs(int l, int r, string t) { if (l > n || r > n || l < r) { return; } if (l == n && r == n) { ans.Add(t); return; } Dfs(l + 1, r, t + "("); Dfs(l, r + 1, t + ")"); } }
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
Go
func generateParenthesis(n int) (ans []string) { var dfs func(int, int, string) dfs = func(l, r int, t string) { if l > n || r > n || l < r { return } if l == n && r == n { ans = append(ans, t) return } dfs(l+1, r, t+"(") dfs(l, r+1, t+")") } dfs(0, 0, "") return ans }
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
Java
class Solution { private List<String> ans = new ArrayList<>(); private int n; public List<String> generateParenthesis(int n) { this.n = n; dfs(0, 0, ""); return ans; } private void dfs(int l, int r, String t) { if (l > n || r > n || l < r) { return; } if (l == n && r == n) { ans.add(t); return; } dfs(l + 1, r, t + "("); dfs(l, r + 1, t + ")"); } }
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
JavaScript
/** * @param {number} n * @return {string[]} */ var generateParenthesis = function (n) { function dfs(l, r, t) { if (l > n || r > n || l < r) { return; } if (l == n && r == n) { ans.push(t); return; } dfs(l + 1, r, t + '('); dfs(l, r + 1, t + ')'); } let ans = []; dfs(0, 0, ''); return ans; };
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
PHP
class Solution { /** * @param Integer $n * @return String[] */ function generateParenthesis($n) { $ans = []; $dfs = function($l, $r, $t) use ($n, &$ans, &$dfs) { if ($l > $n || $r > $n || $l < $r) return; if ($l == $n && $r == $n) { $ans[] = $t; return; } $dfs($l + 1, $r, $t . "("); $dfs($l, $r + 1, $t . ")"); }; $dfs(0, 0, ""); return $ans; } }
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
Python
class Solution: def generateParenthesis(self, n: int) -> List[str]: def dfs(l, r, t): if l > n or r > n or l < r: return if l == n and r == n: ans.append(t) return dfs(l + 1, r, t + '(') dfs(l, r + 1, t + ')') ans = [] dfs(0, 0, '') return ans
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
Rust
impl Solution { pub fn generate_parenthesis(n: i32) -> Vec<String> { let mut ans = Vec::new(); fn dfs(ans: &mut Vec<String>, l: i32, r: i32, t: String, n: i32) { if l > n || r > n || l < r { return; } if l == n && r == n { ans.push(t); return; } dfs(ans, l + 1, r, format!("{}(", t), n); dfs(ans, l, r + 1, format!("{})", t), n); } dfs(&mut ans, 0, 0, String::new(), n); ans } }
22
Generate Parentheses
Medium
<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 3 <strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> ["()"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 8</code></li> </ul>
String; Dynamic Programming; Backtracking
TypeScript
function generateParenthesis(n: number): string[] { function dfs(l, r, t) { if (l > n || r > n || l < r) { return; } if (l == n && r == n) { ans.push(t); return; } dfs(l + 1, r, t + '('); dfs(l, r + 1, t + ')'); } let ans = []; dfs(0, 0, ''); return ans; }
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; }; priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq; for (auto head : lists) { if (head) { pq.push(head); } } ListNode* dummy = new ListNode(); ListNode* cur = dummy; while (!pq.empty()) { ListNode* node = pq.top(); pq.pop(); if (node->next) { pq.push(node->next); } cur->next = node; cur = cur->next; } return dummy->next; } };
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode MergeKLists(ListNode[] lists) { PriorityQueue<ListNode, int> pq = new PriorityQueue<ListNode, int>(); foreach (var head in lists) { if (head != null) { pq.Enqueue(head, head.val); } } var dummy = new ListNode(); var cur = dummy; while (pq.Count > 0) { var node = pq.Dequeue(); cur.next = node; cur = cur.next; if (node.next != null) { pq.Enqueue(node.next, node.next.val); } } return dummy.next; } }
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func mergeKLists(lists []*ListNode) *ListNode { pq := hp{} for _, head := range lists { if head != nil { pq = append(pq, head) } } heap.Init(&pq) dummy := &ListNode{} cur := dummy for len(pq) > 0 { cur.Next = heap.Pop(&pq).(*ListNode) cur = cur.Next if cur.Next != nil { heap.Push(&pq, cur.Next) } } return dummy.Next } type hp []*ListNode func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].Val < h[j].Val } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(*ListNode)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val); for (ListNode head : lists) { if (head != null) { pq.offer(head); } } ListNode dummy = new ListNode(); ListNode cur = dummy; while (!pq.isEmpty()) { ListNode node = pq.poll(); if (node.next != null) { pq.offer(node.next); } cur.next = node; cur = cur.next; } return dummy.next; } }
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode[]} lists * @return {ListNode} */ var mergeKLists = function (lists) { const pq = new MinPriorityQueue({ priority: node => node.val }); lists.filter(head => head).forEach(head => pq.enqueue(head)); const dummy = new ListNode(); let cur = dummy; while (!pq.isEmpty()) { const node = pq.dequeue().element; cur.next = node; cur = cur.next; if (node.next) { pq.enqueue(node.next); } } return dummy.next; };
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
PHP
# Definition for singly-linked list. class ListNode { public $val; public $next; public function __construct($val = 0, $next = null) { $this->val = $val; $this->next = $next; } } class Solution { /** * @param ListNode[] $lists * @return ListNode */ function mergeKLists($lists) { $numLists = count($lists); if ($numLists === 0) { return null; } while ($numLists > 1) { $mid = intval($numLists / 2); for ($i = 0; $i < $mid; $i++) { $lists[$i] = $this->mergeTwoLists($lists[$i], $lists[$numLists - $i - 1]); } $numLists = intval(($numLists + 1) / 2); } return $lists[0]; } function mergeTwoLists($list1, $list2) { $dummy = new ListNode(0); $current = $dummy; while ($list1 != null && $list2 != null) { if ($list1->val <= $list2->val) { $current->next = $list1; $list1 = $list1->next; } else { $current->next = $list2; $list2 = $list2->next; } $current = $current->next; } if ($list1 != null) { $current->next = $list1; } elseif ($list2 != null) { $current->next = $list2; } return $dummy->next; } }
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: setattr(ListNode, "__lt__", lambda a, b: a.val < b.val) pq = [head for head in lists if head] heapify(pq) dummy = cur = ListNode() while pq: node = heappop(pq) if node.next: heappush(pq, node.next) cur.next = node cur = cur.next return dummy.next
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } use std::cmp::Ordering; use std::collections::BinaryHeap; impl PartialOrd for ListNode { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for ListNode { fn cmp(&self, other: &Self) -> Ordering { self.val.cmp(&other.val).reverse() } } impl Solution { pub fn merge_k_lists(lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> { let mut pq = lists .into_iter() .filter_map(|head| head) .collect::<BinaryHeap<_>>(); let mut head = None; let mut cur = &mut head; while let Some(node) = pq.pop() { cur = &mut cur.insert(Box::new(ListNode::new(node.val))).next; if let Some(next) = node.next { pq.push(next); } } head } }
23
Merge k Sorted Lists
Hard
<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p> <p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]] <strong>Output:</strong> [1,1,2,3,4,4,5,6] <strong>Explanation:</strong> The linked-lists are: [ 1-&gt;4-&gt;5, 1-&gt;3-&gt;4, 2-&gt;6 ] merging them into one sorted linked list: 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lists = [] <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lists = [[]] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>k == lists.length</code></li> <li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= lists[i].length &lt;= 500</code></li> <li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li> <li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li> </ul>
Linked List; Divide and Conquer; Heap (Priority Queue); Merge Sort
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function mergeKLists(lists: Array<ListNode | null>): ListNode | null { const pq = new MinPriorityQueue({ priority: (node: ListNode) => node.val }); lists.filter(head => head).forEach(head => pq.enqueue(head)); const dummy: ListNode = new ListNode(); let cur: ListNode = dummy; while (!pq.isEmpty()) { const node = pq.dequeue().element; cur.next = node; cur = cur.next; if (node.next) { pq.enqueue(node.next); } } return dummy.next; }
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { if (!head || !head->next) { return head; } ListNode* t = swapPairs(head->next->next); ListNode* p = head->next; p->next = head; head->next = t; return p; } };
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode SwapPairs(ListNode head) { if (head is null || head.next is null) { return head; } ListNode t = SwapPairs(head.next.next); ListNode p = head.next; p.next = head; head.next = t; return p; } }
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func swapPairs(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } t := swapPairs(head.Next.Next) p := head.Next p.Next = head head.Next = t return p }
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode t = swapPairs(head.next.next); ListNode p = head.next; p.next = head; head.next = t; return p; } }
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var swapPairs = function (head) { if (!head || !head.next) { return head; } const t = swapPairs(head.next.next); const p = head.next; p.next = head; head.next = t; return p; };
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
PHP
# Definition for singly-linked list. # class ListNode { # public $val; # public $next; # public function __construct($val = 0, $next = null) # { # $this->val = $val; # $this->next = $next; # } # } class Solution { /** * @param ListNode $head * @return ListNode */ function swapPairs($head) { $dummy = new ListNode(0); $dummy->next = $head; $prev = $dummy; while ($head !== null && $head->next !== null) { $first = $head; $second = $head->next; $first->next = $second->next; $second->next = $first; $prev->next = $second; $prev = $first; $head = $first->next; } return $dummy->next; } }
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None or head.next is None: return head t = self.swapPairs(head.next.next) p = head.next p.next = head head.next = t return p
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
Ruby
# Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val = 0, _next = nil) # @val = val # @next = _next # end # end # @param {ListNode} head # @return {ListNode} def swap_pairs(head) dummy = ListNode.new(0, head) pre = dummy cur = head while !cur.nil? && !cur.next.nil? t = cur.next cur.next = t.next t.next = cur pre.next = t pre = cur cur = cur.next end dummy.next end
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); let mut cur = dummy.as_mut().unwrap(); while cur.next.is_some() && cur.next.as_ref().unwrap().next.is_some() { cur.next = { let mut b = cur.next.as_mut().unwrap().next.take(); cur.next.as_mut().unwrap().next = b.as_mut().unwrap().next.take(); let a = cur.next.take(); b.as_mut().unwrap().next = a; b }; cur = cur.next.as_mut().unwrap().next.as_mut().unwrap(); } dummy.unwrap().next } }
24
Swap Nodes in Pairs
Medium
<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,4,3]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg" style="width: 422px; height: 222px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = []</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,3]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> </ul>
Recursion; Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function swapPairs(head: ListNode | null): ListNode | null { if (!head || !head.next) { return head; } const t = swapPairs(head.next.next); const p = head.next; p.next = head; head.next = t; return p; }
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* dummy = new ListNode(0, head); ListNode* pre = dummy; while (pre != nullptr) { ListNode* cur = pre; for (int i = 0; i < k; i++) { cur = cur->next; if (cur == nullptr) { return dummy->next; } } ListNode* node = pre->next; ListNode* nxt = cur->next; cur->next = nullptr; pre->next = reverse(node); node->next = nxt; pre = node; } return dummy->next; } private: ListNode* reverse(ListNode* head) { ListNode* dummy = new ListNode(); ListNode* cur = head; while (cur != nullptr) { ListNode* nxt = cur->next; cur->next = dummy->next; dummy->next = cur; cur = nxt; } return dummy->next; } };
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val = 0, ListNode next = null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode ReverseKGroup(ListNode head, int k) { var dummy = new ListNode(0); dummy.next = head; var pre = dummy; while (pre != null) { var cur = pre; for (int i = 0; i < k; i++) { if (cur.next == null) { return dummy.next; } cur = cur.next; } var node = pre.next; var nxt = cur.next; cur.next = null; pre.next = Reverse(node); node.next = nxt; pre = node; } return dummy.next; } private ListNode Reverse(ListNode head) { ListNode prev = null; var cur = head; while (cur != null) { var nxt = cur.next; cur.next = prev; prev = cur; cur = nxt; } return prev; } }
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseKGroup(head *ListNode, k int) *ListNode { dummy := &ListNode{Next: head} pre := dummy for pre != nil { cur := pre for i := 0; i < k; i++ { cur = cur.Next if cur == nil { return dummy.Next } } node := pre.Next nxt := cur.Next cur.Next = nil pre.Next = reverse(node) node.Next = nxt pre = node } return dummy.Next } func reverse(head *ListNode) *ListNode { var dummy *ListNode cur := head for cur != nil { nxt := cur.Next cur.Next = dummy dummy = cur cur = nxt } return dummy }
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(0, head); dummy.next = head; ListNode pre = dummy; while (pre != null) { ListNode cur = pre; for (int i = 0; i < k; i++) { cur = cur.next; if (cur == null) { return dummy.next; } } ListNode node = pre.next; ListNode nxt = cur.next; cur.next = null; pre.next = reverse(node); node.next = nxt; pre = node; } return dummy.next; } private ListNode reverse(ListNode head) { ListNode dummy = new ListNode(); ListNode cur = head; while (cur != null) { ListNode nxt = cur.next; cur.next = dummy.next; dummy.next = cur; cur = nxt; } return dummy.next; } }
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
PHP
/** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val = 0, $next = null) { * $this->val = $val; * $this->next = $next; * } * } */ class Solution { /** * @param ListNode $head * @param Integer $k * @return ListNode */ function reverseKGroup($head, $k) { $dummy = new ListNode(0); $dummy->next = $head; $pre = $dummy; while ($pre !== null) { $cur = $pre; for ($i = 0; $i < $k; $i++) { if ($cur->next === null) { return $dummy->next; } $cur = $cur->next; } $node = $pre->next; $nxt = $cur->next; $cur->next = null; $pre->next = $this->reverse($node); $node->next = $nxt; $pre = $node; } return $dummy->next; } /** * Helper function to reverse a linked list. * @param ListNode $head * @return ListNode */ function reverse($head) { $prev = null; $cur = $head; while ($cur !== null) { $nxt = $cur->next; $cur->next = $prev; $prev = $cur; $cur = $nxt; } return $prev; } }
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: def reverse(head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode() cur = head while cur: nxt = cur.next cur.next = dummy.next dummy.next = cur cur = nxt return dummy.next dummy = pre = ListNode(next=head) while pre: cur = pre for _ in range(k): cur = cur.next if cur is None: return dummy.next node = pre.next nxt = cur.next cur.next = None pre.next = reverse(node) node.next = nxt pre = node return dummy.next
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn reverse_k_group(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> { fn reverse(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut head = head; let mut pre = None; while let Some(mut node) = head { head = node.next.take(); node.next = pre.take(); pre = Some(node); } pre } let mut dummy = Some(Box::new(ListNode::new(0))); let mut pre = &mut dummy; let mut cur = head; while cur.is_some() { let mut q = &mut cur; for _ in 0..k - 1 { if q.is_none() { break; } q = &mut q.as_mut().unwrap().next; } if q.is_none() { pre.as_mut().unwrap().next = cur; return dummy.unwrap().next; } let b = q.as_mut().unwrap().next.take(); pre.as_mut().unwrap().next = reverse(cur); while pre.is_some() && pre.as_mut().unwrap().next.is_some() { pre = &mut pre.as_mut().unwrap().next; } cur = b; } dummy.unwrap().next } }
25
Reverse Nodes in k-Group
Hard
<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p> <p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 2 <strong>Output:</strong> [2,1,4,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/images/reverse_ex2.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], k = 3 <strong>Output:</strong> [3,2,1,4,5] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= Node.val &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
Recursion; Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function reverseKGroup(head: ListNode | null, k: number): ListNode | null { const dummy = new ListNode(0, head); let pre = dummy; while (pre !== null) { let cur: ListNode | null = pre; for (let i = 0; i < k; i++) { cur = cur?.next || null; if (cur === null) { return dummy.next; } } const node = pre.next; const nxt = cur?.next || null; cur!.next = null; pre.next = reverse(node); node!.next = nxt; pre = node!; } return dummy.next; } function reverse(head: ListNode | null): ListNode | null { let dummy: ListNode | null = null; let cur = head; while (cur !== null) { const nxt = cur.next; cur.next = dummy; dummy = cur; cur = nxt; } return dummy; }
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
C++
class Solution { public: int removeDuplicates(vector<int>& nums) { int k = 0; for (int x : nums) { if (k == 0 || x != nums[k - 1]) { nums[k++] = x; } } return k; } };
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
C#
public class Solution { public int RemoveDuplicates(int[] nums) { int k = 0; foreach (int x in nums) { if (k == 0 || x != nums[k - 1]) { nums[k++] = x; } } return k; } }
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
Go
func removeDuplicates(nums []int) int { k := 0 for _, x := range nums { if k == 0 || x != nums[k-1] { nums[k] = x k++ } } return k }
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
Java
class Solution { public int removeDuplicates(int[] nums) { int k = 0; for (int x : nums) { if (k == 0 || x != nums[k - 1]) { nums[k++] = x; } } return k; } }
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
JavaScript
/** * @param {number[]} nums * @return {number} */ var removeDuplicates = function (nums) { let k = 0; for (const x of nums) { if (k === 0 || x !== nums[k - 1]) { nums[k++] = x; } } return k; };
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
PHP
class Solution { /** * @param Integer[] $nums * @return Integer */ function removeDuplicates(&$nums) { $k = 0; foreach ($nums as $x) { if ($k == 0 || $x != $nums[$k - 1]) { $nums[$k++] = $x; } } return $k; } }
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
Python
class Solution: def removeDuplicates(self, nums: List[int]) -> int: k = 0 for x in nums: if k == 0 or x != nums[k - 1]: nums[k] = x k += 1 return k
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
Rust
impl Solution { pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 { let mut k = 0; for i in 0..nums.len() { if k == 0 || nums[i] != nums[k - 1] { nums[k] = nums[i]; k += 1; } } k as i32 } }
26
Remove Duplicates from Sorted Array
Easy
<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p> <p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i &lt; k; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> 2, nums = [1,2,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4] <strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Array; Two Pointers
TypeScript
function removeDuplicates(nums: number[]): number { let k: number = 0; for (const x of nums) { if (k === 0 || x !== nums[k - 1]) { nums[k++] = x; } } return k; }
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
C++
class Solution { public: int removeElement(vector<int>& nums, int val) { int k = 0; for (int x : nums) { if (x != val) { nums[k++] = x; } } return k; } };
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
C#
public class Solution { public int RemoveElement(int[] nums, int val) { int k = 0; foreach (int x in nums) { if (x != val) { nums[k++] = x; } } return k; } }
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
Go
func removeElement(nums []int, val int) int { k := 0 for _, x := range nums { if x != val { nums[k] = x k++ } } return k }
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
Java
class Solution { public int removeElement(int[] nums, int val) { int k = 0; for (int x : nums) { if (x != val) { nums[k++] = x; } } return k; } }
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
JavaScript
/** * @param {number[]} nums * @param {number} val * @return {number} */ var removeElement = function (nums, val) { let k = 0; for (const x of nums) { if (x !== val) { nums[k++] = x; } } return k; };
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
PHP
class Solution { /** * @param Integer[] $nums * @param Integer $val * @return Integer */ function removeElement(&$nums, $val) { for ($i = count($nums) - 1; $i >= 0; $i--) { if ($nums[$i] == $val) { array_splice($nums, $i, 1); } } } }
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
Python
class Solution: def removeElement(self, nums: List[int], val: int) -> int: k = 0 for x in nums: if x != val: nums[k] = x k += 1 return k
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
Rust
impl Solution { pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 { let mut k = 0; for i in 0..nums.len() { if nums[i] != val { nums[k] = nums[i]; k += 1; } } k as i32 } }
27
Remove Element
Easy
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p> <p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p> <ul> <li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li> <li>Return <code>k</code>.</li> </ul> <p><strong>Custom Judge:</strong></p> <p>The judge will test your solution with the following code:</p> <pre> int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i &lt; actualLength; i++) { assert nums[i] == expectedNums[i]; } </pre> <p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,2,3], val = 3 <strong>Output:</strong> 2, nums = [2,2,_,_] <strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2 <strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_] <strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= val &lt;= 100</code></li> </ul>
Array; Two Pointers
TypeScript
function removeElement(nums: number[], val: number): number { let k: number = 0; for (const x of nums) { if (x !== val) { nums[k++] = x; } } return k; }
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
C++
class Solution { private: vector<int> Next(string str) { vector<int> n(str.length()); n[0] = -1; int i = 0, pre = -1; int len = str.length(); while (i < len) { while (pre >= 0 && str[i] != str[pre]) pre = n[pre]; ++i, ++pre; if (i >= len) break; if (str[i] == str[pre]) n[i] = n[pre]; else n[i] = pre; } return n; } public: int strStr(string haystack, string needle) { if (0 == needle.length()) return 0; vector<int> n(Next(needle)); int len = haystack.length() - needle.length() + 1; for (int i = 0; i < len; ++i) { int j = 0, k = i; while (j < needle.length() && k < haystack.length()) { if (haystack[k] != needle[j]) { if (n[j] >= 0) { j = n[j]; continue; } else break; } ++k, ++j; } if (j >= needle.length()) return k - j; } return -1; } };
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
C#
public class Solution { public int StrStr(string haystack, string needle) { for (var i = 0; i < haystack.Length - needle.Length + 1; ++i) { var j = 0; for (; j < needle.Length; ++j) { if (haystack[i + j] != needle[j]) break; } if (j == needle.Length) return i; } return -1; } }
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
Go
func strStr(haystack string, needle string) int { n, m := len(haystack), len(needle) for i := 0; i <= n-m; i++ { if haystack[i:i+m] == needle { return i } } return -1 }
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
Java
class Solution { public int strStr(String haystack, String needle) { if ("".equals(needle)) { return 0; } int len1 = haystack.length(); int len2 = needle.length(); int p = 0; int q = 0; while (p < len1) { if (haystack.charAt(p) == needle.charAt(q)) { if (len2 == 1) { return p; } ++p; ++q; } else { p -= q - 1; q = 0; } if (q == len2) { return p - q; } } return -1; } }
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
JavaScript
/** * @param {string} haystack * @param {string} needle * @return {number} */ var strStr = function (haystack, needle) { const slen = haystack.length; const plen = needle.length; if (slen == plen) { return haystack == needle ? 0 : -1; } for (let i = 0; i <= slen - plen; i++) { let j; for (j = 0; j < plen; j++) { if (haystack[i + j] != needle[j]) { break; } } if (j == plen) return i; } return -1; };
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
PHP
class Solution { /** * @param String $haystack * @param String $needle * @return Integer */ function strStr($haystack, $needle) { $strNew = str_replace($needle, '+', $haystack); $cnt = substr_count($strNew, '+'); if ($cnt > 0) { for ($i = 0; $i < strlen($strNew); $i++) { if ($strNew[$i] == '+') { return $i; } } } else { return -1; } } }
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
Python
class Solution: def strStr(self, haystack: str, needle: str) -> int: n, m = len(haystack), len(needle) for i in range(n - m + 1): if haystack[i : i + m] == needle: return i return -1
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
Rust
impl Solution { pub fn str_str(haystack: String, needle: String) -> i32 { let haystack = haystack.as_bytes(); let needle = needle.as_bytes(); let m = haystack.len(); let n = needle.len(); let mut next = vec![0; n]; let mut j = 0; for i in 1..n { while j > 0 && needle[i] != needle[j] { j = next[j - 1]; } if needle[i] == needle[j] { j += 1; } next[i] = j; } j = 0; for i in 0..m { while j > 0 && haystack[i] != needle[j] { j = next[j - 1]; } if haystack[i] == needle[j] { j += 1; } if j == n { return (i - n + 1) as i32; } } -1 } }
28
Find the Index of the First Occurrence in a String
Easy
<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li> <li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li> </ul>
Two Pointers; String; String Matching
TypeScript
function strStr(haystack: string, needle: string): number { const m = haystack.length; const n = needle.length; for (let i = 0; i <= m - n; i++) { let isEqual = true; for (let j = 0; j < n; j++) { if (haystack[i + j] !== needle[j]) { isEqual = false; break; } } if (isEqual) { return i; } } return -1; }
29
Divide Two Integers
Medium
<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p> <p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p> <p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p> <p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dividend = 10, divisor = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dividend = 7, divisor = -3 <strong>Output:</strong> -2 <strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li> <li><code>divisor != 0</code></li> </ul>
Bit Manipulation; Math
C++
class Solution { public: int divide(int a, int b) { if (b == 1) { return a; } if (a == INT_MIN && b == -1) { return INT_MAX; } bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; int ans = 0; while (a <= b) { int x = b; int cnt = 1; while (x >= (INT_MIN >> 1) && a <= (x << 1)) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; } };
29
Divide Two Integers
Medium
<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p> <p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p> <p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p> <p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dividend = 10, divisor = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dividend = 7, divisor = -3 <strong>Output:</strong> -2 <strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li> <li><code>divisor != 0</code></li> </ul>
Bit Manipulation; Math
C#
public class Solution { public int Divide(int a, int b) { if (b == 1) { return a; } if (a == int.MinValue && b == -1) { return int.MaxValue; } bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; int ans = 0; while (a <= b) { int x = b; int cnt = 1; while (x >= (int.MinValue >> 1) && a <= (x << 1)) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; } }
29
Divide Two Integers
Medium
<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p> <p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p> <p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p> <p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dividend = 10, divisor = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dividend = 7, divisor = -3 <strong>Output:</strong> -2 <strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li> <li><code>divisor != 0</code></li> </ul>
Bit Manipulation; Math
Go
func divide(a int, b int) int { if b == 1 { return a } if a == math.MinInt32 && b == -1 { return math.MaxInt32 } sign := (a > 0 && b > 0) || (a < 0 && b < 0) if a > 0 { a = -a } if b > 0 { b = -b } ans := 0 for a <= b { x := b cnt := 1 for x >= (math.MinInt32>>1) && a <= (x<<1) { x <<= 1 cnt <<= 1 } ans += cnt a -= x } if sign { return ans } return -ans }
29
Divide Two Integers
Medium
<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p> <p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p> <p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p> <p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dividend = 10, divisor = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dividend = 7, divisor = -3 <strong>Output:</strong> -2 <strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li> <li><code>divisor != 0</code></li> </ul>
Bit Manipulation; Math
Java
class Solution { public int divide(int a, int b) { if (b == 1) { return a; } if (a == Integer.MIN_VALUE && b == -1) { return Integer.MAX_VALUE; } boolean sign = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; int ans = 0; while (a <= b) { int x = b; int cnt = 1; while (x >= (Integer.MIN_VALUE >> 1) && a <= (x << 1)) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; } }
29
Divide Two Integers
Medium
<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p> <p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p> <p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p> <p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dividend = 10, divisor = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dividend = 7, divisor = -3 <strong>Output:</strong> -2 <strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li> <li><code>divisor != 0</code></li> </ul>
Bit Manipulation; Math
PHP
class Solution { /** * @param integer $a * @param integer $b * @return integer */ function divide($a, $b) { if ($b == 0) { throw new Exception('Can not divide by 0'); } elseif ($a == 0) { return 0; } if ($a == -2147483648 && $b == -1) { return 2147483647; } $sign = $a < 0 != $b < 0; $a = abs($a); $b = abs($b); $ans = 0; while ($a >= $b) { $x = $b; $cnt = 1; while ($a >= $x << 1) { $x <<= 1; $cnt <<= 1; } $a -= $x; $ans += $cnt; } return $sign ? -$ans : $ans; } }
29
Divide Two Integers
Medium
<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p> <p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p> <p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p> <p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dividend = 10, divisor = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dividend = 7, divisor = -3 <strong>Output:</strong> -2 <strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li> <li><code>divisor != 0</code></li> </ul>
Bit Manipulation; Math
Python
class Solution: def divide(self, a: int, b: int) -> int: if b == 1: return a if a == -(2**31) and b == -1: return 2**31 - 1 sign = (a > 0 and b > 0) or (a < 0 and b < 0) a = -a if a > 0 else a b = -b if b > 0 else b ans = 0 while a <= b: x = b cnt = 1 while x >= (-(2**30)) and a <= (x << 1): x <<= 1 cnt <<= 1 a -= x ans += cnt return ans if sign else -ans
29
Divide Two Integers
Medium
<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p> <p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p> <p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p> <p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dividend = 10, divisor = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dividend = 7, divisor = -3 <strong>Output:</strong> -2 <strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li> <li><code>divisor != 0</code></li> </ul>
Bit Manipulation; Math
TypeScript
function divide(a: number, b: number): number { if (b === 1) { return a; } if (a === -(2 ** 31) && b === -1) { return 2 ** 31 - 1; } const sign: boolean = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; let ans: number = 0; while (a <= b) { let x: number = b; let cnt: number = 1; while (x >= -(2 ** 30) && a <= x << 1) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; }
30
Substring with Concatenation of All Words
Hard
<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p> <p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p> <ul> <li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li> </ul> <p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,9]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br /> The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no concatenated substring.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br /> The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br /> The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>1 &lt;= words[i].length &lt;= 30</code></li> <li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { unordered_map<string, int> cnt; for (const auto& w : words) { cnt[w]++; } vector<int> ans; int m = s.length(), n = words.size(), k = words[0].length(); for (int i = 0; i < k; ++i) { int l = i, r = i; unordered_map<string, int> cnt1; while (r + k <= m) { string t = s.substr(r, k); r += k; if (!cnt.contains(t)) { cnt1.clear(); l = r; continue; } cnt1[t]++; while (cnt1[t] > cnt[t]) { string w = s.substr(l, k); if (--cnt1[w] == 0) { cnt1.erase(w); } l += k; } if (r - l == n * k) { ans.push_back(l); } } } return ans; } };
30
Substring with Concatenation of All Words
Hard
<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p> <p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p> <ul> <li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li> </ul> <p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,9]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br /> The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no concatenated substring.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br /> The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br /> The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>1 &lt;= words[i].length &lt;= 30</code></li> <li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C#
public class Solution { public IList<int> FindSubstring(string s, string[] words) { var cnt = new Dictionary<string, int>(); foreach (var w in words) { if (cnt.ContainsKey(w)) { cnt[w]++; } else { cnt[w] = 1; } } var ans = new List<int>(); int m = s.Length, n = words.Length, k = words[0].Length; for (int i = 0; i < k; ++i) { int l = i, r = i; var cnt1 = new Dictionary<string, int>(); while (r + k <= m) { var t = s.Substring(r, k); r += k; if (!cnt.ContainsKey(t)) { cnt1.Clear(); l = r; continue; } if (cnt1.ContainsKey(t)) { cnt1[t]++; } else { cnt1[t] = 1; } while (cnt1[t] > cnt[t]) { var w = s.Substring(l, k); cnt1[w]--; if (cnt1[w] == 0) { cnt1.Remove(w); } l += k; } if (r - l == n * k) { ans.Add(l); } } } return ans; } }
30
Substring with Concatenation of All Words
Hard
<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p> <p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p> <ul> <li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li> </ul> <p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,9]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br /> The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no concatenated substring.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br /> The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br /> The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>1 &lt;= words[i].length &lt;= 30</code></li> <li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func findSubstring(s string, words []string) (ans []int) { cnt := make(map[string]int) for _, w := range words { cnt[w]++ } m, n, k := len(s), len(words), len(words[0]) for i := 0; i < k; i++ { l, r := i, i cnt1 := make(map[string]int) for r+k <= m { t := s[r : r+k] r += k if _, exists := cnt[t]; !exists { cnt1 = make(map[string]int) l = r continue } cnt1[t]++ for cnt1[t] > cnt[t] { w := s[l : l+k] cnt1[w]-- if cnt1[w] == 0 { delete(cnt1, w) } l += k } if r-l == n*k { ans = append(ans, l) } } } return }
30
Substring with Concatenation of All Words
Hard
<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p> <p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p> <ul> <li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li> </ul> <p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,9]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br /> The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no concatenated substring.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br /> The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br /> The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>1 &lt;= words[i].length &lt;= 30</code></li> <li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public List<Integer> findSubstring(String s, String[] words) { Map<String, Integer> cnt = new HashMap<>(); for (var w : words) { cnt.merge(w, 1, Integer::sum); } List<Integer> ans = new ArrayList<>(); int m = s.length(), n = words.length, k = words[0].length(); for (int i = 0; i < k; ++i) { int l = i, r = i; Map<String, Integer> cnt1 = new HashMap<>(); while (r + k <= m) { var t = s.substring(r, r + k); r += k; if (!cnt.containsKey(t)) { cnt1.clear(); l = r; continue; } cnt1.merge(t, 1, Integer::sum); while (cnt1.get(t) > cnt.get(t)) { String w = s.substring(l, l + k); if (cnt1.merge(w, -1, Integer::sum) == 0) { cnt1.remove(w); } l += k; } if (r - l == n * k) { ans.add(l); } } } return ans; } }
30
Substring with Concatenation of All Words
Hard
<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p> <p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p> <ul> <li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li> </ul> <p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,9]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br /> The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no concatenated substring.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br /> The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br /> The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>1 &lt;= words[i].length &lt;= 30</code></li> <li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
PHP
class Solution { /** * @param String $s * @param String[] $words * @return Integer[] */ function findSubstring($s, $words) { $cnt = []; foreach ($words as $w) { if (isset($cnt[$w])) { $cnt[$w]++; } else { $cnt[$w] = 1; } } $ans = []; $m = strlen($s); $n = count($words); $k = strlen($words[0]); for ($i = 0; $i < $k; $i++) { $l = $i; $r = $i; $cnt1 = []; while ($r + $k <= $m) { $t = substr($s, $r, $k); $r += $k; if (!isset($cnt[$t])) { $cnt1 = []; $l = $r; continue; } if (isset($cnt1[$t])) { $cnt1[$t]++; } else { $cnt1[$t] = 1; } while ($cnt1[$t] > $cnt[$t]) { $w = substr($s, $l, $k); $cnt1[$w]--; if ($cnt1[$w] == 0) { unset($cnt1[$w]); } $l += $k; } if ($r - $l == $n * $k) { $ans[] = $l; } } } return $ans; } }
30
Substring with Concatenation of All Words
Hard
<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p> <p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p> <ul> <li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li> </ul> <p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,9]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br /> The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no concatenated substring.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br /> The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br /> The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>1 &lt;= words[i].length &lt;= 30</code></li> <li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: cnt = Counter(words) m, n = len(s), len(words) k = len(words[0]) ans = [] for i in range(k): l = r = i cnt1 = Counter() while r + k <= m: t = s[r : r + k] r += k if cnt[t] == 0: l = r cnt1.clear() continue cnt1[t] += 1 while cnt1[t] > cnt[t]: rem = s[l : l + k] l += k cnt1[rem] -= 1 if r - l == n * k: ans.append(l) return ans
30
Substring with Concatenation of All Words
Hard
<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p> <p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p> <ul> <li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li> </ul> <p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,9]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br /> The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no concatenated substring.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p> <p><strong>Explanation:</strong></p> <p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br /> The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br /> The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length &lt;= 5000</code></li> <li><code>1 &lt;= words[i].length &lt;= 30</code></li> <li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
TypeScript
function findSubstring(s: string, words: string[]): number[] { const cnt: Map<string, number> = new Map(); for (const w of words) { cnt.set(w, (cnt.get(w) || 0) + 1); } const ans: number[] = []; const [m, n, k] = [s.length, words.length, words[0].length]; for (let i = 0; i < k; i++) { let [l, r] = [i, i]; const cnt1: Map<string, number> = new Map(); while (r + k <= m) { const t = s.substring(r, r + k); r += k; if (!cnt.has(t)) { cnt1.clear(); l = r; continue; } cnt1.set(t, (cnt1.get(t) || 0) + 1); while (cnt1.get(t)! > cnt.get(t)!) { const w = s.substring(l, l + k); cnt1.set(w, cnt1.get(w)! - 1); if (cnt1.get(w) === 0) { cnt1.delete(w); } l += k; } if (r - l === n * k) { ans.push(l); } } } return ans; }
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
C++
class Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size(); int i = n - 2; while (~i && nums[i] >= nums[i + 1]) { --i; } if (~i) { for (int j = n - 1; j > i; --j) { if (nums[j] > nums[i]) { swap(nums[i], nums[j]); break; } } } reverse(nums.begin() + i + 1, nums.end()); } };
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
C#
public class Solution { public void NextPermutation(int[] nums) { int n = nums.Length; int i = n - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { --i; } if (i >= 0) { for (int j = n - 1; j > i; --j) { if (nums[j] > nums[i]) { swap(nums, i, j); break; } } } for (int j = i + 1, k = n - 1; j < k; ++j, --k) { swap(nums, j, k); } } private void swap(int[] nums, int i, int j) { int t = nums[j]; nums[j] = nums[i]; nums[i] = t; } }
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
Go
func nextPermutation(nums []int) { n := len(nums) i := n - 2 for ; i >= 0 && nums[i] >= nums[i+1]; i-- { } if i >= 0 { for j := n - 1; j > i; j-- { if nums[j] > nums[i] { nums[i], nums[j] = nums[j], nums[i] break } } } for j, k := i+1, n-1; j < k; j, k = j+1, k-1 { nums[j], nums[k] = nums[k], nums[j] } }
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
Java
class Solution { public void nextPermutation(int[] nums) { int n = nums.length; int i = n - 2; for (; i >= 0; --i) { if (nums[i] < nums[i + 1]) { break; } } if (i >= 0) { for (int j = n - 1; j > i; --j) { if (nums[j] > nums[i]) { swap(nums, i, j); break; } } } for (int j = i + 1, k = n - 1; j < k; ++j, --k) { swap(nums, j, k); } } private void swap(int[] nums, int i, int j) { int t = nums[j]; nums[j] = nums[i]; nums[i] = t; } }
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
JavaScript
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var nextPermutation = function (nums) { const n = nums.length; let i = n - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { --i; } if (i >= 0) { let j = n - 1; while (j > i && nums[j] <= nums[i]) { --j; } [nums[i], nums[j]] = [nums[j], nums[i]]; } for (i = i + 1, j = n - 1; i < j; ++i, --j) { [nums[i], nums[j]] = [nums[j], nums[i]]; } };