id int64 1 3.71k | 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>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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 == ... |
20 | Valid Parentheses | Easy | <p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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 fals... |
20 | Valid Parentheses | Easy | <p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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 {
... |
20 | Valid Parentheses | Easy | <p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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];
... |
20 | Valid Parentheses | Easy | <p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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 -... |
20 | Valid Parentheses | Easy | <p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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) {
... |
20 | Valid Parentheses | Easy | <p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ol>
<li>Open ... | 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 stac... |
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> </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* mergeTwoLis... |
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> </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 MergeTwoLists(ListNode li... |
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> </p... | 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.Nex... |
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> </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 mergeTwoLists(ListNode ... |
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> </p... | 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 ... |
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> </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 $list1
* @param ... |
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> </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 mergeTwoLists(
self, list1: Optional[ListNode], list2: Optional[ListNode]
) -> Optional[ListNode]:
if list1 is None or 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> </p... | 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?
... |
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> </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 Solutio... |
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> </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 mergeTwoLists(lis... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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;... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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) {
retu... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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;
... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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(... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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;
}
... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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 + ')')
... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><stro... | 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 = ... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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[] li... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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) ... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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[] ... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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({ pri... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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 m... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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)
... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> lists = ... | 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... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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(L... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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) ... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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 linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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 h... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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
*/
fu... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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 ... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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 = hea... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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 Solutio... |
24 | Swap Nodes in Pairs | Medium | <p>Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong... | 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: L... |
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-ou... | 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*... |
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-ou... | 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(ListNod... |
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-ou... | 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... |
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-ou... | 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 ... |
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-ou... | 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 In... |
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-ou... | 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]:... |
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-ou... | 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 Solutio... |
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-ou... | 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(hea... |
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... | 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... | 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... | 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... | 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... | 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... | 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... | 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... | 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... | 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 e... | 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 e... | 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 e... | 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 e... | 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 e... | 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 e... | 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 e... | 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 e... | 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 e... | 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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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;
... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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;
}
... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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) == need... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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++) {
le... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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($s... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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 {
wh... |
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> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<stro... | 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;
... |
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 <co... | 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... |
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 <co... | 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;
... |
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 <co... | 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
... |
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 <co... | 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 : ... |
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 <co... | 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) ... |
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 <co... | 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... |
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 <co... | 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 <= ... |
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>
... | 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; ... |
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>
... | 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;
}
}
va... |
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>
... | 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];... |
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>
... | 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 = word... |
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>
... | 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;
... |
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>
... | 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[... |
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>
... | 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++) {
... |
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>
... | 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]) {
... |
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>
... | 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]) {
... |
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>
... | 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],... |
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>
... | 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 ... |
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>
... | 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.