id
int64 1
3.64k
| 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
|
---|---|---|---|---|---|---|
56 |
Merge Intervals
|
Medium
|
<p>Given an array of <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
|
Array; Sorting
|
Java
|
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
int st = intervals[0][0], ed = intervals[0][1];
List<int[]> ans = new ArrayList<>();
for (int i = 1; i < intervals.length; ++i) {
int s = intervals[i][0], e = intervals[i][1];
if (ed < s) {
ans.add(new int[] {st, ed});
st = s;
ed = e;
} else {
ed = Math.max(ed, e);
}
}
ans.add(new int[] {st, ed});
return ans.toArray(new int[ans.size()][]);
}
}
|
56 |
Merge Intervals
|
Medium
|
<p>Given an array of <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
|
Array; Sorting
|
JavaScript
|
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function (intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const result = [];
const n = intervals.length;
let i = 0;
while (i < n) {
const left = intervals[i][0];
let right = intervals[i][1];
while (true) {
i++;
if (i < n && right >= intervals[i][0]) {
right = Math.max(right, intervals[i][1]);
} else {
result.push([left, right]);
break;
}
}
}
return result;
};
|
56 |
Merge Intervals
|
Medium
|
<p>Given an array of <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
|
Array; Sorting
|
Kotlin
|
class Solution {
fun merge(intervals: Array<IntArray>): Array<IntArray> {
intervals.sortBy { it[0] }
val result = mutableListOf<IntArray>()
val n = intervals.size
var i = 0
while (i < n) {
val left = intervals[i][0]
var right = intervals[i][1]
while (true) {
i++
if (i < n && right >= intervals[i][0]) {
right = maxOf(right, intervals[i][1])
} else {
result.add(intArrayOf(left, right))
break
}
}
}
return result.toTypedArray()
}
}
|
56 |
Merge Intervals
|
Medium
|
<p>Given an array of <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
|
Array; Sorting
|
Python
|
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
ans = []
st, ed = intervals[0]
for s, e in intervals[1:]:
if ed < s:
ans.append([st, ed])
st, ed = s, e
else:
ed = max(ed, e)
ans.append([st, ed])
return ans
|
56 |
Merge Intervals
|
Medium
|
<p>Given an array of <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
|
Array; Sorting
|
Rust
|
impl Solution {
pub fn merge(mut intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
intervals.sort_unstable_by(|a, b| a[0].cmp(&b[0]));
let n = intervals.len();
let mut res = vec![];
let mut i = 0;
while i < n {
let l = intervals[i][0];
let mut r = intervals[i][1];
i += 1;
while i < n && r >= intervals[i][0] {
r = r.max(intervals[i][1]);
i += 1;
}
res.push(vec![l, r]);
}
res
}
}
|
56 |
Merge Intervals
|
Medium
|
<p>Given an array of <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
|
Array; Sorting
|
TypeScript
|
function merge(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const ans: number[][] = [];
let [st, ed] = intervals[0];
for (const [s, e] of intervals.slice(1)) {
if (ed < s) {
ans.push([st, ed]);
[st, ed] = [s, e];
} else {
ed = Math.max(ed, e);
}
}
ans.push([st, ed]);
return ans;
}
|
57 |
Insert Interval
|
Medium
|
<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>
<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>
<p>Return <code>intervals</code><em> after the insertion</em>.</p>
<p><strong>Note</strong> that you don't need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]
<strong>Output:</strong> [[1,5],[6,9]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
<strong>Output:</strong> [[1,2],[3,10],[12,16]]
<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>
<li><code>newInterval.length == 2</code></li>
<li><code>0 <= start <= end <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
intervals.emplace_back(newInterval);
return merge(intervals);
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> ans;
ans.emplace_back(intervals[0]);
for (int i = 1; i < intervals.size(); ++i) {
if (ans.back()[1] < intervals[i][0]) {
ans.emplace_back(intervals[i]);
} else {
ans.back()[1] = max(ans.back()[1], intervals[i][1]);
}
}
return ans;
}
};
|
57 |
Insert Interval
|
Medium
|
<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>
<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>
<p>Return <code>intervals</code><em> after the insertion</em>.</p>
<p><strong>Note</strong> that you don't need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]
<strong>Output:</strong> [[1,5],[6,9]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
<strong>Output:</strong> [[1,2],[3,10],[12,16]]
<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>
<li><code>newInterval.length == 2</code></li>
<li><code>0 <= start <= end <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
C#
|
public class Solution {
public int[][] Insert(int[][] intervals, int[] newInterval) {
int[][] newIntervals = new int[intervals.Length + 1][];
for (int i = 0; i < intervals.Length; ++i) {
newIntervals[i] = intervals[i];
}
newIntervals[intervals.Length] = newInterval;
return Merge(newIntervals);
}
public int[][] Merge(int[][] intervals) {
intervals = intervals.OrderBy(a => a[0]).ToArray();
var ans = new List<int[]>();
ans.Add(intervals[0]);
for (int i = 1; i < intervals.Length; ++i) {
if (ans[ans.Count - 1][1] < intervals[i][0]) {
ans.Add(intervals[i]);
} else {
ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]);
}
}
return ans.ToArray();
}
}
|
57 |
Insert Interval
|
Medium
|
<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>
<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>
<p>Return <code>intervals</code><em> after the insertion</em>.</p>
<p><strong>Note</strong> that you don't need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]
<strong>Output:</strong> [[1,5],[6,9]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
<strong>Output:</strong> [[1,2],[3,10],[12,16]]
<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>
<li><code>newInterval.length == 2</code></li>
<li><code>0 <= start <= end <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Go
|
func insert(intervals [][]int, newInterval []int) [][]int {
merge := func(intervals [][]int) (ans [][]int) {
sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
ans = append(ans, intervals[0])
for _, e := range intervals[1:] {
if ans[len(ans)-1][1] < e[0] {
ans = append(ans, e)
} else {
ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1])
}
}
return
}
intervals = append(intervals, newInterval)
return merge(intervals)
}
|
57 |
Insert Interval
|
Medium
|
<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>
<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>
<p>Return <code>intervals</code><em> after the insertion</em>.</p>
<p><strong>Note</strong> that you don't need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]
<strong>Output:</strong> [[1,5],[6,9]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
<strong>Output:</strong> [[1,2],[3,10],[12,16]]
<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>
<li><code>newInterval.length == 2</code></li>
<li><code>0 <= start <= end <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
int[][] newIntervals = new int[intervals.length + 1][2];
for (int i = 0; i < intervals.length; ++i) {
newIntervals[i] = intervals[i];
}
newIntervals[intervals.length] = newInterval;
return merge(newIntervals);
}
private int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
List<int[]> ans = new ArrayList<>();
ans.add(intervals[0]);
for (int i = 1; i < intervals.length; ++i) {
int s = intervals[i][0], e = intervals[i][1];
if (ans.get(ans.size() - 1)[1] < s) {
ans.add(intervals[i]);
} else {
ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e);
}
}
return ans.toArray(new int[ans.size()][]);
}
}
|
57 |
Insert Interval
|
Medium
|
<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>
<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>
<p>Return <code>intervals</code><em> after the insertion</em>.</p>
<p><strong>Note</strong> that you don't need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]
<strong>Output:</strong> [[1,5],[6,9]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
<strong>Output:</strong> [[1,2],[3,10],[12,16]]
<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>
<li><code>newInterval.length == 2</code></li>
<li><code>0 <= start <= end <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Python
|
class Solution:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
def merge(intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
ans = [intervals[0]]
for s, e in intervals[1:]:
if ans[-1][1] < s:
ans.append([s, e])
else:
ans[-1][1] = max(ans[-1][1], e)
return ans
intervals.append(newInterval)
return merge(intervals)
|
57 |
Insert Interval
|
Medium
|
<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>
<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>
<p>Return <code>intervals</code><em> after the insertion</em>.</p>
<p><strong>Note</strong> that you don't need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]
<strong>Output:</strong> [[1,5],[6,9]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
<strong>Output:</strong> [[1,2],[3,10],[12,16]]
<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>
<li><code>newInterval.length == 2</code></li>
<li><code>0 <= start <= end <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Rust
|
impl Solution {
pub fn insert(intervals: Vec<Vec<i32>>, new_interval: Vec<i32>) -> Vec<Vec<i32>> {
let mut merged_intervals = intervals.clone();
merged_intervals.push(vec![new_interval[0], new_interval[1]]);
// sort by elem[0]
merged_intervals.sort_by_key(|elem| elem[0]);
// merge interval
let mut result = vec![];
for interval in merged_intervals {
if result.is_empty() {
result.push(interval);
continue;
}
let last_elem = result.last_mut().unwrap();
if interval[0] > last_elem[1] {
result.push(interval);
} else {
last_elem[1] = last_elem[1].max(interval[1]);
}
}
result
}
}
|
57 |
Insert Interval
|
Medium
|
<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>
<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>
<p>Return <code>intervals</code><em> after the insertion</em>.</p>
<p><strong>Note</strong> that you don't need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]
<strong>Output:</strong> [[1,5],[6,9]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
<strong>Output:</strong> [[1,2],[3,10],[12,16]]
<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>
<li><code>newInterval.length == 2</code></li>
<li><code>0 <= start <= end <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
TypeScript
|
function insert(intervals: number[][], newInterval: number[]): number[][] {
const merge = (intervals: number[][]): number[][] => {
intervals.sort((a, b) => a[0] - b[0]);
const ans: number[][] = [intervals[0]];
for (let i = 1; i < intervals.length; ++i) {
if (ans.at(-1)[1] < intervals[i][0]) {
ans.push(intervals[i]);
} else {
ans.at(-1)[1] = Math.max(ans.at(-1)[1], intervals[i][1]);
}
}
return ans;
};
intervals.push(newInterval);
return merge(intervals);
}
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
int lengthOfLastWord(string s) {
int i = s.size() - 1;
while (~i && s[i] == ' ') {
--i;
}
int j = i;
while (~j && s[j] != ' ') {
--j;
}
return i - j;
}
};
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
C#
|
public class Solution {
public int LengthOfLastWord(string s) {
int i = s.Length - 1;
while (i >= 0 && s[i] == ' ') {
--i;
}
int j = i;
while (j >= 0 && s[j] != ' ') {
--j;
}
return i - j;
}
}
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
Go
|
func lengthOfLastWord(s string) int {
i := len(s) - 1
for i >= 0 && s[i] == ' ' {
i--
}
j := i
for j >= 0 && s[j] != ' ' {
j--
}
return i - j
}
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
Java
|
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') {
--i;
}
int j = i;
while (j >= 0 && s.charAt(j) != ' ') {
--j;
}
return i - j;
}
}
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
JavaScript
|
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function (s) {
let i = s.length - 1;
while (i >= 0 && s[i] === ' ') {
--i;
}
let j = i;
while (j >= 0 && s[j] !== ' ') {
--j;
}
return i - j;
};
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
PHP
|
class Solution {
/**
* @param String $s
* @return Integer
*/
function lengthOfLastWord($s) {
$count = 0;
while ($s[strlen($s) - 1] == ' ') {
$s = substr($s, 0, -1);
}
while (strlen($s) != 0 && $s[strlen($s) - 1] != ' ') {
$count++;
$s = substr($s, 0, -1);
}
return $count;
}
}
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
Python
|
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
j = i
while j >= 0 and s[j] != ' ':
j -= 1
return i - j
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
Rust
|
impl Solution {
pub fn length_of_last_word(s: String) -> i32 {
let s = s.trim_end();
let n = s.len();
for (i, c) in s.char_indices().rev() {
if c == ' ' {
return (n - i - 1) as i32;
}
}
n as i32
}
}
|
58 |
Length of Last Word
|
Easy
|
<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>
<p>A <strong>word</strong> is a maximal <span data-keyword="substring-nonempty">substring</span> consisting of non-space characters only.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "Hello World"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = " fly me to the moon "
<strong>Output:</strong> 4
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
<li>There will be at least one word in <code>s</code>.</li>
</ul>
|
String
|
TypeScript
|
function lengthOfLastWord(s: string): number {
let i = s.length - 1;
while (i >= 0 && s[i] === ' ') {
--i;
}
let j = i;
while (j >= 0 && s[j] !== ' ') {
--j;
}
return i - j;
}
|
59 |
Spiral Matrix II
|
Medium
|
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 20</code></li>
</ul>
|
Array; Matrix; Simulation
|
C++
|
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
const int dirs[5] = {0, 1, 0, -1, 0};
int i = 0, j = 0, k = 0;
for (int v = 1; v <= n * n; ++v) {
ans[i][j] = v;
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= n || y < 0 || y >= n || ans[x][y] != 0) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
return ans;
}
};
|
59 |
Spiral Matrix II
|
Medium
|
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 20</code></li>
</ul>
|
Array; Matrix; Simulation
|
Go
|
func generateMatrix(n int) [][]int {
ans := make([][]int, n)
for i := range ans {
ans[i] = make([]int, n)
}
dirs := [5]int{0, 1, 0, -1, 0}
i, j, k := 0, 0, 0
for v := 1; v <= n*n; v++ {
ans[i][j] = v
x, y := i+dirs[k], j+dirs[k+1]
if x < 0 || x >= n || y < 0 || y >= n || ans[x][y] != 0 {
k = (k + 1) % 4
}
i += dirs[k]
j += dirs[k+1]
}
return ans
}
|
59 |
Spiral Matrix II
|
Medium
|
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 20</code></li>
</ul>
|
Array; Matrix; Simulation
|
Java
|
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
final int[] dirs = {0, 1, 0, -1, 0};
int i = 0, j = 0, k = 0;
for (int v = 1; v <= n * n; ++v) {
ans[i][j] = v;
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= n || y < 0 || y >= n || ans[x][y] != 0) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
return ans;
}
}
|
59 |
Spiral Matrix II
|
Medium
|
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 20</code></li>
</ul>
|
Array; Matrix; Simulation
|
JavaScript
|
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
const ans = Array.from({ length: n }, () => Array(n).fill(0));
const dirs = [0, 1, 0, -1, 0];
let [i, j, k] = [0, 0, 0];
for (let v = 1; v <= n * n; v++) {
ans[i][j] = v;
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x < 0 || x >= n || y < 0 || y >= n || ans[x][y] !== 0) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
return ans;
};
|
59 |
Spiral Matrix II
|
Medium
|
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 20</code></li>
</ul>
|
Array; Matrix; Simulation
|
Python
|
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
ans = [[0] * n for _ in range(n)]
dirs = (0, 1, 0, -1, 0)
i = j = k = 0
for v in range(1, n * n + 1):
ans[i][j] = v
x, y = i + dirs[k], j + dirs[k + 1]
if x < 0 or x >= n or y < 0 or y >= n or ans[x][y]:
k = (k + 1) % 4
i, j = i + dirs[k], j + dirs[k + 1]
return ans
|
59 |
Spiral Matrix II
|
Medium
|
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 20</code></li>
</ul>
|
Array; Matrix; Simulation
|
Rust
|
impl Solution {
pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
let mut ans = vec![vec![0; n as usize]; n as usize];
let dirs = [0, 1, 0, -1, 0];
let (mut i, mut j, mut k) = (0, 0, 0);
for v in 1..=n * n {
ans[i as usize][j as usize] = v;
let (x, y) = (i + dirs[k], j + dirs[k + 1]);
if x < 0 || x >= n || y < 0 || y >= n || ans[x as usize][y as usize] != 0 {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
ans
}
}
|
59 |
Spiral Matrix II
|
Medium
|
<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 20</code></li>
</ul>
|
Array; Matrix; Simulation
|
TypeScript
|
function generateMatrix(n: number): number[][] {
const ans: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
const dirs = [0, 1, 0, -1, 0];
let [i, j, k] = [0, 0, 0];
for (let v = 1; v <= n * n; v++) {
ans[i][j] = v;
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x < 0 || x >= n || y < 0 || y >= n || ans[x][y] !== 0) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
return ans;
}
|
60 |
Permutation Sequence
|
Hard
|
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
|
Recursion; Math
|
C++
|
class Solution {
public:
string getPermutation(int n, int k) {
string ans;
bitset<10> vis;
for (int i = 0; i < n; ++i) {
int fact = 1;
for (int j = 1; j < n - i; ++j) fact *= j;
for (int j = 1; j <= n; ++j) {
if (vis[j]) continue;
if (k > fact)
k -= fact;
else {
ans += to_string(j);
vis[j] = 1;
break;
}
}
}
return ans;
}
};
|
60 |
Permutation Sequence
|
Hard
|
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
|
Recursion; Math
|
C#
|
public class Solution {
public string GetPermutation(int n, int k) {
var ans = new StringBuilder();
int vis = 0;
for (int i = 0; i < n; ++i) {
int fact = 1;
for (int j = 1; j < n - i; ++j) {
fact *= j;
}
for (int j = 1; j <= n; ++j) {
if (((vis >> j) & 1) == 0) {
if (k > fact) {
k -= fact;
} else {
ans.Append(j);
vis |= 1 << j;
break;
}
}
}
}
return ans.ToString();
}
}
|
60 |
Permutation Sequence
|
Hard
|
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
|
Recursion; Math
|
Go
|
func getPermutation(n int, k int) string {
ans := make([]byte, n)
vis := make([]bool, n+1)
for i := 0; i < n; i++ {
fact := 1
for j := 1; j < n-i; j++ {
fact *= j
}
for j := 1; j <= n; j++ {
if !vis[j] {
if k > fact {
k -= fact
} else {
ans[i] = byte('0' + j)
vis[j] = true
break
}
}
}
}
return string(ans)
}
|
60 |
Permutation Sequence
|
Hard
|
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
|
Recursion; Math
|
Java
|
class Solution {
public String getPermutation(int n, int k) {
StringBuilder ans = new StringBuilder();
boolean[] vis = new boolean[n + 1];
for (int i = 0; i < n; ++i) {
int fact = 1;
for (int j = 1; j < n - i; ++j) {
fact *= j;
}
for (int j = 1; j <= n; ++j) {
if (!vis[j]) {
if (k > fact) {
k -= fact;
} else {
ans.append(j);
vis[j] = true;
break;
}
}
}
}
return ans.toString();
}
}
|
60 |
Permutation Sequence
|
Hard
|
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
|
Recursion; Math
|
Python
|
class Solution:
def getPermutation(self, n: int, k: int) -> str:
ans = []
vis = [False] * (n + 1)
for i in range(n):
fact = 1
for j in range(1, n - i):
fact *= j
for j in range(1, n + 1):
if not vis[j]:
if k > fact:
k -= fact
else:
ans.append(str(j))
vis[j] = True
break
return ''.join(ans)
|
60 |
Permutation Sequence
|
Hard
|
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
|
Recursion; Math
|
Rust
|
impl Solution {
pub fn get_permutation(n: i32, k: i32) -> String {
let mut k = k;
let mut ans = String::new();
let mut fact = vec![1; n as usize];
for i in 1..n as usize {
fact[i] = fact[i - 1] * (i as i32);
}
let mut vis = vec![false; n as usize + 1];
for i in 0..n as usize {
let cnt = fact[(n as usize) - i - 1];
for j in 1..=n {
if vis[j as usize] {
continue;
}
if k > cnt {
k -= cnt;
} else {
ans.push_str(&j.to_string());
vis[j as usize] = true;
break;
}
}
}
ans
}
}
|
60 |
Permutation Sequence
|
Hard
|
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
|
Recursion; Math
|
TypeScript
|
function getPermutation(n: number, k: number): string {
let ans = '';
const vis = Array.from({ length: n + 1 }, () => false);
for (let i = 0; i < n; i++) {
let fact = 1;
for (let j = 1; j < n - i; j++) {
fact *= j;
}
for (let j = 1; j <= n; j++) {
if (!vis[j]) {
if (k > fact) {
k -= fact;
} else {
ans += j;
vis[j] = true;
break;
}
}
}
}
return ans;
}
|
61 |
Rotate List
|
Medium
|
<p>Given the <code>head</code> of a linked list, rotate the list to the right by <code>k</code> places.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/rotate1.jpg" style="width: 450px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [4,5,1,2,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/roate2.jpg" style="width: 305px; height: 350px;" />
<pre>
<strong>Input:</strong> head = [0,1,2], k = 4
<strong>Output:</strong> [2,0,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li>
</ul>
|
Linked List; Two Pointers
|
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* rotateRight(ListNode* head, int k) {
if (!head || !head->next) {
return head;
}
ListNode* cur = head;
int n = 0;
while (cur) {
++n;
cur = cur->next;
}
k %= n;
if (k == 0) {
return head;
}
ListNode* fast = head;
ListNode* slow = head;
while (k--) {
fast = fast->next;
}
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
ListNode* ans = slow->next;
slow->next = nullptr;
fast->next = head;
return ans;
}
};
|
61 |
Rotate List
|
Medium
|
<p>Given the <code>head</code> of a linked list, rotate the list to the right by <code>k</code> places.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/rotate1.jpg" style="width: 450px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [4,5,1,2,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/roate2.jpg" style="width: 305px; height: 350px;" />
<pre>
<strong>Input:</strong> head = [0,1,2], k = 4
<strong>Output:</strong> [2,0,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li>
</ul>
|
Linked List; Two Pointers
|
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 RotateRight(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
var cur = head;
int n = 0;
while (cur != null) {
cur = cur.next;
++n;
}
k %= n;
if (k == 0) {
return head;
}
var fast = head;
var slow = head;
while (k-- > 0) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
var ans = slow.next;
slow.next = null;
fast.next = head;
return ans;
}
}
|
61 |
Rotate List
|
Medium
|
<p>Given the <code>head</code> of a linked list, rotate the list to the right by <code>k</code> places.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/rotate1.jpg" style="width: 450px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [4,5,1,2,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/roate2.jpg" style="width: 305px; height: 350px;" />
<pre>
<strong>Input:</strong> head = [0,1,2], k = 4
<strong>Output:</strong> [2,0,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li>
</ul>
|
Linked List; Two Pointers
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil || head.Next == nil {
return head
}
cur := head
n := 0
for cur != nil {
cur = cur.Next
n++
}
k %= n
if k == 0 {
return head
}
fast, slow := head, head
for i := 0; i < k; i++ {
fast = fast.Next
}
for fast.Next != nil {
fast = fast.Next
slow = slow.Next
}
ans := slow.Next
slow.Next = nil
fast.Next = head
return ans
}
|
61 |
Rotate List
|
Medium
|
<p>Given the <code>head</code> of a linked list, rotate the list to the right by <code>k</code> places.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/rotate1.jpg" style="width: 450px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [4,5,1,2,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/roate2.jpg" style="width: 305px; height: 350px;" />
<pre>
<strong>Input:</strong> head = [0,1,2], k = 4
<strong>Output:</strong> [2,0,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li>
</ul>
|
Linked List; Two Pointers
|
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 rotateRight(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
int n = 0;
for (; cur != null; cur = cur.next) {
n++;
}
k %= n;
if (k == 0) {
return head;
}
ListNode fast = head;
ListNode slow = head;
while (k-- > 0) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode ans = slow.next;
slow.next = null;
fast.next = head;
return ans;
}
}
|
61 |
Rotate List
|
Medium
|
<p>Given the <code>head</code> of a linked list, rotate the list to the right by <code>k</code> places.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/rotate1.jpg" style="width: 450px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [4,5,1,2,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/roate2.jpg" style="width: 305px; height: 350px;" />
<pre>
<strong>Input:</strong> head = [0,1,2], k = 4
<strong>Output:</strong> [2,0,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li>
</ul>
|
Linked List; Two Pointers
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if head is None or head.next is None:
return head
cur, n = head, 0
while cur:
n += 1
cur = cur.next
k %= n
if k == 0:
return head
fast = slow = head
for _ in range(k):
fast = fast.next
while fast.next:
fast, slow = fast.next, slow.next
ans = slow.next
slow.next = None
fast.next = head
return ans
|
61 |
Rotate List
|
Medium
|
<p>Given the <code>head</code> of a linked list, rotate the list to the right by <code>k</code> places.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/rotate1.jpg" style="width: 450px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [4,5,1,2,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/roate2.jpg" style="width: 305px; height: 350px;" />
<pre>
<strong>Input:</strong> head = [0,1,2], k = 4
<strong>Output:</strong> [2,0,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li>
</ul>
|
Linked List; Two Pointers
|
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 rotate_right(mut head: Option<Box<ListNode>>, mut k: i32) -> Option<Box<ListNode>> {
if head.is_none() || k == 0 {
return head;
}
let n = {
let mut cur = &head;
let mut res = 0;
while cur.is_some() {
cur = &cur.as_ref().unwrap().next;
res += 1;
}
res
};
k = k % n;
if k == 0 {
return head;
}
let mut cur = &mut head;
for _ in 0..n - k - 1 {
cur = &mut cur.as_mut().unwrap().next;
}
let mut res = cur.as_mut().unwrap().next.take();
cur = &mut res;
while cur.is_some() {
cur = &mut cur.as_mut().unwrap().next;
}
*cur = head.take();
res
}
}
|
61 |
Rotate List
|
Medium
|
<p>Given the <code>head</code> of a linked list, rotate the list to the right by <code>k</code> places.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/rotate1.jpg" style="width: 450px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [4,5,1,2,3]
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0061.Rotate%20List/images/roate2.jpg" style="width: 305px; height: 350px;" />
<pre>
<strong>Input:</strong> head = [0,1,2], k = 4
<strong>Output:</strong> [2,0,1]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li><code>0 <= k <= 2 * 10<sup>9</sup></code></li>
</ul>
|
Linked List; Two Pointers
|
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 rotateRight(head: ListNode | null, k: number): ListNode | null {
if (!head || !head.next) {
return head;
}
let cur = head;
let n = 0;
while (cur) {
cur = cur.next;
++n;
}
k %= n;
if (k === 0) {
return head;
}
let fast = head;
let slow = head;
while (k--) {
fast = fast.next;
}
while (fast.next) {
fast = fast.next;
slow = slow.next;
}
const ans = slow.next;
slow.next = null;
fast.next = head;
return ans;
}
|
62 |
Unique Paths
|
Medium
|
<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0062.Unique%20Paths/images/robot_maze.png" style="width: 400px; height: 183px;" />
<pre>
<strong>Input:</strong> m = 3, n = 7
<strong>Output:</strong> 28
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 3, n = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
C++
|
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> f(m, vector<int>(n));
f[0][0] = 1;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i) {
f[i][j] += f[i - 1][j];
}
if (j) {
f[i][j] += f[i][j - 1];
}
}
}
return f[m - 1][n - 1];
}
};
|
62 |
Unique Paths
|
Medium
|
<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0062.Unique%20Paths/images/robot_maze.png" style="width: 400px; height: 183px;" />
<pre>
<strong>Input:</strong> m = 3, n = 7
<strong>Output:</strong> 28
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 3, n = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Go
|
func uniquePaths(m int, n int) int {
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
f[0][0] = 1
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if i > 0 {
f[i][j] += f[i-1][j]
}
if j > 0 {
f[i][j] += f[i][j-1]
}
}
}
return f[m-1][n-1]
}
|
62 |
Unique Paths
|
Medium
|
<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0062.Unique%20Paths/images/robot_maze.png" style="width: 400px; height: 183px;" />
<pre>
<strong>Input:</strong> m = 3, n = 7
<strong>Output:</strong> 28
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 3, n = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Java
|
class Solution {
public int uniquePaths(int m, int n) {
var f = new int[m][n];
f[0][0] = 1;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i > 0) {
f[i][j] += f[i - 1][j];
}
if (j > 0) {
f[i][j] += f[i][j - 1];
}
}
}
return f[m - 1][n - 1];
}
}
|
62 |
Unique Paths
|
Medium
|
<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0062.Unique%20Paths/images/robot_maze.png" style="width: 400px; height: 183px;" />
<pre>
<strong>Input:</strong> m = 3, n = 7
<strong>Output:</strong> 28
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 3, n = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
JavaScript
|
/**
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function (m, n) {
const f = Array(m)
.fill(0)
.map(() => Array(n).fill(0));
f[0][0] = 1;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (i > 0) {
f[i][j] += f[i - 1][j];
}
if (j > 0) {
f[i][j] += f[i][j - 1];
}
}
}
return f[m - 1][n - 1];
};
|
62 |
Unique Paths
|
Medium
|
<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0062.Unique%20Paths/images/robot_maze.png" style="width: 400px; height: 183px;" />
<pre>
<strong>Input:</strong> m = 3, n = 7
<strong>Output:</strong> 28
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 3, n = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Python
|
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
f = [[0] * n for _ in range(m)]
f[0][0] = 1
for i in range(m):
for j in range(n):
if i:
f[i][j] += f[i - 1][j]
if j:
f[i][j] += f[i][j - 1]
return f[-1][-1]
|
62 |
Unique Paths
|
Medium
|
<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0062.Unique%20Paths/images/robot_maze.png" style="width: 400px; height: 183px;" />
<pre>
<strong>Input:</strong> m = 3, n = 7
<strong>Output:</strong> 28
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 3, n = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Rust
|
impl Solution {
pub fn unique_paths(m: i32, n: i32) -> i32 {
let (m, n) = (m as usize, n as usize);
let mut f = vec![1; n];
for i in 1..m {
for j in 1..n {
f[j] += f[j - 1];
}
}
f[n - 1]
}
}
|
62 |
Unique Paths
|
Medium
|
<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0062.Unique%20Paths/images/robot_maze.png" style="width: 400px; height: 183px;" />
<pre>
<strong>Input:</strong> m = 3, n = 7
<strong>Output:</strong> 28
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> m = 3, n = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
TypeScript
|
function uniquePaths(m: number, n: number): number {
const f: number[][] = Array(m)
.fill(0)
.map(() => Array(n).fill(0));
f[0][0] = 1;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (i > 0) {
f[i][j] += f[i - 1][j];
}
if (j > 0) {
f[i][j] += f[i][j - 1];
}
}
}
return f[m - 1][n - 1];
}
|
63 |
Unique Paths II
|
Medium
|
<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>
<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == obstacleGrid.length</code></li>
<li><code>n == obstacleGrid[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
C++
|
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<int>> f(m, vector<int>(n, -1));
auto dfs = [&](this auto&& dfs, int i, int j) {
if (i >= m || j >= n || obstacleGrid[i][j]) {
return 0;
}
if (i == m - 1 && j == n - 1) {
return 1;
}
if (f[i][j] == -1) {
f[i][j] = dfs(i + 1, j) + dfs(i, j + 1);
}
return f[i][j];
};
return dfs(0, 0);
}
};
|
63 |
Unique Paths II
|
Medium
|
<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>
<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == obstacleGrid.length</code></li>
<li><code>n == obstacleGrid[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Go
|
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m, n := len(obstacleGrid), len(obstacleGrid[0])
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if i >= m || j >= n || obstacleGrid[i][j] == 1 {
return 0
}
if i == m-1 && j == n-1 {
return 1
}
if f[i][j] == -1 {
f[i][j] = dfs(i+1, j) + dfs(i, j+1)
}
return f[i][j]
}
return dfs(0, 0)
}
|
63 |
Unique Paths II
|
Medium
|
<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>
<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == obstacleGrid.length</code></li>
<li><code>n == obstacleGrid[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Java
|
class Solution {
private Integer[][] f;
private int[][] obstacleGrid;
private int m;
private int n;
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
m = obstacleGrid.length;
n = obstacleGrid[0].length;
this.obstacleGrid = obstacleGrid;
f = new Integer[m][n];
return dfs(0, 0);
}
private int dfs(int i, int j) {
if (i >= m || j >= n || obstacleGrid[i][j] == 1) {
return 0;
}
if (i == m - 1 && j == n - 1) {
return 1;
}
if (f[i][j] == null) {
f[i][j] = dfs(i + 1, j) + dfs(i, j + 1);
}
return f[i][j];
}
}
|
63 |
Unique Paths II
|
Medium
|
<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>
<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == obstacleGrid.length</code></li>
<li><code>n == obstacleGrid[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
JavaScript
|
/**
* @param {number[][]} obstacleGrid
* @return {number}
*/
var uniquePathsWithObstacles = function (obstacleGrid) {
const m = obstacleGrid.length;
const n = obstacleGrid[0].length;
const f = Array.from({ length: m }, () => Array(n).fill(-1));
const dfs = (i, j) => {
if (i >= m || j >= n || obstacleGrid[i][j] === 1) {
return 0;
}
if (i === m - 1 && j === n - 1) {
return 1;
}
if (f[i][j] === -1) {
f[i][j] = dfs(i + 1, j) + dfs(i, j + 1);
}
return f[i][j];
};
return dfs(0, 0);
};
|
63 |
Unique Paths II
|
Medium
|
<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>
<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == obstacleGrid.length</code></li>
<li><code>n == obstacleGrid[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Python
|
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= m or j >= n or obstacleGrid[i][j]:
return 0
if i == m - 1 and j == n - 1:
return 1
return dfs(i + 1, j) + dfs(i, j + 1)
m, n = len(obstacleGrid), len(obstacleGrid[0])
return dfs(0, 0)
|
63 |
Unique Paths II
|
Medium
|
<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>
<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == obstacleGrid.length</code></li>
<li><code>n == obstacleGrid[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Rust
|
impl Solution {
pub fn unique_paths_with_obstacles(obstacle_grid: Vec<Vec<i32>>) -> i32 {
let m = obstacle_grid.len();
let n = obstacle_grid[0].len();
let mut f = vec![vec![-1; n]; m];
Self::dfs(0, 0, &obstacle_grid, &mut f)
}
fn dfs(i: usize, j: usize, obstacle_grid: &Vec<Vec<i32>>, f: &mut Vec<Vec<i32>>) -> i32 {
let m = obstacle_grid.len();
let n = obstacle_grid[0].len();
if i >= m || j >= n || obstacle_grid[i][j] == 1 {
return 0;
}
if i == m - 1 && j == n - 1 {
return 1;
}
if f[i][j] != -1 {
return f[i][j];
}
let down = Self::dfs(i + 1, j, obstacle_grid, f);
let right = Self::dfs(i, j + 1, obstacle_grid, f);
f[i][j] = down + right;
f[i][j]
}
}
|
63 |
Unique Paths II
|
Medium
|
<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>
<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>
<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0063.Unique%20Paths%20II/images/robot2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == obstacleGrid.length</code></li>
<li><code>n == obstacleGrid[i].length</code></li>
<li><code>1 <= m, n <= 100</code></li>
<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Dynamic Programming; Matrix
|
TypeScript
|
function uniquePathsWithObstacles(obstacleGrid: number[][]): number {
const m = obstacleGrid.length;
const n = obstacleGrid[0].length;
const f: number[][] = Array.from({ length: m }, () => Array(n).fill(-1));
const dfs = (i: number, j: number): number => {
if (i >= m || j >= n || obstacleGrid[i][j] === 1) {
return 0;
}
if (i === m - 1 && j === n - 1) {
return 1;
}
if (f[i][j] === -1) {
f[i][j] = dfs(i + 1, j) + dfs(i, j + 1);
}
return f[i][j];
};
return dfs(0, 0);
}
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
C++
|
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int f[m][n];
f[0][0] = grid[0][0];
for (int i = 1; i < m; ++i) {
f[i][0] = f[i - 1][0] + grid[i][0];
}
for (int j = 1; j < n; ++j) {
f[0][j] = f[0][j - 1] + grid[0][j];
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
}
}
return f[m - 1][n - 1];
}
};
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
C#
|
public class Solution {
public int MinPathSum(int[][] grid) {
int m = grid.Length, n = grid[0].Length;
int[,] f = new int[m, n];
f[0, 0] = grid[0][0];
for (int i = 1; i < m; ++i) {
f[i, 0] = f[i - 1, 0] + grid[i][0];
}
for (int j = 1; j < n; ++j) {
f[0, j] = f[0, j - 1] + grid[0][j];
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
f[i, j] = Math.Min(f[i - 1, j], f[i, j - 1]) + grid[i][j];
}
}
return f[m - 1, n - 1];
}
}
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Go
|
func minPathSum(grid [][]int) int {
m, n := len(grid), len(grid[0])
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
f[0][0] = grid[0][0]
for i := 1; i < m; i++ {
f[i][0] = f[i-1][0] + grid[i][0]
}
for j := 1; j < n; j++ {
f[0][j] = f[0][j-1] + grid[0][j]
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
f[i][j] = min(f[i-1][j], f[i][j-1]) + grid[i][j]
}
}
return f[m-1][n-1]
}
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Java
|
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] f = new int[m][n];
f[0][0] = grid[0][0];
for (int i = 1; i < m; ++i) {
f[i][0] = f[i - 1][0] + grid[i][0];
}
for (int j = 1; j < n; ++j) {
f[0][j] = f[0][j - 1] + grid[0][j];
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
}
}
return f[m - 1][n - 1];
}
}
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
JavaScript
|
/**
* @param {number[][]} grid
* @return {number}
*/
var minPathSum = function (grid) {
const m = grid.length;
const n = grid[0].length;
const f = Array(m)
.fill(0)
.map(() => Array(n).fill(0));
f[0][0] = grid[0][0];
for (let i = 1; i < m; ++i) {
f[i][0] = f[i - 1][0] + grid[i][0];
}
for (let j = 1; j < n; ++j) {
f[0][j] = f[0][j - 1] + grid[0][j];
}
for (let i = 1; i < m; ++i) {
for (let j = 1; j < n; ++j) {
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
}
}
return f[m - 1][n - 1];
};
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Python
|
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[0] * n for _ in range(m)]
f[0][0] = grid[0][0]
for i in range(1, m):
f[i][0] = f[i - 1][0] + grid[i][0]
for j in range(1, n):
f[0][j] = f[0][j - 1] + grid[0][j]
for i in range(1, m):
for j in range(1, n):
f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j]
return f[-1][-1]
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Rust
|
impl Solution {
pub fn min_path_sum(mut grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
for i in 1..m {
grid[i][0] += grid[i - 1][0];
}
for i in 1..n {
grid[0][i] += grid[0][i - 1];
}
for i in 1..m {
for j in 1..n {
grid[i][j] += grid[i][j - 1].min(grid[i - 1][j]);
}
}
grid[m - 1][n - 1]
}
}
|
64 |
Minimum Path Sum
|
Medium
|
<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0064.Minimum%20Path%20Sum/images/minpath.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]
<strong>Output:</strong> 12
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= grid[i][j] <= 200</code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
TypeScript
|
function minPathSum(grid: number[][]): number {
const m = grid.length;
const n = grid[0].length;
const f: number[][] = Array(m)
.fill(0)
.map(() => Array(n).fill(0));
f[0][0] = grid[0][0];
for (let i = 1; i < m; ++i) {
f[i][0] = f[i - 1][0] + grid[i][0];
}
for (let j = 1; j < n; ++j) {
f[0][j] = f[0][j - 1] + grid[0][j];
}
for (let i = 1; i < m; ++i) {
for (let j = 1; j < n; ++j) {
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
}
}
return f[m - 1][n - 1];
}
|
65 |
Valid Number
|
Hard
|
<p>Given a string <code>s</code>, return whether <code>s</code> is a <strong>valid number</strong>.<br />
<br />
For example, all the following are valid numbers: <code>"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"</code>, while the following are not valid numbers: <code>"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"</code>.</p>
<p>Formally, a <strong>valid number</strong> is defined using one of the following definitions:</p>
<ol>
<li>An <strong>integer number</strong> followed by an <strong>optional exponent</strong>.</li>
<li>A <strong>decimal number</strong> followed by an <strong>optional exponent</strong>.</li>
</ol>
<p>An <strong>integer number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by <strong>digits</strong>.</p>
<p>A <strong>decimal number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by one of the following definitions:</p>
<ol>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code>.</li>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
<li>A <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
</ol>
<p>An <strong>exponent</strong> is defined with an <strong>exponent notation</strong> <code>'e'</code> or <code>'E'</code> followed by an <strong>integer number</strong>.</p>
<p>The <strong>digits</strong> are defined as one or more digits.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "."</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only English letters (both uppercase and lowercase), digits (<code>0-9</code>), plus <code>'+'</code>, minus <code>'-'</code>, or dot <code>'.'</code>.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
bool isNumber(string s) {
int n = s.size();
int i = 0;
if (s[i] == '+' || s[i] == '-') ++i;
if (i == n) return false;
if (s[i] == '.' && (i + 1 == n || s[i + 1] == 'e' || s[i + 1] == 'E')) return false;
int dot = 0, e = 0;
for (int j = i; j < n; ++j) {
if (s[j] == '.') {
if (e || dot) return false;
++dot;
} else if (s[j] == 'e' || s[j] == 'E') {
if (e || j == i || j == n - 1) return false;
++e;
if (s[j + 1] == '+' || s[j + 1] == '-') {
if (++j == n - 1) return false;
}
} else if (s[j] < '0' || s[j] > '9')
return false;
}
return true;
}
};
|
65 |
Valid Number
|
Hard
|
<p>Given a string <code>s</code>, return whether <code>s</code> is a <strong>valid number</strong>.<br />
<br />
For example, all the following are valid numbers: <code>"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"</code>, while the following are not valid numbers: <code>"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"</code>.</p>
<p>Formally, a <strong>valid number</strong> is defined using one of the following definitions:</p>
<ol>
<li>An <strong>integer number</strong> followed by an <strong>optional exponent</strong>.</li>
<li>A <strong>decimal number</strong> followed by an <strong>optional exponent</strong>.</li>
</ol>
<p>An <strong>integer number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by <strong>digits</strong>.</p>
<p>A <strong>decimal number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by one of the following definitions:</p>
<ol>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code>.</li>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
<li>A <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
</ol>
<p>An <strong>exponent</strong> is defined with an <strong>exponent notation</strong> <code>'e'</code> or <code>'E'</code> followed by an <strong>integer number</strong>.</p>
<p>The <strong>digits</strong> are defined as one or more digits.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "."</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only English letters (both uppercase and lowercase), digits (<code>0-9</code>), plus <code>'+'</code>, minus <code>'-'</code>, or dot <code>'.'</code>.</li>
</ul>
|
String
|
C#
|
using System.Text.RegularExpressions;
public class Solution {
private readonly Regex _isNumber_Regex = new Regex(@"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?\s*$");
public bool IsNumber(string s) {
return _isNumber_Regex.IsMatch(s);
}
}
|
65 |
Valid Number
|
Hard
|
<p>Given a string <code>s</code>, return whether <code>s</code> is a <strong>valid number</strong>.<br />
<br />
For example, all the following are valid numbers: <code>"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"</code>, while the following are not valid numbers: <code>"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"</code>.</p>
<p>Formally, a <strong>valid number</strong> is defined using one of the following definitions:</p>
<ol>
<li>An <strong>integer number</strong> followed by an <strong>optional exponent</strong>.</li>
<li>A <strong>decimal number</strong> followed by an <strong>optional exponent</strong>.</li>
</ol>
<p>An <strong>integer number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by <strong>digits</strong>.</p>
<p>A <strong>decimal number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by one of the following definitions:</p>
<ol>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code>.</li>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
<li>A <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
</ol>
<p>An <strong>exponent</strong> is defined with an <strong>exponent notation</strong> <code>'e'</code> or <code>'E'</code> followed by an <strong>integer number</strong>.</p>
<p>The <strong>digits</strong> are defined as one or more digits.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "."</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only English letters (both uppercase and lowercase), digits (<code>0-9</code>), plus <code>'+'</code>, minus <code>'-'</code>, or dot <code>'.'</code>.</li>
</ul>
|
String
|
Go
|
func isNumber(s string) bool {
i, n := 0, len(s)
if s[i] == '+' || s[i] == '-' {
i++
}
if i == n {
return false
}
if s[i] == '.' && (i+1 == n || s[i+1] == 'e' || s[i+1] == 'E') {
return false
}
var dot, e int
for j := i; j < n; j++ {
if s[j] == '.' {
if e > 0 || dot > 0 {
return false
}
dot++
} else if s[j] == 'e' || s[j] == 'E' {
if e > 0 || j == i || j == n-1 {
return false
}
e++
if s[j+1] == '+' || s[j+1] == '-' {
j++
if j == n-1 {
return false
}
}
} else if s[j] < '0' || s[j] > '9' {
return false
}
}
return true
}
|
65 |
Valid Number
|
Hard
|
<p>Given a string <code>s</code>, return whether <code>s</code> is a <strong>valid number</strong>.<br />
<br />
For example, all the following are valid numbers: <code>"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"</code>, while the following are not valid numbers: <code>"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"</code>.</p>
<p>Formally, a <strong>valid number</strong> is defined using one of the following definitions:</p>
<ol>
<li>An <strong>integer number</strong> followed by an <strong>optional exponent</strong>.</li>
<li>A <strong>decimal number</strong> followed by an <strong>optional exponent</strong>.</li>
</ol>
<p>An <strong>integer number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by <strong>digits</strong>.</p>
<p>A <strong>decimal number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by one of the following definitions:</p>
<ol>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code>.</li>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
<li>A <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
</ol>
<p>An <strong>exponent</strong> is defined with an <strong>exponent notation</strong> <code>'e'</code> or <code>'E'</code> followed by an <strong>integer number</strong>.</p>
<p>The <strong>digits</strong> are defined as one or more digits.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "."</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only English letters (both uppercase and lowercase), digits (<code>0-9</code>), plus <code>'+'</code>, minus <code>'-'</code>, or dot <code>'.'</code>.</li>
</ul>
|
String
|
Java
|
class Solution {
public boolean isNumber(String s) {
int n = s.length();
int i = 0;
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
++i;
}
if (i == n) {
return false;
}
if (s.charAt(i) == '.'
&& (i + 1 == n || s.charAt(i + 1) == 'e' || s.charAt(i + 1) == 'E')) {
return false;
}
int dot = 0, e = 0;
for (int j = i; j < n; ++j) {
if (s.charAt(j) == '.') {
if (e > 0 || dot > 0) {
return false;
}
++dot;
} else if (s.charAt(j) == 'e' || s.charAt(j) == 'E') {
if (e > 0 || j == i || j == n - 1) {
return false;
}
++e;
if (s.charAt(j + 1) == '+' || s.charAt(j + 1) == '-') {
if (++j == n - 1) {
return false;
}
}
} else if (s.charAt(j) < '0' || s.charAt(j) > '9') {
return false;
}
}
return true;
}
}
|
65 |
Valid Number
|
Hard
|
<p>Given a string <code>s</code>, return whether <code>s</code> is a <strong>valid number</strong>.<br />
<br />
For example, all the following are valid numbers: <code>"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"</code>, while the following are not valid numbers: <code>"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"</code>.</p>
<p>Formally, a <strong>valid number</strong> is defined using one of the following definitions:</p>
<ol>
<li>An <strong>integer number</strong> followed by an <strong>optional exponent</strong>.</li>
<li>A <strong>decimal number</strong> followed by an <strong>optional exponent</strong>.</li>
</ol>
<p>An <strong>integer number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by <strong>digits</strong>.</p>
<p>A <strong>decimal number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by one of the following definitions:</p>
<ol>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code>.</li>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
<li>A <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
</ol>
<p>An <strong>exponent</strong> is defined with an <strong>exponent notation</strong> <code>'e'</code> or <code>'E'</code> followed by an <strong>integer number</strong>.</p>
<p>The <strong>digits</strong> are defined as one or more digits.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "."</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only English letters (both uppercase and lowercase), digits (<code>0-9</code>), plus <code>'+'</code>, minus <code>'-'</code>, or dot <code>'.'</code>.</li>
</ul>
|
String
|
Python
|
class Solution:
def isNumber(self, s: str) -> bool:
n = len(s)
i = 0
if s[i] in '+-':
i += 1
if i == n:
return False
if s[i] == '.' and (i + 1 == n or s[i + 1] in 'eE'):
return False
dot = e = 0
j = i
while j < n:
if s[j] == '.':
if e or dot:
return False
dot += 1
elif s[j] in 'eE':
if e or j == i or j == n - 1:
return False
e += 1
if s[j + 1] in '+-':
j += 1
if j == n - 1:
return False
elif not s[j].isnumeric():
return False
j += 1
return True
|
65 |
Valid Number
|
Hard
|
<p>Given a string <code>s</code>, return whether <code>s</code> is a <strong>valid number</strong>.<br />
<br />
For example, all the following are valid numbers: <code>"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"</code>, while the following are not valid numbers: <code>"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"</code>.</p>
<p>Formally, a <strong>valid number</strong> is defined using one of the following definitions:</p>
<ol>
<li>An <strong>integer number</strong> followed by an <strong>optional exponent</strong>.</li>
<li>A <strong>decimal number</strong> followed by an <strong>optional exponent</strong>.</li>
</ol>
<p>An <strong>integer number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by <strong>digits</strong>.</p>
<p>A <strong>decimal number</strong> is defined with an <strong>optional sign</strong> <code>'-'</code> or <code>'+'</code> followed by one of the following definitions:</p>
<ol>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code>.</li>
<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
<li>A <strong>dot</strong> <code>'.'</code> followed by <strong>digits</strong>.</li>
</ol>
<p>An <strong>exponent</strong> is defined with an <strong>exponent notation</strong> <code>'e'</code> or <code>'E'</code> followed by an <strong>integer number</strong>.</p>
<p>The <strong>digits</strong> are defined as one or more digits.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "."</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only English letters (both uppercase and lowercase), digits (<code>0-9</code>), plus <code>'+'</code>, minus <code>'-'</code>, or dot <code>'.'</code>.</li>
</ul>
|
String
|
Rust
|
impl Solution {
pub fn is_number(s: String) -> bool {
let mut i = 0;
let n = s.len();
if let Some(c) = s.chars().nth(i) {
if c == '+' || c == '-' {
i += 1;
if i == n {
return false;
}
}
}
if let Some(x) = s.chars().nth(i) {
if x == '.'
&& (i + 1 == n
|| (if let Some(m) = s.chars().nth(i + 1) {
m == 'e' || m == 'E'
} else {
false
}))
{
return false;
}
}
let mut dot = 0;
let mut e = 0;
let mut j = i;
while j < n {
if let Some(c) = s.chars().nth(j) {
if c == '.' {
if e > 0 || dot > 0 {
return false;
}
dot += 1;
} else if c == 'e' || c == 'E' {
if e > 0 || j == i || j == n - 1 {
return false;
}
e += 1;
if let Some(x) = s.chars().nth(j + 1) {
if x == '+' || x == '-' {
j += 1;
if j == n - 1 {
return false;
}
}
}
} else if !c.is_ascii_digit() {
return false;
}
}
j += 1;
}
true
}
}
|
66 |
Plus One
|
Easy
|
<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>'s.</p>
<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> digits = [1,2,3]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong> The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> digits = [4,3,2,1]
<strong>Output:</strong> [4,3,2,2]
<strong>Explanation:</strong> The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> digits = [9]
<strong>Output:</strong> [1,0]
<strong>Explanation:</strong> The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
<li><code>digits</code> does not contain any leading <code>0</code>'s.</li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for (int i = digits.size() - 1; i >= 0; --i) {
++digits[i];
digits[i] %= 10;
if (digits[i] != 0) return digits;
}
digits.insert(digits.begin(), 1);
return digits;
}
};
|
66 |
Plus One
|
Easy
|
<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>'s.</p>
<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> digits = [1,2,3]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong> The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> digits = [4,3,2,1]
<strong>Output:</strong> [4,3,2,2]
<strong>Explanation:</strong> The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> digits = [9]
<strong>Output:</strong> [1,0]
<strong>Explanation:</strong> The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
<li><code>digits</code> does not contain any leading <code>0</code>'s.</li>
</ul>
|
Array; Math
|
Go
|
func plusOne(digits []int) []int {
n := len(digits)
for i := n - 1; i >= 0; i-- {
digits[i]++
digits[i] %= 10
if digits[i] != 0 {
return digits
}
}
return append([]int{1}, digits...)
}
|
66 |
Plus One
|
Easy
|
<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>'s.</p>
<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> digits = [1,2,3]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong> The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> digits = [4,3,2,1]
<strong>Output:</strong> [4,3,2,2]
<strong>Explanation:</strong> The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> digits = [9]
<strong>Output:</strong> [1,0]
<strong>Explanation:</strong> The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
<li><code>digits</code> does not contain any leading <code>0</code>'s.</li>
</ul>
|
Array; Math
|
Java
|
class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for (int i = n - 1; i >= 0; --i) {
++digits[i];
digits[i] %= 10;
if (digits[i] != 0) {
return digits;
}
}
digits = new int[n + 1];
digits[0] = 1;
return digits;
}
}
|
66 |
Plus One
|
Easy
|
<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>'s.</p>
<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> digits = [1,2,3]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong> The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> digits = [4,3,2,1]
<strong>Output:</strong> [4,3,2,2]
<strong>Explanation:</strong> The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> digits = [9]
<strong>Output:</strong> [1,0]
<strong>Explanation:</strong> The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
<li><code>digits</code> does not contain any leading <code>0</code>'s.</li>
</ul>
|
Array; Math
|
JavaScript
|
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function (digits) {
for (let i = digits.length - 1; i >= 0; --i) {
++digits[i];
digits[i] %= 10;
if (digits[i] != 0) {
return digits;
}
}
return [1, ...digits];
};
|
66 |
Plus One
|
Easy
|
<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>'s.</p>
<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> digits = [1,2,3]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong> The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> digits = [4,3,2,1]
<strong>Output:</strong> [4,3,2,2]
<strong>Explanation:</strong> The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> digits = [9]
<strong>Output:</strong> [1,0]
<strong>Explanation:</strong> The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
<li><code>digits</code> does not contain any leading <code>0</code>'s.</li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
n = len(digits)
for i in range(n - 1, -1, -1):
digits[i] += 1
digits[i] %= 10
if digits[i] != 0:
return digits
return [1] + digits
|
66 |
Plus One
|
Easy
|
<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>'s.</p>
<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> digits = [1,2,3]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong> The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> digits = [4,3,2,1]
<strong>Output:</strong> [4,3,2,2]
<strong>Explanation:</strong> The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> digits = [9]
<strong>Output:</strong> [1,0]
<strong>Explanation:</strong> The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
<li><code>digits</code> does not contain any leading <code>0</code>'s.</li>
</ul>
|
Array; Math
|
Rust
|
impl Solution {
pub fn plus_one(mut digits: Vec<i32>) -> Vec<i32> {
let n = digits.len();
for i in (0..n).rev() {
digits[i] += 1;
if 10 > digits[i] {
return digits;
}
digits[i] %= 10;
}
digits.insert(0, 1);
digits
}
}
|
66 |
Plus One
|
Easy
|
<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>'s.</p>
<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> digits = [1,2,3]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong> The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> digits = [4,3,2,1]
<strong>Output:</strong> [4,3,2,2]
<strong>Explanation:</strong> The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> digits = [9]
<strong>Output:</strong> [1,0]
<strong>Explanation:</strong> The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
<li><code>digits</code> does not contain any leading <code>0</code>'s.</li>
</ul>
|
Array; Math
|
TypeScript
|
function plusOne(digits: number[]): number[] {
const n = digits.length;
for (let i = n - 1; i >= 0; i--) {
if (10 > ++digits[i]) {
return digits;
}
digits[i] %= 10;
}
return [1, ...digits];
}
|
67 |
Add Binary
|
Easy
|
<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length <= 10<sup>4</sup></code></li>
<li><code>a</code> and <code>b</code> consist only of <code>'0'</code> or <code>'1'</code> characters.</li>
<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>
|
Bit Manipulation; Math; String; Simulation
|
C++
|
class Solution {
public:
string addBinary(string a, string b) {
string ans;
int i = a.size() - 1, j = b.size() - 1;
for (int carry = 0; i >= 0 || j >= 0 || carry; --i, --j) {
carry += (i >= 0 ? a[i] - '0' : 0) + (j >= 0 ? b[j] - '0' : 0);
ans.push_back((carry % 2) + '0');
carry /= 2;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
|
67 |
Add Binary
|
Easy
|
<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length <= 10<sup>4</sup></code></li>
<li><code>a</code> and <code>b</code> consist only of <code>'0'</code> or <code>'1'</code> characters.</li>
<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>
|
Bit Manipulation; Math; String; Simulation
|
C#
|
public class Solution {
public string AddBinary(string a, string b) {
int i = a.Length - 1;
int j = b.Length - 1;
var sb = new StringBuilder();
for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) {
carry += i >= 0 ? a[i] - '0' : 0;
carry += j >= 0 ? b[j] - '0' : 0;
sb.Append(carry % 2);
carry /= 2;
}
var ans = sb.ToString().ToCharArray();
Array.Reverse(ans);
return new string(ans);
}
}
|
67 |
Add Binary
|
Easy
|
<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length <= 10<sup>4</sup></code></li>
<li><code>a</code> and <code>b</code> consist only of <code>'0'</code> or <code>'1'</code> characters.</li>
<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>
|
Bit Manipulation; Math; String; Simulation
|
Go
|
func addBinary(a string, b string) string {
i, j := len(a)-1, len(b)-1
ans := []byte{}
for carry := 0; i >= 0 || j >= 0 || carry > 0; i, j = i-1, j-1 {
if i >= 0 {
carry += int(a[i] - '0')
}
if j >= 0 {
carry += int(b[j] - '0')
}
ans = append(ans, byte(carry%2+'0'))
carry /= 2
}
for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
ans[i], ans[j] = ans[j], ans[i]
}
return string(ans)
}
|
67 |
Add Binary
|
Easy
|
<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length <= 10<sup>4</sup></code></li>
<li><code>a</code> and <code>b</code> consist only of <code>'0'</code> or <code>'1'</code> characters.</li>
<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>
|
Bit Manipulation; Math; String; Simulation
|
Java
|
class Solution {
public String addBinary(String a, String b) {
var sb = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1;
for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) {
carry += (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0);
sb.append(carry % 2);
carry /= 2;
}
return sb.reverse().toString();
}
}
|
67 |
Add Binary
|
Easy
|
<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length <= 10<sup>4</sup></code></li>
<li><code>a</code> and <code>b</code> consist only of <code>'0'</code> or <code>'1'</code> characters.</li>
<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>
|
Bit Manipulation; Math; String; Simulation
|
Python
|
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a, 2) + int(b, 2))[2:]
|
67 |
Add Binary
|
Easy
|
<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length <= 10<sup>4</sup></code></li>
<li><code>a</code> and <code>b</code> consist only of <code>'0'</code> or <code>'1'</code> characters.</li>
<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>
|
Bit Manipulation; Math; String; Simulation
|
Rust
|
impl Solution {
pub fn add_binary(a: String, b: String) -> String {
let mut i = (a.len() as i32) - 1;
let mut j = (b.len() as i32) - 1;
let mut carry = 0;
let mut ans = String::new();
let a = a.as_bytes();
let b = b.as_bytes();
while i >= 0 || j >= 0 || carry > 0 {
if i >= 0 {
carry += a[i as usize] - b'0';
i -= 1;
}
if j >= 0 {
carry += b[j as usize] - b'0';
j -= 1;
}
ans.push_str(&(carry % 2).to_string());
carry /= 2;
}
ans.chars().rev().collect()
}
}
|
67 |
Add Binary
|
Easy
|
<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length <= 10<sup>4</sup></code></li>
<li><code>a</code> and <code>b</code> consist only of <code>'0'</code> or <code>'1'</code> characters.</li>
<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>
|
Bit Manipulation; Math; String; Simulation
|
TypeScript
|
function addBinary(a: string, b: string): string {
return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2);
}
|
68 |
Text Justification
|
Hard
|
<p>Given an array of strings <code>words</code> and a width <code>maxWidth</code>, format the text such that each line has exactly <code>maxWidth</code> characters and is fully (left and right) justified.</p>
<p>You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces <code>' '</code> when necessary so that each line has exactly <code>maxWidth</code> characters.</p>
<p>Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.</p>
<p>For the last line of text, it should be left-justified, and no extra space is inserted between words.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A word is defined as a character sequence consisting of non-space characters only.</li>
<li>Each word's length is guaranteed to be greater than <code>0</code> and not exceed <code>maxWidth</code>.</li>
<li>The input array <code>words</code> contains at least one word.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
<strong>Output:</strong>
[
"This is an",
"example of text",
"justification. "
]</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
<strong>Output:</strong>
[
"What must be",
"acknowledgment ",
"shall be "
]
<strong>Explanation:</strong> Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
<strong>Output:</strong>
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 300</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li><code>words[i]</code> consists of only English letters and symbols.</li>
<li><code>1 <= maxWidth <= 100</code></li>
<li><code>words[i].length <= maxWidth</code></li>
</ul>
|
Array; String; Simulation
|
C++
|
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ans;
for (int i = 0, n = words.size(); i < n;) {
vector<string> t = {words[i]};
int cnt = words[i].size();
++i;
while (i < n && cnt + 1 + words[i].size() <= maxWidth) {
cnt += 1 + words[i].size();
t.emplace_back(words[i++]);
}
if (i == n || t.size() == 1) {
string left = t[0];
for (int j = 1; j < t.size(); ++j) {
left += " " + t[j];
}
string right = string(maxWidth - left.size(), ' ');
ans.emplace_back(left + right);
continue;
}
int spaceWidth = maxWidth - (cnt - t.size() + 1);
int w = spaceWidth / (t.size() - 1);
int m = spaceWidth % (t.size() - 1);
string row;
for (int j = 0; j < t.size() - 1; ++j) {
row += t[j] + string(w + (j < m ? 1 : 0), ' ');
}
row += t.back();
ans.emplace_back(row);
}
return ans;
}
};
|
68 |
Text Justification
|
Hard
|
<p>Given an array of strings <code>words</code> and a width <code>maxWidth</code>, format the text such that each line has exactly <code>maxWidth</code> characters and is fully (left and right) justified.</p>
<p>You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces <code>' '</code> when necessary so that each line has exactly <code>maxWidth</code> characters.</p>
<p>Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.</p>
<p>For the last line of text, it should be left-justified, and no extra space is inserted between words.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A word is defined as a character sequence consisting of non-space characters only.</li>
<li>Each word's length is guaranteed to be greater than <code>0</code> and not exceed <code>maxWidth</code>.</li>
<li>The input array <code>words</code> contains at least one word.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
<strong>Output:</strong>
[
"This is an",
"example of text",
"justification. "
]</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
<strong>Output:</strong>
[
"What must be",
"acknowledgment ",
"shall be "
]
<strong>Explanation:</strong> Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
<strong>Output:</strong>
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 300</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li><code>words[i]</code> consists of only English letters and symbols.</li>
<li><code>1 <= maxWidth <= 100</code></li>
<li><code>words[i].length <= maxWidth</code></li>
</ul>
|
Array; String; Simulation
|
C#
|
public class Solution {
public IList<string> FullJustify(string[] words, int maxWidth) {
var ans = new List<string>();
for (int i = 0, n = words.Length; i < n;) {
var t = new List<string>();
t.Add(words[i]);
int cnt = words[i].Length;
++i;
while (i < n && cnt + 1 + words[i].Length <= maxWidth) {
t.Add(words[i]);
cnt += 1 + words[i].Length;
++i;
}
if (i == n || t.Count == 1) {
string left = string.Join(" ", t);
string right = new string(' ', maxWidth - left.Length);
ans.Add(left + right);
continue;
}
int spaceWidth = maxWidth - (cnt - t.Count + 1);
int w = spaceWidth / (t.Count - 1);
int m = spaceWidth % (t.Count - 1);
var row = new StringBuilder();
for (int j = 0; j < t.Count - 1; ++j) {
row.Append(t[j]);
row.Append(new string(' ', w + (j < m ? 1 : 0)));
}
row.Append(t[t.Count - 1]);
ans.Add(row.ToString());
}
return ans;
}
}
|
68 |
Text Justification
|
Hard
|
<p>Given an array of strings <code>words</code> and a width <code>maxWidth</code>, format the text such that each line has exactly <code>maxWidth</code> characters and is fully (left and right) justified.</p>
<p>You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces <code>' '</code> when necessary so that each line has exactly <code>maxWidth</code> characters.</p>
<p>Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.</p>
<p>For the last line of text, it should be left-justified, and no extra space is inserted between words.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A word is defined as a character sequence consisting of non-space characters only.</li>
<li>Each word's length is guaranteed to be greater than <code>0</code> and not exceed <code>maxWidth</code>.</li>
<li>The input array <code>words</code> contains at least one word.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
<strong>Output:</strong>
[
"This is an",
"example of text",
"justification. "
]</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
<strong>Output:</strong>
[
"What must be",
"acknowledgment ",
"shall be "
]
<strong>Explanation:</strong> Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
<strong>Output:</strong>
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 300</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li><code>words[i]</code> consists of only English letters and symbols.</li>
<li><code>1 <= maxWidth <= 100</code></li>
<li><code>words[i].length <= maxWidth</code></li>
</ul>
|
Array; String; Simulation
|
Go
|
func fullJustify(words []string, maxWidth int) (ans []string) {
for i, n := 0, len(words); i < n; {
t := []string{words[i]}
cnt := len(words[i])
i++
for i < n && cnt+1+len(words[i]) <= maxWidth {
cnt += 1 + len(words[i])
t = append(t, words[i])
i++
}
if i == n || len(t) == 1 {
left := strings.Join(t, " ")
right := strings.Repeat(" ", maxWidth-len(left))
ans = append(ans, left+right)
continue
}
spaceWidth := maxWidth - (cnt - len(t) + 1)
w := spaceWidth / (len(t) - 1)
m := spaceWidth % (len(t) - 1)
row := strings.Builder{}
for j, s := range t[:len(t)-1] {
row.WriteString(s)
row.WriteString(strings.Repeat(" ", w))
if j < m {
row.WriteString(" ")
}
}
row.WriteString(t[len(t)-1])
ans = append(ans, row.String())
}
return
}
|
68 |
Text Justification
|
Hard
|
<p>Given an array of strings <code>words</code> and a width <code>maxWidth</code>, format the text such that each line has exactly <code>maxWidth</code> characters and is fully (left and right) justified.</p>
<p>You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces <code>' '</code> when necessary so that each line has exactly <code>maxWidth</code> characters.</p>
<p>Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.</p>
<p>For the last line of text, it should be left-justified, and no extra space is inserted between words.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A word is defined as a character sequence consisting of non-space characters only.</li>
<li>Each word's length is guaranteed to be greater than <code>0</code> and not exceed <code>maxWidth</code>.</li>
<li>The input array <code>words</code> contains at least one word.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
<strong>Output:</strong>
[
"This is an",
"example of text",
"justification. "
]</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
<strong>Output:</strong>
[
"What must be",
"acknowledgment ",
"shall be "
]
<strong>Explanation:</strong> Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
<strong>Output:</strong>
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 300</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li><code>words[i]</code> consists of only English letters and symbols.</li>
<li><code>1 <= maxWidth <= 100</code></li>
<li><code>words[i].length <= maxWidth</code></li>
</ul>
|
Array; String; Simulation
|
Java
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ans = new ArrayList<>();
for (int i = 0, n = words.length; i < n;) {
List<String> t = new ArrayList<>();
t.add(words[i]);
int cnt = words[i].length();
++i;
while (i < n && cnt + 1 + words[i].length() <= maxWidth) {
cnt += 1 + words[i].length();
t.add(words[i++]);
}
if (i == n || t.size() == 1) {
String left = String.join(" ", t);
String right = " ".repeat(maxWidth - left.length());
ans.add(left + right);
continue;
}
int spaceWidth = maxWidth - (cnt - t.size() + 1);
int w = spaceWidth / (t.size() - 1);
int m = spaceWidth % (t.size() - 1);
StringBuilder row = new StringBuilder();
for (int j = 0; j < t.size() - 1; ++j) {
row.append(t.get(j));
row.append(" ".repeat(w + (j < m ? 1 : 0)));
}
row.append(t.get(t.size() - 1));
ans.add(row.toString());
}
return ans;
}
}
|
68 |
Text Justification
|
Hard
|
<p>Given an array of strings <code>words</code> and a width <code>maxWidth</code>, format the text such that each line has exactly <code>maxWidth</code> characters and is fully (left and right) justified.</p>
<p>You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces <code>' '</code> when necessary so that each line has exactly <code>maxWidth</code> characters.</p>
<p>Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.</p>
<p>For the last line of text, it should be left-justified, and no extra space is inserted between words.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A word is defined as a character sequence consisting of non-space characters only.</li>
<li>Each word's length is guaranteed to be greater than <code>0</code> and not exceed <code>maxWidth</code>.</li>
<li>The input array <code>words</code> contains at least one word.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
<strong>Output:</strong>
[
"This is an",
"example of text",
"justification. "
]</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
<strong>Output:</strong>
[
"What must be",
"acknowledgment ",
"shall be "
]
<strong>Explanation:</strong> Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
<strong>Output:</strong>
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 300</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li><code>words[i]</code> consists of only English letters and symbols.</li>
<li><code>1 <= maxWidth <= 100</code></li>
<li><code>words[i].length <= maxWidth</code></li>
</ul>
|
Array; String; Simulation
|
Python
|
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
ans = []
i, n = 0, len(words)
while i < n:
t = []
cnt = len(words[i])
t.append(words[i])
i += 1
while i < n and cnt + 1 + len(words[i]) <= maxWidth:
cnt += 1 + len(words[i])
t.append(words[i])
i += 1
if i == n or len(t) == 1:
left = ' '.join(t)
right = ' ' * (maxWidth - len(left))
ans.append(left + right)
continue
space_width = maxWidth - (cnt - len(t) + 1)
w, m = divmod(space_width, len(t) - 1)
row = []
for j, s in enumerate(t[:-1]):
row.append(s)
row.append(' ' * (w + (1 if j < m else 0)))
row.append(t[-1])
ans.append(''.join(row))
return ans
|
68 |
Text Justification
|
Hard
|
<p>Given an array of strings <code>words</code> and a width <code>maxWidth</code>, format the text such that each line has exactly <code>maxWidth</code> characters and is fully (left and right) justified.</p>
<p>You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces <code>' '</code> when necessary so that each line has exactly <code>maxWidth</code> characters.</p>
<p>Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.</p>
<p>For the last line of text, it should be left-justified, and no extra space is inserted between words.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A word is defined as a character sequence consisting of non-space characters only.</li>
<li>Each word's length is guaranteed to be greater than <code>0</code> and not exceed <code>maxWidth</code>.</li>
<li>The input array <code>words</code> contains at least one word.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
<strong>Output:</strong>
[
"This is an",
"example of text",
"justification. "
]</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
<strong>Output:</strong>
[
"What must be",
"acknowledgment ",
"shall be "
]
<strong>Explanation:</strong> Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
<strong>Output:</strong>
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 300</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li><code>words[i]</code> consists of only English letters and symbols.</li>
<li><code>1 <= maxWidth <= 100</code></li>
<li><code>words[i].length <= maxWidth</code></li>
</ul>
|
Array; String; Simulation
|
TypeScript
|
function fullJustify(words: string[], maxWidth: number): string[] {
const ans: string[] = [];
for (let i = 0, n = words.length; i < n; ) {
const t: string[] = [words[i]];
let cnt = words[i++].length;
while (i < n && cnt + 1 + words[i].length <= maxWidth) {
t.push(words[i]);
cnt += 1 + words[i++].length;
}
if (i === n || t.length === 1) {
const left: string = t.join(' ');
const right: string = ' '.repeat(maxWidth - left.length);
ans.push(left + right);
continue;
}
const spaceWidth: number = maxWidth - (cnt - t.length + 1);
const w: number = Math.floor(spaceWidth / (t.length - 1));
const m: number = spaceWidth % (t.length - 1);
const row: string[] = [];
for (let j = 0; j < t.length - 1; ++j) {
row.push(t[j]);
row.push(' '.repeat(w + (j < m ? 1 : 0)));
}
row.push(t[t.length - 1]);
ans.push(row.join(''));
}
return ans;
}
|
69 |
Sqrt(x)
|
Easy
|
<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>
<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>
<ul>
<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Math; Binary Search
|
C++
|
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x;
while (l < r) {
int mid = (l + r + 1ll) >> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
}
};
|
69 |
Sqrt(x)
|
Easy
|
<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>
<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>
<ul>
<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Math; Binary Search
|
C#
|
public class Solution {
public int MySqrt(int x) {
int l = 0, r = x;
while (l < r) {
int mid = (l + r + 1) >>> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
}
}
|
69 |
Sqrt(x)
|
Easy
|
<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>
<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>
<ul>
<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Math; Binary Search
|
Go
|
func mySqrt(x int) int {
return sort.Search(x+1, func(i int) bool { return i*i > x }) - 1
}
|
69 |
Sqrt(x)
|
Easy
|
<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>
<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>
<ul>
<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Math; Binary Search
|
Java
|
class Solution {
public int mySqrt(int x) {
int l = 0, r = x;
while (l < r) {
int mid = (l + r + 1) >>> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
}
}
|
69 |
Sqrt(x)
|
Easy
|
<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>
<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>
<ul>
<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Math; Binary Search
|
JavaScript
|
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function (x) {
let [l, r] = [0, x];
while (l < r) {
const mid = (l + r + 1) >> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
};
|
69 |
Sqrt(x)
|
Easy
|
<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>
<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>
<ul>
<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Math; Binary Search
|
Python
|
class Solution:
def mySqrt(self, x: int) -> int:
l, r = 0, x
while l < r:
mid = (l + r + 1) >> 1
if mid > x // mid:
r = mid - 1
else:
l = mid
return l
|
69 |
Sqrt(x)
|
Easy
|
<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>
<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>
<ul>
<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x <= 2<sup>31</sup> - 1</code></li>
</ul>
|
Math; Binary Search
|
Rust
|
impl Solution {
pub fn my_sqrt(x: i32) -> i32 {
let mut l = 0;
let mut r = x;
while l < r {
let mid = (l + r + 1) / 2;
if mid > x / mid {
r = mid - 1;
} else {
l = mid;
}
}
l
}
}
|
70 |
Climbing Stairs
|
Easy
|
<p>You are climbing a staircase. It takes <code>n</code> steps to reach the top.</p>
<p>Each time you can either climb <code>1</code> or <code>2</code> steps. In how many distinct ways can you climb to the top?</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 45</code></li>
</ul>
|
Memoization; Math; Dynamic Programming
|
C++
|
class Solution {
public:
int climbStairs(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; ++i) {
int c = a + b;
a = b;
b = c;
}
return b;
}
};
|
70 |
Climbing Stairs
|
Easy
|
<p>You are climbing a staircase. It takes <code>n</code> steps to reach the top.</p>
<p>Each time you can either climb <code>1</code> or <code>2</code> steps. In how many distinct ways can you climb to the top?</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 45</code></li>
</ul>
|
Memoization; Math; Dynamic Programming
|
Go
|
func climbStairs(n int) int {
a, b := 0, 1
for i := 0; i < n; i++ {
a, b = b, a+b
}
return b
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.