leetcode 1289 - Minimum Falling Path Sum II

https://leetcode.com/problems/minimum-falling-path-sum-ii/

Given a square grid of integers arr, a falling path with non-zero shifts is a choice of exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in the same column.

Return the minimum sum of a falling path with non-zero shifts.

Example 1:

Input: arr = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.

Constraints:

1 <= arr.length == arr[i].length <= 200
-99 <= arr[i][j] <= 99

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
int minFallingPathSum(vector<vector<int>>& arr) {
int row = arr.size(), col = arr[0].size();

int prev_min1 = INT_MAX, prev_min2 = INT_MAX;
int prev_min1_idx, prev_min2_idx;

int dp[row][col];

for (int i = 0; i < row; i++) {
int min1 = INT_MAX, min2 = INT_MAX;
int min1_idx, min2_idx;

for (int j = 0; j < col; j++) {
if (i == 0) {
dp[i][j] = arr[i][j];
} else {
if (j != prev_min1_idx)
dp[i][j] = dp[i-1][prev_min1_idx] + arr[i][j];
else
dp[i][j] = dp[i-1][prev_min2_idx] + arr[i][j];
}

if (dp[i][j] <= min1) {
min2 = min1;
min2_idx = min1_idx;
min1 = dp[i][j];
min1_idx = j;
} else if (dp[i][j] < min2) {
min2 = dp[i][j];
min2_idx = j;
}
}

prev_min1 = min1;
prev_min1_idx = min1_idx;
prev_min2 = min2;
prev_min2_idx = min2_idx;
}

return prev_min1;
}
};

leetcode 1293 - Shortest Path in a Grid with Obstacles Elimination

https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/

Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

Example 1:

Input:
grid =
[[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]],
k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

Example 2:

Input:
grid =
[[0,1,1],
[1,1,1],
[1,0,0]],
k = 1
Output: -1
Explanation:
We need to eliminate at least two obstacles to find such a walk.

Constraints:

grid.length == m
grid[0].length == n
1 <= m, n <= 40
1 <= k <= m*n
grid[i][j] == 0 or 1
grid[0][0] == grid[m-1][n-1] == 0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
struct State {
int x, y;
int remain;

State(int _x, int _y, int _remain) {
x = _x;
y = _y;
remain = _remain;
}
};

int shortestPath(vector<vector<int>>& grid, int k) {
int row = grid.size(), col = grid[0].size();
queue<State> q;

q.push(State(0, 0, k));

int step = 0;

vector<vector<int>> dirs = {{0,-1},{-1,0}, {0,1}, {1,0}};
vector<vector<vector<bool>>> seen(row,
vector<vector<bool>>(col, vector<bool>(k+1, false)));

while (!q.empty()) {
int size = q.size();

for (int i = 0; i < size; i++) {
State s = q.front(); q.pop();

if (s.x == row-1 && s.y == col-1) return step;

for (auto &dir : dirs) {
int x = s.x + dir[0];
int y = s.y + dir[1];

if (x < 0 || x >= row || y < 0 || y >= col) continue;

int r = s.remain - (grid[x][y] == 1);

if (r < 0 || seen[x][y][r]) continue;

seen[x][y][r] = true;

q.push(State(x, y, r));

}
}

step++;
}

return -1;
}
};

leetcode 1298 - Maximum Candies You Can Get from Boxes

https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/

Given n boxes, each box is given in the format [status, candies, keys, containedBoxes] where:

status[i]: an integer which is 1 if box[i] is open and 0 if box[i] is closed.
candies[i]: an integer representing the number of candies in box[i].
keys[i]: an array contains the indices of the boxes you can open with the key in box[i].
containedBoxes[i]: an array contains the indices of the boxes found in box[i].
You will start with some boxes given in initialBoxes array. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.

Return the maximum number of candies you can get following the rules above.

Example 1:

Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
Output: 16
Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you don’t have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
Total number of candies collected = 7 + 4 + 5 = 16 candy.
Example 2:

Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
Output: 6
Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6.
Example 3:

Input: status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]
Output: 1
Example 4:

Input: status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []
Output: 0
Example 5:

Input: status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]
Output: 7

Constraints:

1 <= status.length <= 1000
status.length == candies.length == keys.length == containedBoxes.length == n
status[i] is 0 or 1.
1 <= candies[i] <= 1000
0 <= keys[i].length <= status.length
0 <= keys[i][j] < status.length
All values in keys[i] are unique.
0 <= containedBoxes[i].length <= status.length
0 <= containedBoxes[i][j] < status.length
All values in containedBoxes[i] are unique.
Each box is contained in one box at most.
0 <= initialBoxes.length <= status.length
0 <= initialBoxes[i] < status.length

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {

queue<int> q;
unordered_set<int> all_keys;
vector<int> all_boxes;

for (int i : initialBoxes)
q.push(i);

while (!q.empty()) {
int i = q.front(); q.pop();

all_boxes.push_back(i);
for (int b : containedBoxes[i])
q.push(b);
for (int k : keys[i])
all_keys.insert(k);
}

int total = 0;

for (int i : all_boxes) {
if (status[i] == 1 || all_keys.count(i))
total += candies[i];
}

return total;
}
};

leetcode 1301 - Number of Paths with Max Score

https://leetcode.com/problems/number-of-paths-with-max-score/

You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character ‘S’.

You need to reach the top left square marked with the character ‘E’. The rest of the squares are labeled either with a numeric character 1, 2, …, 9 or with an obstacle ‘X’. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.

Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.

In case there is no path, return [0, 0].

Example 1:

Input: board = [“E23”,”2X2”,”12S”]
Output: [7,1]
Example 2:

Input: board = [“E12”,”1X1”,”21S”]
Output: [4,2]
Example 3:

Input: board = [“E11”,”XXX”,”11S”]
Output: [0,0]

Constraints:

2 <= board.length == board[i].length <= 100

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
vector<int> pathsWithMaxScore(vector<string>& board) {
int mod = 1e9 + 7;
vector<vector<int>> dirs = {{0,-1},{-1,0},{-1,-1}};

int row = board.size(), col = board[0].size();

vector<vector<pair<int,int>>> dp(row, vector<pair<int,int>>(col, {0, 0}));
dp[0][0] = {0, 1};

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (i == 0 && j == 0) continue;
if (board[i][j] == 'X') continue;

for (auto &dir : dirs) {
int x = i + dir[0], y = j + dir[1];
if (x < 0 || x >= row || y < 0 || y >= col || board[x][y] == 'X') continue;

if (dp[x][y].first > dp[i][j].first)
dp[i][j] = dp[x][y];
else if (dp[x][y].first == dp[i][j].first)
dp[i][j].second = (dp[i][j].second + dp[x][y].second) % mod;
}

if (i != row - 1 || j != col - 1)
dp[i][j].first += board[i][j] - '0';

dp[i][j].first %= mod;
}
}

auto &p = dp[row-1][col-1];
if (p.second == 0)
return vector<int>{0,0};
return vector<int>{p.first, p.second};
}
};

leetcode 1307 - Verbal Arithmetic Puzzle

https://leetcode.com/problems/verbal-arithmetic-puzzle/

Given an equation, represented by words on left side and the result on right side.

You need to check if the equation is solvable under the following rules:

Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.

Example 1:

Input: words = [“SEND”,”MORE”], result = “MONEY”
Output: true
Explanation: Map ‘S’-> 9, ‘E’->5, ‘N’->6, ‘D’->7, ‘M’->1, ‘O’->0, ‘R’->8, ‘Y’->’2’
Such that: “SEND” + “MORE” = “MONEY” , 9567 + 1085 = 10652
Example 2:

Input: words = [“SIX”,”SEVEN”,”SEVEN”], result = “TWENTY”
Output: true
Explanation: Map ‘S’-> 6, ‘I’->5, ‘X’->0, ‘E’->8, ‘V’->7, ‘N’->2, ‘T’->1, ‘W’->’3’, ‘Y’->4
Such that: “SIX” + “SEVEN” + “SEVEN” = “TWENTY” , 650 + 68782 + 68782 = 138214
Example 3:

Input: words = [“THIS”,”IS”,”TOO”], result = “FUNNY”
Output: true
Example 4:

Input: words = [“LEET”,”CODE”], result = “POINT”
Output: false

Constraints:

2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
public:
int char_to_int[256];
int int_to_char[10];

bool isSolvable(vector<string>& words, string result) {
for (int i = 0; i < 256; i++)
char_to_int[i] = -1;
for (int i = 0; i < 10; i++)
int_to_char[i] = -1;

string word;
return backtrace(words, 0, 0, 0, 0, result);
}

bool backtrace(vector<string> &words, int i, int k, int num, int sum, string &result) {
if (words[i].size() == k) {
sum += num;
num = 0;
k = 0;
i++;
}

if (i == words.size()) {
return check(sum, result);
}

int c = words[i][k];

for (int n = 0; n <= 9; n++) {
if (n == 0 && k == 0) continue;

if (int_to_char[n] != -1 && int_to_char[n] != c) continue;
if (char_to_int[c] != -1 && char_to_int[c] != n) continue;

int old_c = int_to_char[n];
int old_n = char_to_int[c];

int_to_char[n] = c;
char_to_int[c] = n;

if (backtrace(words, i, k+1, num * 10 + n, sum, result))
return true;

int_to_char[n] = old_c;
char_to_int[c] = old_n;
}

return false;
}

bool check(int sum, string &result) {
if (result.empty()) return false;
int i = result.size() - 1;

do {
if (i < 0) return false;

int n = sum % 10;
sum = sum / 10;

int c = result[i];
if (char_to_int[c] != -1 && char_to_int[c] != n) return false;
if (int_to_char[n] != -1 && int_to_char[n] != c) return false;
i--;
} while (sum);

return i < 0;
}
};

leetcode 1312 - Minimum Insertion Steps to Make a String Palindrome

https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/

Given a string s. In one step you can insert any character at any index of the string.

Return the minimum number of steps to make s palindrome.

A Palindrome String is one that reads the same backward as well as forward.

Example 1:

Input: s = “zzazz”
Output: 0
Explanation: The string “zzazz” is already palindrome we don’t need any insertions.
Example 2:

Input: s = “mbadm”
Output: 2
Explanation: String can be “mbdadbm” or “mdbabdm”.
Example 3:

Input: s = “leetcode”
Output: 5
Explanation: Inserting 5 characters the string becomes “leetcodocteel”.
Example 4:

Input: s = “g”
Output: 0
Example 5:

Input: s = “no”
Output: 1

Constraints:

1 <= s.length <= 500
All characters of s are lower case English letters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int minInsertions(string s) {
int size = s.size();
vector<vector<int>> dp(size, vector<int>(size, 0));

for (int len = 2; len <= size; len++) {
for (int i = 0; i <= size - len; i++) {
int j = i + len - 1;

dp[i][j] = min(dp[i+1][j] + 1, dp[i][j-1]+1);
if (s[i] == s[j])
dp[i][j] = min(dp[i][j], dp[i+1][j-1]);
}
}

return dp[0][size-1];
}
};

leetcode 1316 - Distinct Echo Substrings

https://leetcode.com/problems/distinct-echo-substrings/
https://leetcode.com/problems/distinct-echo-substrings/discuss/478854/C%2B%2B-DP-solution-O(N2)-with-explanation

Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself.

Example 1:

Input: text = “abcabcabc”
Output: 3
Explanation: The 3 substrings are “abcabc”, “bcabca” and “cabcab”.
Example 2:

Input: text = “leetcodeleetcode”
Output: 2
Explanation: The 2 substrings are “ee” and “leetcodeleetcode”.

Constraints:

1 <= text.length <= 2000
text has only lowercase English letters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int distinctEchoSubstrings(string text) {
unordered_set<string> distinct;
int size = text.size();

vector<vector<int>> dp(size+1, vector<int>(size+1, 0));

for (int j = size - 1; j > 0; j--) {
for (int i = j - 1; i >= 0; i--) {
if (text[i] == text[j])
dp[i][j] = dp[i+1][j+1] + 1;

if (dp[i][j] >= j - i)
distinct.insert(text.substr(i, j-i));
}
}

return distinct.size();
}
};

leetcode 1320 - Minimum Distance to Type a Word Using Two Fingers

https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/
https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/477652/JavaC%2B%2BPython-DP-Solution-O(1)-Space

ABCDEF
GHIJKL
MNOPQR
STUVWX
YZ

You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is located at coordinate (2,3) and the letter Z is located at coordinate (4,1).

Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|.

Note that the initial positions of your two fingers are considered free so don’t count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.

Example 1:

Input: word = “CAKE”
Output: 3
Explanation:
Using two fingers, one optimal way to type “CAKE” is:
Finger 1 on letter ‘C’ -> cost = 0
Finger 1 on letter ‘A’ -> cost = Distance from letter ‘C’ to letter ‘A’ = 2
Finger 2 on letter ‘K’ -> cost = 0
Finger 2 on letter ‘E’ -> cost = Distance from letter ‘K’ to letter ‘E’ = 1
Total distance = 3
Example 2:

Input: word = “HAPPY”
Output: 6
Explanation:
Using two fingers, one optimal way to type “HAPPY” is:
Finger 1 on letter ‘H’ -> cost = 0
Finger 1 on letter ‘A’ -> cost = Distance from letter ‘H’ to letter ‘A’ = 2
Finger 2 on letter ‘P’ -> cost = 0
Finger 2 on letter ‘P’ -> cost = Distance from letter ‘P’ to letter ‘P’ = 0
Finger 1 on letter ‘Y’ -> cost = Distance from letter ‘A’ to letter ‘Y’ = 4
Total distance = 6
Example 3:

Input: word = “NEW”
Output: 3
Example 4:

Input: word = “YEAR”
Output: 7

Constraints:

2 <= word.length <= 300
Each word[i] is an English uppercase letter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
int memo[300][27][27];

int minimumDistance(string word) {
for (int i = 0; i < 300; i++)
for (int j = 0; j < 27; j++)
for (int k = 0; k < 27; k++)
memo[i][j][k] = -1;

return dfs(word, 0, {4,2}, {4,2});
}

int dfs(string &word, int i, pair<int,int> finger1, pair<int,int> finger2) {
if (i == (int)word.size()) return 0;

int idx1 = finger1.first * 6 + finger1.second;
int idx2 = finger2.first * 6 + finger2.second;
if (memo[i][idx1][idx2] != -1)
return memo[i][idx1][idx2];

pair<int,int> p = getPoint(word[i]);
int d1 = getDist(p, finger1);
int d2 = getDist(p, finger2);

//finger 1
int dist1 = dfs(word, i+1, p, finger2) + d1;
//finger 2
int dist2 = dfs(word, i+1, finger1, p) + d2;

memo[i][idx1][idx2] = min(dist1, dist2);
return memo[i][idx1][idx2];
}

pair<int,int> getPoint(char c) {
int idx = c - 'A';

return {idx/6, idx%6};
}

int getDist(pair<int,int> &p1, pair<int,int> &p2) {
if (p2.first * 6 + p2.second == 26) return 0;

return abs(p1.first - p2.first) + abs(p1.second - p2.second);
}
};

leetcode 681 - Next Closest Time

https://leetcode.com/problems/next-closest-time/

Given a time represented in the format “HH:MM”, form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.

You may assume the given input string is always valid. For example, “01:34”, “12:09” are all valid. “1:34”, “12:9” are all invalid.

Example 1:

Input: “19:34”
Output: “19:39”
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later.
Example 2:

Input: “23:59”
Output: “22:22”
Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day’s time since it is smaller than the input time numerically.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Solution {
public:
struct Time {
int hour;
int min;
};

string closestTime;
int closest;
Time origTime;

string nextClosestTime(string time) {
closest = INT_MAX;
string str(4, ' ');
str[0] = time[0];
str[1] = time[1];
str[2] = time[3];
str[3] = time[4];

origTime = parseTimeStr(str);

string output;
dfs(str, output);

if (closestTime.empty()) return time;

return closestTime.substr(0, 2) + ":" + closestTime.substr(2);
}

void dfs(string &str, string &output) {
if (output.size() == 1 && output[0] >= '3') return;
if (output.size() == 3 && output[2] >= '6') return;

if (output.size() == 2 && (output[0]-'0') * 10 + (output[1] - '0') >= 24)
return;
if (output.size() == 4) {
if ((output[2]-'0') * 10 + (output[3] - '0') < 60) {
int diff = timeDiff(origTime, parseTimeStr(output));
if (diff && diff < closest) {
closest = diff;
closestTime = output;
}
}

return;
}

for (int i = 0; i < str.size(); i++) {
output.push_back(str[i]);
dfs(str, output);
output.pop_back();
}
}

Time parseTimeStr(string &str) {
Time t;

t.hour = (str[0] - '0') * 10 + (str[1] - '0');
t.min = (str[2] - '0') * 10 + (str[3] - '0');
return t;
}

int timeDiff(Time orig, Time t) {
int diff = (t.hour - orig.hour) * 60 + (t.min - orig.min);

if (orig.hour > t.hour || (orig.hour == t.hour && orig.min > t.min)) {
diff += 24 * 60;
}

return diff;
}
};

leetcode 708 - Insert into a Sorted Circular Linked List

https://leetcode.com/problems/insert-into-a-sorted-circular-linked-list/

Given a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the circular list.

If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.

If the list is empty (i.e., given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the original given node.

Example 1:

Input: head = [3,4,1], insertVal = 2
Output: [3,4,1,2]
Explanation: In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.

Example 2:

Input: head = [], insertVal = 1
Output: [1]
Explanation: The list is empty (given head is null). We create a new single circular list and return the reference to that single node.
Example 3:

Input: head = [1], insertVal = 0
Output: [1,0]

Constraints:

0 <= Number of Nodes <= 5 * 10^4
-10^6 <= Node.val <= 10^6
-10^6 <= insertVal <= 10^6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;

Node() {}

Node(int _val) {
val = _val;
next = NULL;
}

Node(int _val, Node* _next) {
val = _val;
next = _next;
}
};
*/
class Solution {
public:
Node* insert(Node* head, int insertVal) {
Node *node = new Node(insertVal);

if (!head) {
node->next = node;
return node;
}

if (head == head->next) {
node->next = head;
head->next = node;
return head;
}

Node *cur = head, *next = cur->next;

while (1) {
if ((cur->val <= insertVal && insertVal <= next->val) ||
(cur->val > next->val && (insertVal >= cur->val || insertVal <= next->val)) ||
(next == head)) {
node->next = next;
cur->next = node;
break;
}

cur = next;
next = next->next;
}

return head;
}
};