id
int64
1
3.63k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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 (!keys || !vals || !used) { free(keys); free(vals); free(used); *returnSize = 0; return NULL; } for (int i = 0; i < numsSize; ++i) { int x = nums[i]; int y = target - x; unsigned int h = (unsigned int) y & (capacity - 1); while (used[h]) { if (keys[h] == y) { int* res = malloc(2 * sizeof(int)); res[0] = vals[h]; res[1] = i; *returnSize = 2; free(keys); free(vals); free(used); return res; } h = (h + 1) & (capacity - 1); } unsigned int h2 = (unsigned int) x & (capacity - 1); while (used[h2]) h2 = (h2 + 1) & (capacity - 1); used[h2] = 1; keys[h2] = x; vals[h2] = i; } *returnSize = 0; free(keys); free(vals); free(used); return NULL; }
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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}; } if (!d.ContainsKey(x)) { d.Add(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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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}; } d.put(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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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 } return intArrayOf() } }
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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]; } $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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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]; } d.insert(x, i); } vec![] } }
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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.contains(y)) { ans = Array(d(y), i) } else { d(x) = i } } ans } }
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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> element twice.</p> <p>You can return the answer in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,11,15], target = 9 <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], target = 6 <strong>Output:</strong> [1,2] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3], target = 6 <strong>Output:</strong> [0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> <li><strong>Only one valid answer exists.</strong></li> </ul> <p>&nbsp;</p> <strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face="monospace">&nbsp;</font>time complexity?
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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; struct ListNode* curr = dummy; int carry = 0; while (l1 != NULL || l2 != NULL || carry != 0) { int sum = carry; if (l1 != NULL) { sum += l1->val; l1 = l1->next; } if (l2 != NULL) { sum += l2->val; l2 = l2->next; } carry = sum / 10; int val = sum % 10; struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode)); newNode->val = val; newNode->next = NULL; curr->next = newNode; curr = curr->next; } struct ListNode* result = dummy->next; free(dummy); return result; }
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode dummy; int carry = 0; ListNode* cur = &dummy; while (l1 || l2 || carry) { int s = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; carry = s / 10; cur->next = new ListNode(s % 10); cur = cur->next; l1 = l1 ? l1->next : nullptr; l2 = l2 ? l2->next : nullptr; } return dummy.next; } };
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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, ListNode l2) { ListNode dummy = new ListNode(); int carry = 0; ListNode cur = dummy; while (l1 != null || l2 != null || carry != 0) { int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; carry = s / 10; cur.next = new ListNode(s % 10); cur = cur.next; l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; } return dummy.next; } }
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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 l2 != nil { s += l2.Val } carry = s / 10 cur.Next = &ListNode{s % 10, nil} cur = cur.Next if l1 != nil { l1 = l1.Next } if l2 != nil { l2 = l2.Next } } return dummy.Next }
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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 l1, ListNode l2) { ListNode dummy = new ListNode(0); int carry = 0; ListNode cur = dummy; while (l1 != null || l2 != null || carry != 0) { int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; carry = s / 10; cur.next = new ListNode(s % 10); cur = cur.next; l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; } return dummy.next; } }
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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 = new ListNode(); let carry = 0; let cur = dummy; while (l1 || l2 || carry) { const s = (l1?.val || 0) + (l2?.val || 0) + carry; carry = Math.floor(s / 10); cur.next = new ListNode(s % 10); cur = cur.next; l1 = l1?.next; l2 = l2?.next; } return dummy.next; };
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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 SinglyLinkedList): SinglyLinkedList[int] = var aggregate: SinglyLinkedList psum: seq[char] temp_la, temp_lb: seq[int] while not l1.head.isNil: temp_la.add(l1.head.value) l1.head = l1.head.next while not l2.head.isNil: temp_lb.add(l2.head.value) l2.head = l2.head.next psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) for i in psum: aggregate.append(($i).parseInt()) result = aggregate
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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 ListNode $l2 * @return ListNode */ function addTwoNumbers($l1, $l2) { $dummy = new ListNode(0); $current = $dummy; $carry = 0; while ($l1 !== null || $l2 !== null) { $x = $l1 !== null ? $l1->val : 0; $y = $l2 !== null ? $l2->val : 0; $sum = $x + $y + $carry; $carry = (int) ($sum / 10); $current->next = new ListNode($sum % 10); $current = $current->next; if ($l1 !== null) { $l1 = $l1->next; } if ($l2 !== null) { $l2 = $l2->next; } } if ($carry > 0) { $current->next = new ListNode($carry); } return $dummy->next; } }
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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, curr = 0, dummy while l1 or l2 or carry: s = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry carry, val = divmod(s, 10) curr.next = ListNode(val) curr = curr.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None return dummy.next
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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() carry = 0 cur = dummy while !l1.nil? || !l2.nil? || carry > 0 s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry carry = s / 10 cur.next = ListNode.new(s % 10) cur = cur.next l1 = l1.nil? ? l1 : l1.next l2 = l2.nil? ? l2 : l2.next end dummy.next end
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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 Solution { pub fn add_two_numbers( mut l1: Option<Box<ListNode>>, mut l2: Option<Box<ListNode>>, ) -> Option<Box<ListNode>> { let mut dummy = Some(Box::new(ListNode::new(0))); let mut cur = &mut dummy; let mut sum = 0; while l1.is_some() || l2.is_some() || sum != 0 { if let Some(node) = l1 { sum += node.val; l1 = node.next; } if let Some(node) = l2 { sum += node.val; l2 = node.next; } cur.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum % 10))); cur = &mut cur.as_mut().unwrap().next; sum /= 10; } dummy.unwrap().next.take() } }
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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; self.next = next; } * } */ class Solution { func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { var dummy = ListNode.init() var carry = 0 var l1 = l1 var l2 = l2 var cur = dummy while l1 != nil || l2 != nil || carry != 0 { let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry carry = s / 10 cur.next = ListNode.init(s % 10) cur = cur.next! l1 = l1?.next l2 = l2?.next } return dummy.next } }
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 contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0002.Add%20Two%20Numbers/images/addtwonumber1.jpg" style="width: 483px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,0,8] <strong>Explanation:</strong> 342 + 465 = 807. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] <strong>Output:</strong> [8,9,9,9,0,0,0,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul>
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: ListNode | null, l2: ListNode | null): ListNode | null { const dummy = new ListNode(); let cur = dummy; let sum = 0; while (l1 != null || l2 != null || sum !== 0) { if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } cur.next = new ListNode(sum % 10); cur = cur.next; sum = Math.floor(sum / 10); } return dummy.next; }
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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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]]--; l++; } if (ans < r - l + 1) { 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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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); } 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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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++]]; } ans = Math.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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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++)]; } ans = Math.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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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.get(s[l]) - 1); ++l; } ans = Math.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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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()]-- l++ } ans = Math.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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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])]--; $l++; } $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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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; while cnt[c as usize] > 1 { cnt[chars[l] as usize] -= 1; l += 1; } ans = ans.max((r - l + 1) as i32); } 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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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(sArray[r].asciiValue!)] > 1 { cnt[Int(sArray[l].asciiValue!)] -= 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>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;bbbbb&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;pwwkew&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3. Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of English letters, digits, symbols and spaces.</li> </ul>
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); ++l; } ans = Math.max(ans, r - l + 1); } return ans; }
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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_MAX; int y = (j + p - 1 < n) ? nums2[j + p - 1] : INT_MAX; if (x < y) return findKth(nums1, m, i + p, nums2, n, j, k - p); else return findKth(nums1, m, i, nums2, n, j + p, k - p); } double findMedianSortedArrays(int* nums1, int m, int* nums2, int n) { int total = m + n; int a = findKth(nums1, m, 0, nums2, n, 0, (total + 1) / 2); int b = findKth(nums1, m, 0, nums2, n, 0, (total + 2) / 2); return (a + b) / 2.0; }
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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) { return nums1[i + k - 1]; } if (k == 1) { return min(nums1[i], nums2[j]); } int p = k / 2; int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); }; int a = f(0, 0, (m + n + 1) / 2); int b = f(0, 0, (m + n + 2) / 2); return (a + b) / 2.0; } };
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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 + 1) / 2); int b = f(0, 0, (m + n + 2) / 2); return (a + b) / 2.0; } private int f(int i, int j, int k) { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1]; } if (k == 1) { return Math.Min(nums1[i], nums2[j]); } int p = k / 2; int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); } }
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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<<30 if ni := i + p - 1; ni < m { x = nums1[ni] } if nj := j + p - 1; nj < n { y = nums2[nj] } if x < y { return f(i+p, j, k-p) } return f(i, j+p, k-p) } a, b := f(0, 0, (m+n+1)/2), f(0, 0, (m+n+2)/2) return float64(a+b) / 2.0 }
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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) / 2); int b = f(0, 0, (m + n + 2) / 2); return (a + b) / 2.0; } private int f(int i, int j, int k) { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1]; } if (k == 1) { return Math.min(nums1[i], nums2[j]); } int p = k / 2; int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); } }
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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) { return nums1[i + k - 1]; } if (k == 1) { return Math.min(nums1[i], nums2[j]); } const p = Math.floor(k / 2); const x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; const y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); }; const a = f(0, 0, Math.floor((m + n + 1) / 2)); const b = f(0, 0, Math.floor((m + n + 2) / 2)); return (a + b) / 2; };
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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 = fullList[value].toFloat() # Driver Code # var # arrA: seq[int] = @[1, 2] # arrB: seq[int] = @[3, 4, 5] # echo medianOfTwoSortedArrays(arrA, arrB)
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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 / 2]; } else { return ($arr[intdiv($cnt_arr, 2) - 1] + $arr[intdiv($cnt_arr, 2)]) / 2; } } }
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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(nums1[i], nums2[j]) p = k // 2 x = nums1[i + p - 1] if i + p - 1 < m else inf y = nums2[j + p - 1] if j + p - 1 < n else inf return f(i + p, j, k - p) if x < y else f(i, j + p, k - p) m, n = len(nums1), len(nums2) a = f(0, 0, (m + n + 1) // 2) b = f(0, 0, (m + n + 2) // 2) return (a + b) / 2
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:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3], nums2 = [2] <strong>Output:</strong> 2.00000 <strong>Explanation:</strong> merged array = [1,2,3] and median is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [3,4] <strong>Output:</strong> 2.50000 <strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == m</code></li> <li><code>nums2.length == n</code></li> <li><code>0 &lt;= m &lt;= 1000</code></li> <li><code>0 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= m + n &lt;= 2000</code></li> <li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> </ul>
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]; } if (k == 1) { return Math.min(nums1[i], nums2[j]); } const p = Math.floor(k / 2); const x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; const y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); }; const a = f(0, 0, Math.floor((m + n + 1) / 2)); const b = f(0, 0, Math.floor((m + n + 2) / 2)); return (a + b) / 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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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; ~i; --i) { for (int j = i + 1; j < n; ++j) { f[i][j] = false; if (s[i] == s[j]) { f[i][j] = f[i + 1][j - 1]; if (f[i][j] && mx < j - i + 1) { mx = j - i + 1; k = i; } } } } char* res = (char*) malloc((mx + 1) * sizeof(char)); strncpy(res, s + k, mx); res[mx] = '\0'; for (int i = 0; i < n; ++i) { free(f[i]); } free(f); return res; }
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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] == s[j]) { f[i][j] = f[i + 1][j - 1]; if (f[i][j] && mx < j - i + 1) { mx = j - i + 1; k = i; } } } } return s.substr(k, mx); } };
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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 - 2; i >= 0; --i) { for (int j = i + 1; j < n; ++j) { f[i, j] = false; if (s[i] == s[j]) { f[i, j] = f[i + 1, j - 1]; if (f[i, j] && mx < j - i + 1) { mx = j - i + 1; k = i; } } } } return s.Substring(k, mx); } }
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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] if f[i][j] && mx < j-i+1 { mx = j - i + 1 k = i } } } } return s[k : k+mx] }
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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) { f[i][j] = false; if (s.charAt(i) == s.charAt(j)) { f[i][j] = f[i + 1][j - 1]; if (f[i][j] && mx < j - i + 1) { mx = j - i + 1; k = i; } } } } return s.substring(k, k + mx); } }
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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][j] = false; if (s[i] === s[j]) { f[i][j] = f[i + 1][j - 1]; if (f[i][j] && mx < j - i + 1) { mx = j - i + 1; k = i; } } } } return s.slice(k, k + mx); };
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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][j - 1] and s[i] == s[j] if dp[i][j] and mx < j - i + 1: start = i mx = j - i + 1 result = s[start ..< start+mx]
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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 + 1); $len = max($len1, $len2); if ($len > $maxLength) { $start = $i - intval(($len - 1) / 2); $maxLength = $len; } } return substr($s, $start, $maxLength); } function expandFromCenter($s, $left, $right) { while ($left >= 0 && $right < strlen($s) && $s[$left] === $s[$right]) { $left--; $right++; } return $right - $left - 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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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[i + 1][j - 1] if f[i][j] and mx < j - i + 1: k, mx = i, j - i + 1 return s[k : k + mx]
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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] { dp[start][end] = end - start < 2 || dp[start + 1][end - 1]; if dp[start][end] && end - start + 1 > ans.len() { ans = &s[start..=end]; } } } } ans.to_string() } }
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 = &quot;babad&quot; <strong>Output:</strong> &quot;bab&quot; <strong>Explanation:</strong> &quot;aba&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cbbd&quot; <strong>Output:</strong> &quot;bb&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consist of only digits and English letters.</li> </ul>
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; if (s[i] === s[j]) { f[i][j] = f[i + 1][j - 1]; if (f[i][j] && mx < j - i + 1) { mx = j - i + 1; k = i; } } } } return s.slice(k, k + mx); }
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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(char)); idx[i] = 0; } int i = 0, k = -1; for (int p = 0; p < len; ++p) { g[i][idx[i]++] = s[p]; if (i == 0 || i == numRows - 1) { k = -k; } i += k; } char* ans = (char*) malloc((len + 1) * sizeof(char)); int pos = 0; for (int r = 0; r < numRows; ++r) { for (int j = 0; j < idx[r]; ++j) { ans[pos++] = g[r][j]; } free(g[r]); } ans[pos] = '\0'; free(g); free(idx); return ans; }
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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; } i += k; } string ans; for (auto& t : g) { ans += t; } return ans; } };
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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(); } int i = 0, k = -1; foreach (char c in s.ToCharArray()) { g[i].Append(c); if (i == 0 || i == numRows - 1) { k = -k; } i += k; } StringBuilder ans = new StringBuilder(); foreach (StringBuilder t in g) { ans.Append(t); } return ans.ToString(); } }
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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].append(c); if (i == 0 || i == numRows - 1) { k = -k; } i += k; } return String.join("", g); } }
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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 || i === numRows - 1) { k = -k; } i += k; } return g.flat().join(''); };
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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); for ($j = 0; $j < $length; $j++) { $c = $s[$j]; $g[$i] .= $c; if ($i == 0 || $i == $numRows - 1) { $k = -$k; } $i += $k; } return implode("", $g); } }
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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 return ''.join(chain(*g))
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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].push(c); if i == 0 || i == num_rows - 1 { k = -k; } i = (i as isize + k) as usize; } g.concat() } }
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;</code></p> <p>Write the code that will take a string and make this conversion given a number of rows:</p> <pre> string convert(string s, int numRows); </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3 <strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4 <strong>Output:</strong> &quot;PINALSIGYAHRPI&quot; <strong>Explanation:</strong> P I N A L S I G Y A H R P I </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;A&quot;, numRows = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li> <li><code>1 &lt;= numRows &lt;= 1000</code></li> </ul>
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; } i += k; } return g.flat().join(''); }
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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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); } 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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 ($isNegative) { $reversed *= -1; } if ($reversed < -pow(2, 31) || $reversed > pow(2, 31) - 1) { return 0; } return $reversed; } }
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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 x = (x - y) // 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 not allow you to store 64-bit integers (signed or unsigned).</strong></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> x = 123 <strong>Output:</strong> 321 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -123 <strong>Output:</strong> -321 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 120 <strong>Output:</strong> 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li> </ul>
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 }), Err(_) => 0, } } }
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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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 == INT_MAX / 10 && digit > INT_MAX % 10)) { return sign == 1 ? INT_MAX : INT_MIN; } res = res * 10 + digit; i++; } return res * sign; }
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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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 (i < n && isdigit(s[i])) { int digit = s[i] - '0'; if (res > INT_MAX / 10 || (res == INT_MAX / 10 && digit > INT_MAX % 10)) { return sign == 1 ? INT_MAX : INT_MIN; } res = res * 10 + digit; ++i; } return res * sign; } };
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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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.Length) { if (str[i] == '+') { ++i; } else if (str[i] == '-') { minus = true; ++i; } } while (i < str.Length && char.IsDigit(str[i])) { result = result * 10 + str[i] - '0'; if (result > int.MaxValue) { break; } ++i; } if (minus) result = -result; if (result > int.MaxValue) { result = int.MaxValue; } if (result < int.MinValue) { result = int.MinValue; } return (int)result; } }
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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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 } } if num > math.MaxInt32 { if sign == -1 { return math.MinInt32 } return math.MaxInt32 } return sign * num }
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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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) == '-') sign = -1; if (s.charAt(i) == '-' || s.charAt(i) == '+') ++i; int res = 0, flag = Integer.MAX_VALUE / 10; for (; i < n; ++i) { // 非数字,跳出循环体 if (s.charAt(i) < '0' || s.charAt(i) > '9') break; // 溢出判断 if (res > flag || (res == flag && s.charAt(i) > '7')) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; res = res * 10 + (s.charAt(i) - '0'); } return sign * res; } }
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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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 = str.charCodeAt(i) - 48; if (t > 9 || t < 0) break; if (ans > 2147483647 / 10 || ans > (2147483647 - t) / 10) { return isPositive ? 2147483647 : -2147483648; } else { ans = ans * 10 + t; } } return isPositive ? ans : -ans; };
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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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; } return intval($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>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li> <li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li> <li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li> </ol> <p>Return the integer as the final result.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;42&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <pre> The underlined characters are what is read in and the caret is the current reader position. Step 1: &quot;42&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in) ^ </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot; -042&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-42</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;<u> </u>-042&quot; (leading whitespace is read and ignored) ^ Step 2: &quot; <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative) ^ Step 3: &quot; -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result) ^ </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1337c0d3&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1337</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0-1&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <pre> Step 1: &quot;0-1&quot; (no characters read because there is no leading whitespace) ^ Step 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;) ^ Step 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit) ^ </pre> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;words and 987&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Reading stops at the first non-digit character &#39;w&#39;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 200</code></li> <li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li> </ul>
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 if s[i] in ['-', '+']: i += 1 res, flag = 0, (2**31 - 1) // 10 while i < n: # 非数字,跳出循环体 if not s[i].isdigit(): break c = int(s[i]) # 溢出判断 if res > flag or (res == flag and c > 7): return 2**31 - 1 if sign > 0 else -(2**31) res = res * 10 + c i += 1 return sign * res
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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); } return $x == $y || $x == (int) ($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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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> <strong>Input:</strong> x = 121 <strong>Output:</strong> true <strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> x = -121 <strong>Output:</strong> false <strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> x = 10 <strong>Output:</strong> false <strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without converting the integer to a string?
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 of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
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] == pp[j] || pp[j] == '.') && dfs(i + 1, j))) { res = 1; } } else if (i < m && (ss[i] == pp[j] || pp[j] == '.') && dfs(i + 1, j + 1)) { res = 1; } f[i][j] = res; return res == 1; } bool isMatch(char* s, char* p) { ss = s; pp = p; m = strlen(s); n = strlen(p); memset(f, 0, sizeof(f)); return dfs(0, 0); }