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
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
C
#include <stdlib.h> int* twoSum(int* nums, int numsSize, int target, int* returnSize) { int capacity = 1; while (capacity < numsSize * 2) capacity <<= 1; int* keys = malloc(capacity * sizeof(int)); int* vals = malloc(capacity * sizeof(int)); char* used = calloc(capacity, sizeof(char)); if (!key...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Cangjie
class Solution { func twoSum(nums: Array<Int64>, target: Int64): Array<Int64> { let d = HashMap<Int64, Int64>() for (i in 0..nums.size) { if (d.contains(target - nums[i])) { return [d[target - nums[i]], i] } d[nums[i]] = i } ...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
C++
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> d; for (int i = 0;; ++i) { int x = nums[i]; int y = target - x; if (d.contains(y)) { return {d[y], i}; } d[x] = i; ...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
C#
public class Solution { public int[] TwoSum(int[] nums, int target) { var d = new Dictionary<int, int>(); for (int i = 0, j; ; ++i) { int x = nums[i]; int y = target - x; if (d.TryGetValue(y, out j)) { return new [] {j, i}; } ...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Go
func twoSum(nums []int, target int) []int { d := map[int]int{} for i := 0; ; i++ { x := nums[i] y := target - x if j, ok := d[y]; ok { return []int{j, i} } d[x] = i } }
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Java
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> d = new HashMap<>(); for (int i = 0;; ++i) { int x = nums[i]; int y = target - x; if (d.containsKey(y)) { return new int[] {d.get(y), i}; } ...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function (nums, target) { const d = new Map(); for (let i = 0; ; ++i) { const x = nums[i]; const y = target - x; if (d.has(y)) { return [d.get(y), i]; } d.set(x, i);...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Kotlin
class Solution { fun twoSum(nums: IntArray, target: Int): IntArray { val m = mutableMapOf<Int, Int>() nums.forEachIndexed { i, x -> val y = target - x val j = m.get(y) if (j != null) { return intArrayOf(j, i) } m[x] = i ...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Nim
import std/enumerate import std/tables proc twoSum(nums: seq[int], target: int): seq[int] = var d = initTable[int, int]() for i, x in nums.pairs(): let y = target - x if d.hasKey(y): return @[d[y], i] d[x] = i return @[]
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
PHP
class Solution { /** * @param Integer[] $nums * @param Integer $target * @return Integer[] */ function twoSum($nums, $target) { $d = []; foreach ($nums as $i => $x) { $y = $target - $x; if (isset($d[$y])) { return [$d[$y], $i]; ...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Python
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} for i, x in enumerate(nums): if (y := target - x) in d: return [d[y], i] d[x] = i
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Ruby
# @param {Integer[]} nums # @param {Integer} target # @return {Integer[]} def two_sum(nums, target) d = {} nums.each_with_index do |x, i| y = target - x if d.key?(y) return [d[y], i] end d[x] = i end end
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Rust
use std::collections::HashMap; impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut d = HashMap::new(); for (i, &x) in nums.iter().enumerate() { let y = target - x; if let Some(&j) = d.get(&y) { return vec![j as i32, i as i32]; ...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Scala
import scala.collection.mutable object Solution { def twoSum(nums: Array[Int], target: Int): Array[Int] = { val d = mutable.Map[Int, Int]() var ans: Array[Int] = Array() for (i <- nums.indices if ans.isEmpty) { val x = nums(i) val y = target - x if (d.con...
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
Swift
class Solution { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var d = [Int: Int]() for (i, x) in nums.enumerated() { let y = target - x if let j = d[y] { return [j, i] } d[x] = i } return [] } }
1
Two Sum
Easy
<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p> <p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> elemen...
Array; Hash Table
TypeScript
function twoSum(nums: number[], target: number): number[] { const d = new Map<number, number>(); for (let i = 0; ; ++i) { const x = nums[i]; const y = target - x; if (d.has(y)) { return [d.get(y)!, i]; } d.set(x, i); } }
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode* dummy = (struct ListNode*) malloc(sizeof(struct ListNode)); dummy->val = 0; dummy->next = NULL;...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
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* addTwoNumbe...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
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 AddTwoNumbers(ListNode l1...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { dummy := &ListNode{} carry := 0 cur := dummy for l1 != nil || l2 != nil || carry != 0 { s := carry if l1 != nil { s += l1.Val } if l...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
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 addTwoNumbers(ListNode ...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function (l1, l2) { const dummy = n...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
Nim
#[ # Driver code in the solution file # Definition for singly-linked list. type Node[int] = ref object value: int next: Node[int] SinglyLinkedList[T] = object head, tail: Node[T] ]# # More efficient code churning ... proc addTwoNumbers(l1: var SinglyLinkedList, l2: var Sing...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
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 $l1 * @param List...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers( self, l1: Optional[ListNode], l2: Optional[ListNode] ) -> Optional[ListNode]: dummy = ListNode() carry...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
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} l1 # @param {ListNode} l2 # @return {ListNode} def add_two_numbers(l1, l2) dummy = ListNode.new() carr...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
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...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
Swift
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init() { self.val = 0; self.next = nil; } * public init(_ val: Int) { self.val = val; self.next = nil; } * public init(_ val: Int, _ next: ListNode?) { self.val = val...
2
Add Two Numbers
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p> <p>You may assume the two numbers do not conta...
Recursion; Linked List; Math
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 addTwoNumbers(l1:...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
C
int lengthOfLongestSubstring(char* s) { int freq[256] = {0}; int l = 0, r = 0; int ans = 0; int len = strlen(s); for (r = 0; r < len; r++) { char c = s[r]; freq[(unsigned char) c]++; while (freq[(unsigned char) c] > 1) { freq[(unsigned char) s[l]]--; ...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
C++
class Solution { public: int lengthOfLongestSubstring(string s) { int cnt[128]{}; int ans = 0, n = s.size(); for (int l = 0, r = 0; r < n; ++r) { ++cnt[s[r]]; while (cnt[s[r]] > 1) { --cnt[s[l++]]; } ans = max(ans, r - l + 1); ...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
C#
public class Solution { public int LengthOfLongestSubstring(string s) { int n = s.Length; int ans = 0; var cnt = new int[128]; for (int l = 0, r = 0; r < n; ++r) { ++cnt[s[r]]; while (cnt[s[r]] > 1) { --cnt[s[l++]]; } an...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
Go
func lengthOfLongestSubstring(s string) (ans int) { cnt := [128]int{} l := 0 for r, c := range s { cnt[c]++ for cnt[c] > 1 { cnt[s[l]]-- l++ } ans = max(ans, r-l+1) } return }
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
Java
class Solution { public int lengthOfLongestSubstring(String s) { int[] cnt = new int[128]; int ans = 0, n = s.length(); for (int l = 0, r = 0; r < n; ++r) { char c = s.charAt(r); ++cnt[c]; while (cnt[c] > 1) { --cnt[s.charAt(l++)]; ...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
JavaScript
/** * @param {string} s * @return {number} */ var lengthOfLongestSubstring = function (s) { let ans = 0; const n = s.length; const cnt = new Map(); for (let l = 0, r = 0; r < n; ++r) { cnt.set(s[r], (cnt.get(s[r]) || 0) + 1); while (cnt.get(s[r]) > 1) { cnt.set(s[l], cnt.g...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
Kotlin
class Solution { fun lengthOfLongestSubstring(s: String): Int { val n = s.length var ans = 0 val cnt = IntArray(128) var l = 0 for (r in 0 until n) { cnt[s[r].toInt()]++ while (cnt[s[r].toInt()] > 1) { cnt[s[l].toInt()]-- ...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
PHP
class Solution { function lengthOfLongestSubstring($s) { $n = strlen($s); $ans = 0; $cnt = array_fill(0, 128, 0); $l = 0; for ($r = 0; $r < $n; ++$r) { $cnt[ord($s[$r])]++; while ($cnt[ord($s[$r])] > 1) { $cnt[ord($s[$l])]--; ...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
Python
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: cnt = Counter() ans = l = 0 for r, c in enumerate(s): cnt[c] += 1 while cnt[c] > 1: cnt[s[l]] -= 1 l += 1 ans = max(ans, r - l + 1) return ans
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
Rust
impl Solution { pub fn length_of_longest_substring(s: String) -> i32 { let mut cnt = [0; 128]; let mut ans = 0; let mut l = 0; let chars: Vec<char> = s.chars().collect(); let n = chars.len(); for (r, &c) in chars.iter().enumerate() { cnt[c as usize] += 1; ...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
Swift
class Solution { func lengthOfLongestSubstring(_ s: String) -> Int { let n = s.count var ans = 0 var cnt = [Int](repeating: 0, count: 128) var l = 0 let sArray = Array(s) for r in 0..<n { cnt[Int(sArray[r].asciiValue!)] += 1 while cnt[Int(sArra...
3
Longest Substring Without Repeating Characters
Medium
<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword="substring-nonempty"><strong>substring</strong></span> without duplicate characters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcabcbb&quot; <strong>...
Hash Table; String; Sliding Window
TypeScript
function lengthOfLongestSubstring(s: string): number { let ans = 0; const cnt = new Map<string, number>(); const n = s.length; for (let l = 0, r = 0; r < n; ++r) { cnt.set(s[r], (cnt.get(s[r]) || 0) + 1); while (cnt.get(s[r])! > 1) { cnt.set(s[l], cnt.get(s[l])! - 1); ...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
C
int findKth(int* nums1, int m, int i, int* nums2, int n, int j, int k) { if (i >= m) return nums2[j + k - 1]; if (j >= n) return nums1[i + k - 1]; if (k == 1) return nums1[i] < nums2[j] ? nums1[i] : nums2[j]; int p = k / 2; int x = (i + p - 1 < m) ? nums1[i + p - 1] : INT_M...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
C++
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); function<int(int, int, int)> f = [&](int i, int j, int k) { if (i >= m) { return nums2[j + k - 1]; } if (j >= n...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
C#
public class Solution { private int m; private int n; private int[] nums1; private int[] nums2; public double FindMedianSortedArrays(int[] nums1, int[] nums2) { m = nums1.Length; n = nums2.Length; this.nums1 = nums1; this.nums2 = nums2; int a = f(0, 0, (m + n...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
Go
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { m, n := len(nums1), len(nums2) var f func(i, j, k int) int f = func(i, j, k int) int { if i >= m { return nums2[j+k-1] } if j >= n { return nums1[i+k-1] } if k == 1 { return min(nums1[i], nums2[j]) } p := k / 2 x, y := 1<<30, 1<...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
Java
class Solution { private int m; private int n; private int[] nums1; private int[] nums2; public double findMedianSortedArrays(int[] nums1, int[] nums2) { m = nums1.length; n = nums2.length; this.nums1 = nums1; this.nums2 = nums2; int a = f(0, 0, (m + n + 1) /...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
JavaScript
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var findMedianSortedArrays = function (nums1, nums2) { const m = nums1.length; const n = nums2.length; const f = (i, j, k) => { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { ...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
Nim
import std/[algorithm, sequtils] proc medianOfTwoSortedArrays(nums1: seq[int], nums2: seq[int]): float = var fullList: seq[int] = concat(nums1, nums2) value: int = fullList.len div 2 fullList.sort() if fullList.len mod 2 == 0: result = (fullList[value - 1] + fullList[value]) / 2 else: result ...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
PHP
class Solution { /** * @param int[] $nums1 * @param int[] $nums2 * @return float */ function findMedianSortedArrays($nums1, $nums2) { $arr = array_merge($nums1, $nums2); sort($arr); $cnt_arr = count($arr); if ($cnt_arr % 2) { return $arr[$cnt_arr...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
Python
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: def f(i: int, j: int, k: int) -> int: if i >= m: return nums2[j + k - 1] if j >= n: return nums1[i + k - 1] if k == 1: return min...
4
Median of Two Sorted Arrays
Hard
<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p> <p>The overall run time complexity should be <code>O(log (m+n))</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:<...
Array; Binary Search; Divide and Conquer
TypeScript
function findMedianSortedArrays(nums1: number[], nums2: number[]): number { const m = nums1.length; const n = nums2.length; const f = (i: number, j: number, k: number): number => { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1];...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
C
char* longestPalindrome(char* s) { int n = strlen(s); bool** f = (bool**) malloc(n * sizeof(bool*)); for (int i = 0; i < n; ++i) { f[i] = (bool*) malloc(n * sizeof(bool)); for (int j = 0; j < n; ++j) { f[i][j] = true; } } int k = 0, mx = 1; for (int i = n - 2;...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
C++
class Solution { public: string longestPalindrome(string s) { int n = s.size(); vector<vector<bool>> f(n, vector<bool>(n, true)); int k = 0, mx = 1; for (int i = n - 2; ~i; --i) { for (int j = i + 1; j < n; ++j) { f[i][j] = false; if (s[i] ...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
C#
public class Solution { public string LongestPalindrome(string s) { int n = s.Length; bool[,] f = new bool[n, n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; ++j) { f[i, j] = true; } } int k = 0, mx = 1; for (int i = n ...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
Go
func longestPalindrome(s string) string { n := len(s) f := make([][]bool, n) for i := range f { f[i] = make([]bool, n) for j := range f[i] { f[i][j] = true } } k, mx := 0, 1 for i := n - 2; i >= 0; i-- { for j := i + 1; j < n; j++ { f[i][j] = false if s[i] == s[j] { f[i][j] = f[i+1][j-1] ...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
Java
class Solution { public String longestPalindrome(String s) { int n = s.length(); boolean[][] f = new boolean[n][n]; for (var g : f) { Arrays.fill(g, true); } int k = 0, mx = 1; for (int i = n - 2; i >= 0; --i) { for (int j = i + 1; j < n; ++j) ...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
JavaScript
/** * @param {string} s * @return {string} */ var longestPalindrome = function (s) { const n = s.length; const f = Array(n) .fill(0) .map(() => Array(n).fill(true)); let k = 0; let mx = 1; for (let i = n - 2; i >= 0; --i) { for (let j = i + 1; j < n; ++j) { f[i...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
Nim
import std/sequtils proc longestPalindrome(s: string): string = let n: int = s.len() var dp = newSeqWith[bool](n, newSeqWith[bool](n, false)) start: int = 0 mx: int = 1 for j in 0 ..< n: for i in 0 .. j: if j - i < 2: dp[i][j] = s[i] == s[j] else: dp[i][j] = dp[i + 1]...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
PHP
class Solution { /** * @param string $s * @return string */ function longestPalindrome($s) { $start = 0; $maxLength = 0; for ($i = 0; $i < strlen($s); $i++) { $len1 = $this->expandFromCenter($s, $i, $i); $len2 = $this->expandFromCenter($s, $i, $i +...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
Python
class Solution: def longestPalindrome(self, s: str) -> str: n = len(s) f = [[True] * n for _ in range(n)] k, mx = 0, 1 for i in range(n - 2, -1, -1): for j in range(i + 1, n): f[i][j] = False if s[i] == s[j]: f[i][j] = f...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
Rust
impl Solution { pub fn longest_palindrome(s: String) -> String { let (n, mut ans) = (s.len(), &s[..1]); let mut dp = vec![vec![false; n]; n]; let data: Vec<char> = s.chars().collect(); for end in 1..n { for start in 0..=end { if data[start] == data[end] {...
5
Longest Palindromic Substring
Medium
<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = ...
Two Pointers; String; Dynamic Programming
TypeScript
function longestPalindrome(s: string): string { const n = s.length; const f: boolean[][] = Array(n) .fill(0) .map(() => Array(n).fill(true)); let k = 0; let mx = 1; for (let i = n - 2; i >= 0; --i) { for (let j = i + 1; j < n; ++j) { f[i][j] = false; i...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
C
char* convert(char* s, int numRows) { if (numRows == 1) { return strdup(s); } int len = strlen(s); char** g = (char**) malloc(numRows * sizeof(char*)); int* idx = (int*) malloc(numRows * sizeof(int)); for (int i = 0; i < numRows; ++i) { g[i] = (char*) malloc((len + 1) * sizeof(c...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
C++
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) { return s; } vector<string> g(numRows); int i = 0, k = -1; for (char c : s) { g[i] += c; if (i == 0 || i == numRows - 1) { k = -k; ...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
C#
public class Solution { public string Convert(string s, int numRows) { if (numRows == 1) { return s; } int n = s.Length; StringBuilder[] g = new StringBuilder[numRows]; for (int j = 0; j < numRows; ++j) { g[j] = new StringBuilder(); } i...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
Go
func convert(s string, numRows int) string { if numRows == 1 { return s } g := make([][]byte, numRows) i, k := 0, -1 for _, c := range s { g[i] = append(g[i], byte(c)) if i == 0 || i == numRows-1 { k = -k } i += k } return string(bytes.Join(g, nil)) }
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
Java
class Solution { public String convert(String s, int numRows) { if (numRows == 1) { return s; } StringBuilder[] g = new StringBuilder[numRows]; Arrays.setAll(g, k -> new StringBuilder()); int i = 0, k = -1; for (char c : s.toCharArray()) { g[i]...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
JavaScript
/** * @param {string} s * @param {number} numRows * @return {string} */ var convert = function (s, numRows) { if (numRows === 1) { return s; } const g = new Array(numRows).fill(_).map(() => []); let i = 0; let k = -1; for (const c of s) { g[i].push(c); if (i === 0 || ...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
PHP
class Solution { /** * @param String $s * @param Integer $numRows * @return String */ function convert($s, $numRows) { if ($numRows == 1) { return $s; } $g = array_fill(0, $numRows, ""); $i = 0; $k = -1; $length = strlen($s); ...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
Python
class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s g = [[] for _ in range(numRows)] i, k = 0, -1 for c in s: g[i].append(c) if i == 0 or i == numRows - 1: k = -k i += k retu...
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
Rust
impl Solution { pub fn convert(s: String, num_rows: i32) -> String { if num_rows == 1 { return s; } let num_rows = num_rows as usize; let mut g = vec![String::new(); num_rows]; let mut i = 0; let mut k = -1; for c in s.chars() { g[i]....
6
Zigzag Conversion
Medium
<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p> <pre> P A H N A P L S I I G Y I R </pre> <p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;<...
String
TypeScript
function convert(s: string, numRows: number): string { if (numRows === 1) { return s; } const g: string[][] = new Array(numRows).fill(0).map(() => []); let i = 0; let k = -1; for (const c of s) { g[i].push(c); if (i === numRows - 1 || i === 0) { k = -k; ...
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
C
int reverse(int x) { int ans = 0; for (; x != 0; x /= 10) { if (ans > INT_MAX / 10 || ans < INT_MIN / 10) { return 0; } ans = ans * 10 + x % 10; } return ans; }
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
C++
class Solution { public: int reverse(int x) { int ans = 0; for (; x; x /= 10) { if (ans < INT_MIN / 10 || ans > INT_MAX / 10) { return 0; } ans = ans * 10 + x % 10; } return ans; } };
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
C#
public class Solution { public int Reverse(int x) { int ans = 0; for (; x != 0; x /= 10) { if (ans < int.MinValue / 10 || ans > int.MaxValue / 10) { return 0; } ans = ans * 10 + x % 10; } return ans; } }
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
Go
func reverse(x int) (ans int) { for ; x != 0; x /= 10 { if ans < math.MinInt32/10 || ans > math.MaxInt32/10 { return 0 } ans = ans*10 + x%10 } return }
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
Java
class Solution { public int reverse(int x) { int ans = 0; for (; x != 0; x /= 10) { if (ans < Integer.MIN_VALUE / 10 || ans > Integer.MAX_VALUE / 10) { return 0; } ans = ans * 10 + x % 10; } return ans; } }
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
JavaScript
/** * @param {number} x * @return {number} */ var reverse = function (x) { const mi = -(2 ** 31); const mx = 2 ** 31 - 1; let ans = 0; for (; x != 0; x = ~~(x / 10)) { if (ans < ~~(mi / 10) || ans > ~~(mx / 10)) { return 0; } ans = ans * 10 + (x % 10); } re...
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
PHP
class Solution { /** * @param int $x * @return int */ function reverse($x) { $isNegative = $x < 0; $x = abs($x); $reversed = 0; while ($x > 0) { $reversed = $reversed * 10 + ($x % 10); $x = (int) ($x / 10); } if ($isNegat...
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
Python
class Solution: def reverse(self, x: int) -> int: ans = 0 mi, mx = -(2**31), 2**31 - 1 while x: if ans < mi // 10 + 1 or ans > mx // 10: return 0 y = x % 10 if x < 0 and y > 0: y -= 10 ans = ans * 10 + y ...
7
Reverse Integer
Medium
<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p> <p><strong>Assume the environment does...
Math
Rust
impl Solution { pub fn reverse(mut x: i32) -> i32 { let is_minus = x < 0; match x .abs() .to_string() .chars() .rev() .collect::<String>() .parse::<i32>() { Ok(x) => x * (if is_minus { -1 } else { 1 }), ...
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
C
int myAtoi(char* s) { int i = 0; while (s[i] == ' ') { i++; } int sign = 1; if (s[i] == '-' || s[i] == '+') { sign = (s[i] == '-') ? -1 : 1; i++; } int res = 0; while (isdigit(s[i])) { int digit = s[i] - '0'; if (res > INT_MAX / 10 || (res == IN...
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
C++
class Solution { public: int myAtoi(string s) { int i = 0, n = s.size(); while (i < n && s[i] == ' ') ++i; int sign = 1; if (i < n && (s[i] == '-' || s[i] == '+')) { sign = s[i] == '-' ? -1 : 1; ++i; } int res = 0; while (...
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
C#
// https://leetcode.com/problems/string-to-integer-atoi/ public partial class Solution { public int MyAtoi(string str) { int i = 0; long result = 0; bool minus = false; while (i < str.Length && char.IsWhiteSpace(str[i])) { ++i; } if (i < str....
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
Go
func myAtoi(s string) int { i, n := 0, len(s) num := 0 for i < n && s[i] == ' ' { i++ } if i == n { return 0 } sign := 1 if s[i] == '-' { sign = -1 i++ } else if s[i] == '+' { i++ } for i < n && s[i] >= '0' && s[i] <= '9' { num = num*10 + int(s[i]-'0') i++ if num > math.MaxInt32 { break...
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
Java
class Solution { public int myAtoi(String s) { if (s == null) return 0; int n = s.length(); if (n == 0) return 0; int i = 0; while (s.charAt(i) == ' ') { // 仅包含空格 if (++i == n) return 0; } int sign = 1; if (s.charAt(i) == '-') s...
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
JavaScript
const myAtoi = function (str) { str = str.trim(); if (!str) return 0; let isPositive = 1; let i = 0, ans = 0; if (str[i] === '+') { isPositive = 1; i++; } else if (str[i] === '-') { isPositive = 0; i++; } for (; i < str.length; i++) { let t...
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
PHP
class Solution { /** * @param string $s * @return int */ function myAtoi($s) { $s = str_replace('e', 'x', $s); if (intval($s) < pow(-2, 31)) { return -2147483648; } if (intval($s) > pow(2, 31) - 1) { return 2147483647; } ret...
8
String to Integer (atoi)
Medium
<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p> <p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p> <ol> <li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li> <li><strong>Signedness</strong...
String
Python
class Solution: def myAtoi(self, s: str) -> int: if not s: return 0 n = len(s) if n == 0: return 0 i = 0 while s[i] == ' ': i += 1 # 仅包含空格 if i == n: return 0 sign = -1 if s[i] == '-' else 1 ...
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
C
bool isPalindrome(int x) { if (x < 0 || (x != 0 && x % 10 == 0)) { return false; } int y = 0; while (y < x) { y = y * 10 + x % 10; x /= 10; } return (x == y || x == y / 10); }
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
C++
class Solution { public: bool isPalindrome(int x) { if (x < 0 || (x && x % 10 == 0)) { return false; } int y = 0; for (; y < x; x /= 10) { y = y * 10 + x % 10; } return x == y || x == y / 10; } };
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
C#
public class Solution { public bool IsPalindrome(int x) { if (x < 0 || (x > 0 && x % 10 == 0)) { return false; } int y = 0; for (; y < x; x /= 10) { y = y * 10 + x % 10; } return x == y || x == y / 10; } }
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
Go
func isPalindrome(x int) bool { if x < 0 || (x > 0 && x%10 == 0) { return false } y := 0 for ; y < x; x /= 10 { y = y*10 + x%10 } return x == y || x == y/10 }
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
Java
class Solution { public boolean isPalindrome(int x) { if (x < 0 || (x > 0 && x % 10 == 0)) { return false; } int y = 0; for (; y < x; x /= 10) { y = y * 10 + x % 10; } return x == y || x == y / 10; } }
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
JavaScript
/** * @param {number} x * @return {boolean} */ var isPalindrome = function (x) { if (x < 0 || (x > 0 && x % 10 === 0)) { return false; } let y = 0; for (; y < x; x = ~~(x / 10)) { y = y * 10 + (x % 10); } return x === y || x === ~~(y / 10); };
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
PHP
class Solution { /** * @param Integer $x * @return Boolean */ function isPalindrome($x) { if ($x < 0 || ($x && $x % 10 == 0)) { return false; } $y = 0; while ($x > $y) { $y = $y * 10 + ($x % 10); $x = (int) ($x / 10); } ...
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
Python
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0 or (x and x % 10 == 0): return False y = 0 while y < x: y = y * 10 + x % 10 x //= 10 return x in (y, y // 10)
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
Rust
impl Solution { pub fn is_palindrome(mut x: i32) -> bool { if x < 0 || (x != 0 && x % 10 == 0) { return false; } let mut y = 0; while x > y { y = y * 10 + x % 10; x /= 10; } x == y || x == y / 10 } }
9
Palindrome Number
Easy
<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword="palindrome-integer"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <str...
Math
TypeScript
function isPalindrome(x: number): boolean { if (x < 0 || (x > 0 && x % 10 === 0)) { return false; } let y = 0; for (; y < x; x = ~~(x / 10)) { y = y * 10 + (x % 10); } return x === y || x === ~~(y / 10); }
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more...
Recursion; String; Dynamic Programming
C
#define MAX_LEN 1000 char *ss, *pp; int m, n; int f[MAX_LEN + 1][MAX_LEN + 1]; bool dfs(int i, int j) { if (j >= n) { return i == m; } if (f[i][j] != 0) { return f[i][j] == 1; } int res = -1; if (j + 1 < n && pp[j + 1] == '*') { if (dfs(i, j + 2) || (i < m && (ss[i] == ...