fabiochiu/medium-articles huggingface dataset:
[LeetCode] 雙指標法(Two pointers)解題
Tags: Leetcode, 演算法, 資料結構

反向指標

反向雙指標最強大的就是在處理有排序的陣列時非常好用，從頭尾開始，往中間做遍歷。以167. Two Sum II — Input array is sorted為例：

題目

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

解題

前一篇已經寫過Two Sum的心得了，這題和那題最主要的不一樣是，這題的陣列已經幫你由小到大排序好了。首先要記得的是，「排序」是一件很珍貴的事！只要資料有排序過，就有很大的機會可以用很低的時間/空間複雜度去寫演算法，因為相當於資料已經被處理過一手了。

思考

因為已經被排序過，有沒有辦法達到時間O(n)、空間O(1)？因為排序的本質，我們可以知道陣列內數字間的大小關係 — 排在後面的一定比前面的大。

所以如果我的兩個數字和sum不等於target，我只要比較現在的sum vs. target，如果sum>target，我就把sum「調小」，可以透過把sum「往左移動」達成，如果sum>target，則是要把sum「往右移動」。

所以就產生了雙指針的想法！我設定兩個指針，分別指在陣列的最大和最小數，如果相加>target，則把大的指針往左邊移動，如果<target，則把小的指針往右移動，一直到指針交叉(因為等於重複查找)或找到target為止。

程式碼

var twoSum = function(numbers, target) {

let p1 = 0

let p2 = numbers.length - 1



while (p2 > p1) {

if (numbers[p1]+numbers[p2] > target) {

p2--

} else if (numbers[p1]+numbers[p2] < target) {

p1++

} else {

return [p1+1, p2+1]

}

}



};

這樣的寫法又比hash table空間複雜度更低，同時維持時間複雜度在O(n)。這題用反向指標其實有「逼近」的概念在，跟binary search有一點像，因為是排序資料，所以可以透過慢慢逼近去找出答案。

同向指標

283. Move Zeroes

題目

Given an array nums , write a function to move all 0 's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]

Output: [1,3,12,0,0]

Note:

You must do this in-place without making a copy of the array. Minimize the total number of operations.

這題要特別注意的是，不能創造額外的陣列來解題，所以我不能創造一個新陣列->for迴圈去跑nums->把非0的數字丟進新陣列->看有幾個零再把它push到新陣列裡面->回傳新陣列。

所以我們只能去思考要怎麼樣在原有的陣列裡面透過「交換」的方式，把0換到最後面。

解題

思考

「交換」代表的是兩兩互換，也就是說我需要去控制兩個元素，所以很明顯的可以用雙指標去解題。但是這和上一題不一樣的是，這裡不是排序陣列，我也沒有要去「逼近」什麼已知數，而且我是要把所有的0去「推」到最後面，所以我應該是要讓兩個指標都從0開始而不是從頭和尾開始。

那我的兩個指標分別要做什麼呢？思考一下我要做什麼：去遍歷一個陣列，如果遇到不是0，就把它和前面的0做交換，來慢慢的把0換到最後面去。

所以，我的一個指針需要往前走去遍歷，另外一個則需要留在0，一直到被互換後再往前進找下一個0。

引用開頭文章，同方向指標：

設定兩個指標、從頭往尾(或從尾到頭)遍歷，我稱之為同方向指標，第一個指標用於遍歷，第二個指標滿足一定條件下移動

程式碼

var moveZeroes = function(nums) {

let p1 = 0

let p2 = 0



while (p2 < nums.length) {

if (nums[p2] === 0) {

p2 ++

} else {

[nums[p1], nums[p2]] = [nums[p2], nums[p1]]

p1++

p2++

}

}

};

這邊讓p2去做遍歷，所以while要設在<nums.length。p1則是根據題目情況做移動，只有在交換過後才會移動。

註記1：這段程式是ES6當中讓變數互換的寫法：

[nums[p1], nums[p2]] = [nums[p2], nums[p1]]

註記2: 這篇medium有圖解此寫法，會看得比較清楚：

後記
Jeff Erickson’s book on algorithms
By: Sweta Barman
Tags: Leetcode, Algorithms, Coding Interviews

I’d started to get bored of leetcode. I could not bring myself to solve another leetcode problem. After all, it did not serve any higher purpose. I wanted something else to occupy my mind — that is when I came across Jeff Erickson’s book on Algorithms : https://jeffe.cs.illinois.edu/teaching/algorithms/#book

It absolutely blew my mind! This book is clearer and better written than any other algorithm book out there! So friends and algorithm enthusiasts — let’s solve the exercises!

I will be starting a new series of posts on the book — I’m open to discussions and working together while solving the exercises! Let me know!
Squares of a sorted array
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]

Output: [0,1,9,16,100]

Explanation: After squaring, the array becomes [16,1,0,9,100].

After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]

Output: [4,9,9,49,121]

Constraints:

1 <= nums.length <= 104

-104 <= nums[i] <= 104

nums is sorted in non-decreasing order.

Check below blog for solution with explanation
LeetCode Challenge: Single Number
By: Will Sheppard
Tags: Leetcode, JavaScript, Coding, Programming, Arrays

Url: https://leetcode.com/problems/single-number/

Description

Given a non-empty array of integers nums , every element appears twice except for one. Find that single one.

Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

Example 1

Input: nums = [2,2,1]

Output: 1

Example 2

Input: nums = [4,1,2,1,2]

Output: 4

Example 3

Input: nums = [1]

Output: 1

Constraints

1 <= nums.length <= 3 * 104

-3 * 104 <= nums[i] <= 3 * 104

Each element in the array appears twice except for one element which appears only once.

Solution:

Steps

1. Create a object to keep track of the number of times a integer occurs in our nums array.

2. Loop through nums array.

3. If there is no key in obj matching the corresponding integer, add the key to the obj Object, and assign it with the property 1.

4. If the corresponding integer is already has a key, matching its value, then increment the property of that key in obj.

5. Return the key in obj that has a property of 1.

Code (JavaScript)

Results

Runtime: 104 ms, faster than 29.24% of JavaScript online submissions for Single Number. Memory Usage: 44.4 MB, less than 27.33% of JavaScript online submissions for Single Number.

Thanks for viewing. If you have any feedback on how to improve this code, leave a comment.
[Leet code] Reverse Bits
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Leetcode: https://leetcode.com/problems/reverse-bits/

Problem:

Reverse bits of a given 32 bits unsigned integer.

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.

In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825 .

Follow up:

If this function is called many times, how would you optimize it?

Example 1:

Input: n = 00000010100101000001111010011100

Output: 964176192 (00111001011110000010100101000000)

Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: n = 11111111111111111111111111111101

Output: 3221225471 (10111111111111111111111111111111)

Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Constraints:

The input must be a binary string of length 32

Solution:



#

#

def reverseBits(self, n):

test = list('{:032b}'.format(n))

test.reverse()

return int("".join(test),2) class Solution: @param n, an integer @return an integerdef reverseBits(self, n):test = list('{:032b}'.format(n))test.reverse()return int("".join(test),2)

Explanation:

‘{:032b}’.format(n) will convert an int to a binary number of 32 bits. We assign this to a list to make use of the reverse operator. Then we join this list into a string and int(number,2) will convert a binary back to a decimal.
[Leet Code] Number of 1 bits
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Leetcode: https://leetcode.com/problems/number-of-1-bits/

Problem:

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.

In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3 above, the input represents the signed integer. -3 .

Follow up: If this function is called many times, how would you optimize it?

Example 1:

Input: n = 00000000000000000000000000001011

Output: 3

Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000

Output: 1

Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101

Output: 31

Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Solution:

class Solution(object):

def hammingWeight(self, n):

"""

:type n: int

:rtype: int

"""

return list(format(n,"b")).count("1")

Explanation:
JavaScript Algorithms: Verifying an Alien Dictionary (LeetCode)
By: Anatolii Kurochkin
Tags: Leetcode, Data Structures, Software Development, Algorithms, JavaScript

Description

In an alien language, surprisingly they also use English lowercase letters, but possibly in a different order . The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.

Example 1:

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"

Output: true

Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:

Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"

Output: false

Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:

Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"

Output: false

Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ( words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"falseThe first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ( More info ).

Constraints:

1 <= words.length <= 100

1 <= words[i].length <= 20

order.length == 26

All characters in words[i] and order are English lowercase letters.

Solution

First of all, let’s find out what lexicographic order is — wiki. What we really need to know about lexicographic order for solving this problem:

If two words have the same first letter, we compare the second. If the second letters are the same, we compare the third and so on. Finally, one word comes before the other if the first differing letter comes before the corresponding letter.

If two words are identical up to the length of the shorter word, the shorter word comes first.

In other words — javascript.info:

Compare the first character of both strings. If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done. Otherwise, if both strings’ first characters are the same, compare the second characters the same way. Repeat until the end of either string. If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.

To compare two letters in JavaScript means to compare their codes in Unicode (16-bit Unicode Transformation Format). So, using Unicode we know that a has feff0061 char code, b has feff0062 , and so on.

'a'.charCodeAt().toString(16) -> 61

'b'.charCodeAt().toString(16) -> 62

...

'z'.charCodeAt().toString(16) -> 7a
[Leet Code] XOR Operation in an Array
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Leet Code: https://leetcode.com/problems/xor-operation-in-an-array/

Problem:

Given an integer n and an integer start .

Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length .

Return the bitwise XOR of all elements of nums .

Example 1:

Input: n = 5, start = 0

Output: 8

Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.

Where "^" corresponds to bitwise XOR operator.

Example 2:

Input: n = 4, start = 3

Output: 8

Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.

Example 3:

Input: n = 1, start = 7

Output: 7

Example 4:

Input: n = 10, start = 5

Output: 2

Solution:

class Solution(object):

def xorOperation(self, n, start):

"""

:type n: int

:type start: int

:rtype: int

"""

bitwise = 0

for i in range(n):

bitwise ^= (start + 2*i)

return bitwise
Longest Common Prefix
Tags: Leetcode, Leetcode Easy, Longest Common Prefix

My Solution

const longestCommonPrefix = (strs) => {

let result = "";

let single = [];

let match = [];

let i = 0;

while (single.length === match.length) {

single = strs.map((str) => str[i]);

match = single.filter((ltr) => ltr === single[i]);

single.length === match.length && (result += match[0]);

i++;

}

return result;

};

This is my first solution! Logic is to start with getting the single letter array and the matching array. Then, if match.length is equal to single.length , which is the same as strs.length , it added to result array. And this goes until the single array length equal to the match array length.

This works fine, however, the problem is over the memory limitations. I got runtime error by this solution. I tried to approach it in a different way.

const longestCommonPrefix = (strs) => {

if (strs.length === 0) return "";

let prefix = strs[0];

for (let i = 1; i < strs.length; i++) {

while (strs[i].indexOf(prefix) !== 0) {

prefix = prefix.substring(0, prefix.length - 1);

}

}

return prefix;

};

This is my second solution, it simply defines the first letter is as prefix . then it subtracts the letter from the end until remaining only the common letter.

This works well! simpler and better I guess!

This time, there is no best practice in the Leetcode community. Done!
Balanced Parentheses
By: Sivareddy Uppathi
Tags: Leetcode, Fang, Java8, Java, Competitive Programming

This the frequently asked question in FANG & Top Rated Leet Code Problem.. solution in Java.

Approach-1 : Time Complexity : O(n) & Space: O(n).

This problem is to check how much good you are at data structures. Best Data Structure to solve this problem is Stack or ArrayDeque(In Java) faster than Stack. To validate current char I used switch-case instead of if-else

import java.util.Stack;

*

*

*/

public class BalancedParathesis { /** @author SivaReddy Uppathi*/public class BalancedParathesis { // Approch-1

private static boolean isBalanced(String expression) {

// ArrayDeque is faster than Stack class

// Deque<Character> stack = new ArrayDeque<>();

Stack<Character> paranthasis = new Stack<>(); if (expression.isEmpty()) {

return true;

} for (int i = 0; i < expression.length(); i++) {

char current = expression.charAt(i); if (current == '(' || current == '{' || current == '[') {

paranthasis.add(current);

continue;

}

if (paranthasis.empty()) {

return false;

}

char lastchar;

switch (current) {

case '}':

lastchar = paranthasis.pop();

if (lastchar == '(' || lastchar == '[') {

return false;

}

break;

case ')':

lastchar = paranthasis.pop();

if (lastchar == '{' || lastchar == '[') {

return false;

}

break;

case ']':

lastchar = paranthasis.pop();

if (lastchar == '{' || lastchar == '(') {

return false;

}

break;

}

}

return paranthasis.empty();

}

public static void main(String[] args) {

String str = "{a[b(g)]q}";

boolean balanced = isBalanced(str);

System.out.println(balanced);

}

}

Approach-2 : Time Complexity : O(n) & Space: O(n).

It is also same as Approach 1 but the difference is Using if-else. This is a Short form of above one.
[Leet Code] Queries on a Permutation With Key
By: Matthew Boyd
Tags: Leetcode, Data Structures, Algorithms, Leetcode Solution, Leetcode Medium

Leet Code: https://leetcode.com/problems/queries-on-a-permutation-with-key/

Problem:

Given the array queries of positive integers between 1 and m , you have to process all queries[i] (from i=0 to i=queries.length-1 ) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m] . For the current i , find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i] . Return an array containing the result for the given queries .

Example:

Input: queries = [3,1,2,1], m = 5

Output: [2,1,2,1]

Explanation: The queries are processed as follow:

For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5].

For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5].

For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5].

For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5].

Therefore, the array containing the result is [2,1,2,1].

Solution:

class Solution(object):

def processQueries(self, queries, m):

"""

:type queries: List[int]

:type m: int

:rtype: List[int]

"""

answer = queries

p = [number for number in range(1,m+1)]

for i, v in enumerate(queries):

answer[i] = p.index(v)

p.remove(v)

p.insert(0,v)

return answer

So first we assign the list queries to a variable answer, this will give us the same length of list. Then we create the p variable of 1-m(m+1 is needed because arrays start at 0). Then we use the enumerate function in python, the i will provide us the index, and v will provide us the value of queries at that index. Then we assign the first each index of answer to the position of the index of the value in query. Then we remove the value in p and insert it back at the start. Then return our answer.
Palindrome Number
Tags: Leetcode, Leetcode Easy, Palindrome Number

Palindrome Number

Problem

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Follow up: Could you solve it without converting the integer to a string?

Example 1:

Input: x = 121

Output: true

Example 2:

Input: x = -121

Output: false

Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10

Output: false

Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:

Input: x = -101

Output: false

Constraints:
[Leet Code] Maximum Nesting Depth of the Parentheses
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

LeetCode: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/

Problem:

A string is a valid parentheses string (denoted VPS) if it meets one of the following:

It is an empty string "" , or a single character not equal to "(" or ")" ,

, or a single character not equal to or , It can be written as AB ( A concatenated with B ), where A and B are VPS 's, or

( concatenated with ), where and are 's, or It can be written as (A) , where A is a VPS.

We can similarly define the nesting depth depth(S) of any VPS S as follows:

depth("") = 0

depth(C) = 0 , where C is a string with a single character not equal to "(" or ")" .

, where is a string with a single character not equal to or . depth(A + B) = max(depth(A), depth(B)) , where A and B are VPS 's.

, where and are 's. depth("(" + A + ")") = 1 + depth(A) , where A is a VPS.

For example, "" , "()()" , and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.

Given a VPS represented as string s , return the nesting depth of s .

Example 1:

Input: s = "(1+(2*3)+((8)/4))+1"

Output: 3

Explanation: Digit 8 is inside of 3 nested parentheses in the string.

Example 2:

Input: s = "(1)+((2))+(((3)))"

Output: 3

Example 3:

Input: s = "1+(2*3)/(2-1)"

Output: 1

Example 4:

Input: s = "1"

Output: 0

Solution:

class Solution(object):

def maxDepth(self, s):

"""

:type s: str

:rtype: int

"""

stack = []

max_val = 0

for i in s:

if i == "(":

stack.append(i)

if i == ")":

stack.pop()

length = len(stack)

if length > max_val:

max_val = length

return max_val

Explanation:
Roman to Integer
Tags: Leetcode, Roman To Integer, Leetcode Easy

Roman to Integer

Problem

Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M .

Symbol Value

I 1

V 5

X 10

L 50

C 100

D 500

M 1000

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II .

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.

can be placed before (5) and (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90.

can be placed before (50) and (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

Example 1:

Input: s = "III"

Output: 3

Example 2:

Input: s = "IV"

Output: 4

Example 3:

Input: s = "IX"

Output: 9

Example 4:

Input: s = "LVIII"

Output: 58

Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: s = "MCMXCIV"

Output: 1994

Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:
LeetCode Challenge: Shuffle Strings
By: Will Sheppard
Tags: Leetcode, Data Structures, Algorithms, Coding, Programming

Description

Given a string s and an integer array indices of the same length.

The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.

Return the shuffled string.

Example 1

Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]

Output: "leetcode"

Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.

Example 2

Input: s = "abc", indices = [0,1,2]

Output: "abc"

Explanation: After shuffling, each character remains in its position.

Example 3

Input: s = "aiohn", indices = [3,1,4,2,0]

Output: "nihao"

Constraints

s.length == indices.length == n

1 <= n <= 100

s contains only lower-case English letters.

contains only lower-case English letters. 0 <= indices[i] < n

All values of indices are unique (i.e. indices is a permutation of the integers from 0 to n - 1 ).

Solution:

Steps

1. Initialize an empty array named shuffled, which will eventually hold the characters of s.

2. Loop over the string

3. Then for each iteration, use the value of i, to push that specific character in s, to the corresponding index in shuffled, based on the current value in our indices array.

4. Convert our shuffled array to a string.

5. Return shuffled

Code (JavaScript)

Results

Runtime: 96 ms, faster than 33.74% of JavaScript online submissions for Shuffle String. Memory Usage: 40.5 MB, less than 34.70% of JavaScript online submissions for Shuffle String.

Thanks for viewing. If you have any feedback on how to improve this code, leave a comment.
[Leet Code] Widest Vertical Area Between Two Points Containing No Points
By: Matthew Boyd
Tags: Leetcode, Data Structures, Algorithms, Leetcode Solution, Leetcode Medium

LeetCode: https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/

Problem:

Given n points on a 2D plane where points[i] = [xi, yi] , Return the widest vertical area between two points such that no points are inside the area.

A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.

Note that points on the edge of a vertical area are not considered included in the area.

Example 1:

​

Input: points = [[8,7],[9,9],[7,4],[9,7]]

Output: 1

Explanation: Both the red and the blue area are optimal.

Example 2:

Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]

Output: 3

Solution:

class Solution(object):

def maxWidthOfVerticalArea(self, points):

"""

:type points: List[List[int]]

:rtype: int

"""

test = []

for i in points:

test.append(i[0])



test.sort(reverse=True)



max_diff = 0

for i in range(len(test)-1):

diff = test[i] - test[i+1]

if diff > max_diff:

max_diff = diff

return max_diff

Explanation:

For this, all we really want is the X axis, and we want to arrange them in order so that we can see if there are any points in between two points. To do this, we first go through and get all the x axis they are the first number in each duo [1,0] X = 1, therefore because it’s a list of lists, we can get to each individual list and say that we want the 0th element. We append this onto a list;

Then we want to sort the list in reverse, from highest to lowest. test.sort(reverse=True).

Then we define a max diff variable. Then what we’re going to do is cycle through our list of X values and because they’re in reverse order, we can do i — i+1 and this will give us a positive number. Remember to do len(test)-1 to make sure you don’t get an out of range exception. Then we check if the diff calculated is greater than what’s stored in max_diff, and if so make max_diff = diff, otherwise continue on. Then we return the max_diff.
Leetcode 560. Subarray Sum Equals K(C++,C#,JAVA,JAVASCRIPT,RUBY,TYPESCRIPT)
By: Chan Park
Tags: Leetcode, Leetcode 560 Subarray Sum, Leetcode Medium, Leetcode 560, Subarray Sum Equals K

Given an array of integers nums and an integer k , return the total number of continuous subarrays whose sum equals to k .

Example 1:

Example 2:

Constraints:

//C++

int subarraySum(vector<int> &nums, int k)

{

int count = 0, sum = 0;

map<int, int> map;

map[0] = 1;

for (int i = 0; i < nums.size(); i++)

{

sum += nums[i];

if (map.find(sum - k) != map.end())

count += map[sum - k];

map[sum]++;

}

return count;

}

//C#

public int SubarraySum(int[] nums, int k)

{

int count = 0, sum = 0;

Dictionary<int, int> map = new Dictionary<int, int>();

map[0] = 1;

for (int i = 0; i < nums.Length; i++)

{

sum += nums[i];

if (map.ContainsKey(sum - k))

count += map[sum - k];

if (map.ContainsKey(sum))

map[sum] = map[sum] + 1;

else

map[sum] = 1;

}

return count;

}

//Java

public int subarraySum(int[] nums, int k) {

int count = 0;

int sum = 0;

HashMap<Integer, Integer> hashmap = new HashMap<Integer,Integer>();

hashmap.put(0, 1);

for (int i = 0; i < nums.length; i++) {

sum += nums[i];

if (hashmap.containsKey(sum - k)) {

count += hashmap.get(sum - k);

}

if (hashmap.containsKey(sum)) {

hashmap.put(sum, hashmap.get(sum) + 1);

} else {

hashmap.put(sum, 1);

}

}

return count;

}

//Javascript

var subarraySum = function(nums, k) {

let count = 0;

let sum = 0;

let hash = {};

// hash[0] = 1;

for(let i = 0; i < nums.length; i++)

{

sum+=nums[i];



if(sum===k)

count++;



if(hash[sum-k])

{

count += hash[sum-k];

}



if(hash[sum])

{

hash[sum]++;



}else

{

hash[sum] = 1;

}



//count+= (hash[sum-k] || 0)

//hash[sum] = (hash[sum] || 0) + 1;



}

return count;

};

//Ruby

def subarray_sum(nums, k)

hash = Hash.new(0)

hash[0] = 1

count = sum = 0

nums.each do |num|

sum += num

count += hash[sum - k]

hash[sum] += 1

end

count

end
Smallest Subtree with all the Deepest Nodes
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given the root of a binary tree, the depth of each node is the shortest distance to the root.

Return the smallest subtree such that it contains all the deepest nodes in the original tree.

A node is called the deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is tree consisting of that node, plus the set of all descendants of that node.

Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4]

Output: [2,7,4]

Explanation: We return the node with value 2, colored in yellow in the diagram.

The nodes coloured in blue are the deepest nodes of the tree.

Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.

Example 2:

Input: root = [1]

Output: [1]

Explanation: The root is the deepest node in the tree.

Example 3:

Input: root = [0,1,3,null,2]

Output: [2]

Explanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.

Constraints:

The number of nodes in the tree will be in the range [1, 500] .

. 0 <= Node.val <= 500

The values of the nodes in the tree are unique.

Visit below link for solution with detailed explanation
Leetcode SQL
By: Jen-Li Chen
Tags: Leetcode, Sql, Solutions

Leetcode SQL

1454. Active Users

Table Accounts :

+---------------+---------+

| Column Name | Type |

+---------------+---------+

| id | int |

| name | varchar |

+---------------+---------+

the id is the primary key for this table.

This table contains the account id and the user name of each account.

Table Logins :

+---------------+---------+

| Column Name | Type |

+---------------+---------+

| id | int |

| login_date | date |

+---------------+---------+

There is no primary key for this table, it may contain duplicates.

This table contains the account id of the user who logged in and the login date. A user may log in multiple times in the day.

Write an SQL query to find the id and the name of active users.

Active users are those who logged in to their accounts for 5 or more consecutive days.

Return the result table ordered by the id.

The query result format is in the following example:

Accounts table:

+----+----------+

| id | name |

+----+----------+

| 1 | Winston |

| 7 | Jonathan |

+----+----------+ Logins table:

+----+------------+

| id | login_date |

+----+------------+

| 7 | 2020-05-30 |

| 1 | 2020-05-30 |

| 7 | 2020-05-31 |

| 7 | 2020-06-01 |

| 7 | 2020-06-02 |

| 7 | 2020-06-02 |

| 7 | 2020-06-03 |

| 1 | 2020-06-07 |

| 7 | 2020-06-10 |

+----+------------+ Result table:

+----+----------+

| id | name |

+----+----------+

| 7 | Jonathan |

+----+----------+

User Winston with id = 1 logged in 2 times only in 2 different days, so, Winston is not an active user.

User Jonathan with id = 7 logged in 7 times in 6 different days, five of them were consecutive days, so, Jonathan is an active user.

Follow up question:

Can you write a general solution if the active users are those who logged in to their accounts for n or more consecutive days?

Solution:
[LeetCode]#1614. Maximum Nesting Depth of the Parentheses
By: Fatboy Slim
Tags: Leetcode, Leetcode Easy, Python, Algorithms, Python3

Environment: Python 3.7

Key technique: max

A string is a valid parentheses string (denoted VPS) if it meets one of the following:

It is an empty string "" , or a single character not equal to "(" or ")" ,

, or a single character not equal to or , It can be written as AB ( A concatenated with B ), where A and B are VPS 's, or

( concatenated with ), where and are 's, or It can be written as (A) , where A is a VPS.

We can similarly define the nesting depth depth(S) of any VPS S as follows:

depth("") = 0

depth(C) = 0 , where C is a string with a single character not equal to "(" or ")" .

, where is a string with a single character not equal to or . depth(A + B) = max(depth(A), depth(B)) , where A and B are VPS 's.

, where and are 's. depth("(" + A + ")") = 1 + depth(A) , where A is a VPS.

For example, "" , "()()" , and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.

Given a VPS represented as string s , return the nesting depth of s .

Example 1:

Input: s = "(1+(2*3)+((8)/4))+1"

Output: 3

Explanation: Digit 8 is inside of 3 nested parentheses in the string.

Analysis:

Search input. If the input is ‘(‘, tmp+=1. If the input is is ‘)’, tmp-=1. Find the maximum as an answer.

Solution:

class Solution:

def maxDepth(self, s):

ans=0

tmp=0

for i in s:

if (i=='('):

tmp+=1

ans=max(ans,tmp)

elif(i==')'):

tmp-=1

ans=max(ans,tmp)

return ans

Submissions:

Reference:

https://blog.csdn.net/w5688414/article/details/109369137
[LeetCode] 使用hash table來降低時間複雜度
Tags: Leetcode, 演算法, 資料結構

題目

Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target .

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

連結：https://leetcode.com/problems/two-sum/

簡單來說就是給一個陣列nums和一個目標數target，陣列中僅有一組數字兩兩相加會等於target，需要回傳這組數字的位置。

舉例：如果輸入 nums = [2,10,1, 7, 6,11] target = 9，會回傳[0,3]
Leetcode #1 — Two Sum (Python). Hello everyone, my name is Dhairya Dave…
By: Dhairya Dave
Tags: Leetcode, Leetcode Easy, Python, Coding Interviews, Python Programming

Today, we’ll be looking at the Two Sum problem. This problem is categorized as “Easy” on Leetcode.

Problem Statement

Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target . You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Examples from Leetcode

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Output explained:

The list containing the indices [0,1] should be returned as nums[0] + nums[1] = 2 + 7 = 9 (target)

Input: nums = [3,2,4], target = 6

Output: [1,2]

Input: nums = [3,3], target = 6

Output: [0,1]

Solution

Explanation (with two examples):

1. Let's call: twoSum([2, 7, 11, 15], 26) - Start by creating a dictionary ‘d’. - The 'idx' and 'num' values in "for idx, num in enumerate(nums)", where nums = [2,7,11,15] look something like this: idx -> num

0 -> 2

1 -> 7

2 -> 11

3 -> 15 - Iteration 1: idx = 0,

num = 2,

difference = target - num = 26 - 2 = 24 if 24 in d -> False So, we set d[2] = 0 ... d is now {2: 0} - Iteration 2: idx = 1,

num = 7,

difference = target - num = 26 - 7 = 19 if 19 in d -> False So, we set d[7] = 1 ... d is now {2: 0, 7: 1} - Iteration 3: idx = 2,

num = 11,

difference = target - num = 26 - 11 = 15 if 15 in d -> False So, we set d[11] = 2 ... d is now {2: 0, 7: 1, 11: 2} - Iteration 4: idx = 3,

num = 15,

difference = target - num = 26 - 15 = 11 if 11 in d -> True ... return [d[difference], idx] = [d[11], 3] = [2,3]

2. Let's call: twoSum([3, 6, 9, 12], 15) - Iteration 1: idx = 0,

num = 3,

difference = target - num = 15 - 3 = 12 if 12 in d -> False So, we set d[3] = 0 ... d is now {3: 0} - Iteration 2: idx = 1,

num = 6,

difference = target - num = 15 - 6 = 9 if 9 in d -> False So, we set d[6] = 1 ... d is now {3: 0, 6: 1} - Iteration 3: idx = 2,

num = 9,

difference = target - num = 15 - 9 = 6 if 6 in d -> True ... return [d[difference], idx] = [d[6], 2] =

[1, 2]

That’s all, folks! Happy Learning!

Dhairya Dave
[Leet Code] Split a String in Balanced Strings
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

LeetCode: https://leetcode.com/problems/split-a-string-in-balanced-strings/

Problem:

Balanced strings are those who have equal quantity of 'L' and 'R' characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings. Example 1: Input: s = "RLRRLLRLRL"

Output: 4

Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:

Input: s = "RLLLLRRRLR"

Output: 3

Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.

Example 3:

Input: s = "LLLLRRRR"

Output: 1

Explanation: s can be split into "LLLLRRRR".

Example 4:

Input: s = "RLRRRLLRLL"

Output: 2

Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

Solution:

class Solution(object):

def balancedStringSplit(self, s):

"""

:type s: str

:rtype: int

"""

balanced, l_count, r_count = 0,0,0



for i in s:

if i == 'L':

l_count = l_count + 1

else:

r_count = r_count + 1



if r_count == l_count:

balanced = balanced +1



return balanced

Explanation:

First you create three variables: balanced, l_count (left count) and r_count (right count). Then we want to iterate through the balanced string that we’ve got. If it’s an L, increment l_count, if it’s an R increment r_count. Then we want to check when l_count and r_count are equal, then we have a pair, so we want to increment balanced. Then we can just return the balanced variable.
623. Add One Row to Tree
By: Jesus Pf
Tags: Leetcode, Software, Interview, Bfs, Facebook Interview

LeetCode level medium question involving BFS and binary trees

Given the root of a binary tree, then value v and depth d , you need to add a row of nodes with value v at the given depth d . The root node is at depth 1.

The adding rule is: given a positive integer depth d , for each NOT null tree nodes N in depth d-1 , create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.

Example 1:

Input:

A binary tree as following:

4

/ \

2 6

/ \ /

3 1 5 v = 1 d = 2 Output:

4

/ \

1 1

/ \

2 6

/ \ /

3 1 5

Example 2:

Input:

A binary tree as following:

4

/

2

/ \

3 1 v = 1 d = 3 Output:

4

/

2

/ \

1 1

/ \

3 1

Note:

The given d is in range [1, maximum depth of the given tree + 1]. The given binary tree has at least one tree node.

Result:

Success Details Runtime: 0 ms, faster than 100.00% of Java online submissions for Add One Row to Tree. Memory Usage: 38.6 MB, less than 87.71% of Java online submissions for Add One Row to Tree.

Solution:
[Leet Code] Contains Duplicates II
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Problem:

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3

Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1

Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2

Output: false

Solution:
Leetcode-Design
By: Yunrui Li
Tags: Leetcode, Data Structure Algorithm, Python3, Design

The below LC problems are related to Design fundamental data structure from scratch:

考點 for min stack:

當我們想要retrieve一個最大或最小值得一個資料結構, 我們會想到heap, 他可以access minimum element in O(1)的時間, 但是他在insert和pop的時候都會需要花到O(log k)的時間. 所以我們除了一個正常的normal的stack可以做到pop/insert/top in O(1)的時間, 還需要再一個min stack, 我們會在push和pop操作時，同時維持這個min stack使得他棧頂的元素永遠是當前最小的元素. 在push的時候, 如果push的element比top of min stack還小, 我們放入此元素進min stack反之則忽略. 而在pop的時候的如果top of stack剛好是最小元素(top of min stack), 我們就不只對stack做pop()的動作也要對min stack做pop()的動作.

考點for max stack

我們不只是要implement getmin()我們需要implement popmax()的function. 這樣在push和pop的時候都需要同時對stack和max stack做操作. max stack在push的時候, 如果當前push小於top of max stack, 就不放入max stack但放入當前最大進入max stack. 而pop的時候同時都需要pop但回傳stack的pop. 最難在popmax() 如果top of stack of 和 top of max stack不同, 我們需要一個tmp stack去存放pop的元素從stack, 如果tmp_stack不為空, 再把他push回去.

考點for implement queue using two stacks

我們用兩個stack來達到queue, push的時候都放進stack1裡面, 但當peek()和pop()操作的時候, 當stack2是空的時候, 我們要把所有在stack1的element都倒進stack2, 直到stack1是空的, 在這樣的操作下當我們從stack2做pop()和peek()都會像queue的FIFO. 時間複雜度分析, 雖然每次移動stack1的元素到stack2的元素需要O(n)的時間, 但每次移動後, 保證了往後的n次peek()和pop()只需要O(1)的時間, 所以O(n)的時間複雜度平攤到了n次操作上, 最後還是每次只需要O(1)的時間.

155. Min Stack

641. Design Circular Deque

706. Design HashMap
Valid Mountain Array
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given an array of integers arr , return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if:

arr.length >= 3

There exists some i with 0 < i < arr.length - 1 such that:

with such that: arr[0] < arr[1] < ... < arr[i - 1] < A[i]

arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Example 1:

Input: arr = [2,1]

Output: false

Example 2:

Input: arr = [3,5,5]

Output: false

Example 3:

Input: arr = [0,3,2,1]

Output: true

Constraints:

1 <= arr.length <= 104

0 <= arr[i] <= 104

For solution with detailed explanation, visit below
[Leet Code] Convert Binary Number in a Linked List to Integer
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Leetcode Solution, Algorithms, Linked Lists

LeetCode: https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/

Problem:

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list.

Example 1:

Input: head = [1,0,1]

Output: 5

Explanation: (101) in base 2 = (5) in base 10

Example 2:

Input: head = [0]

Output: 0

Solution:

# Definition for singly-linked list.

# class ListNode(object):

# def __init__(self, val=0, next=None):

# self.val = val

# self.next = next

class Solution(object):

def getDecimalValue(self, head):

"""

:type head: ListNode

:rtype: int

"""

answers = []



while head.next:

answers.append(head.val)

head = head.next

answers.append(head.val)



length = len(answers) - 1

answers_sum = 0

for i,v in enumerate(answers):

answers_sum = answers_sum + (answers[i] * (2 ** length))

length = length - 1

return answers_sum

Explanation:

So we can break this problem into two sections, first we need to iterate over the linked list, and feed this into a string or a list. Then when we’ve done that, we then need to do the calculation for binary → decimal which is

[1,0,1]

(2² * 1) + (2¹ *0) + (2⁰*1)

4 +1 + 0 = 5

Something to note about this is that the power is len -1 of the array each time .
LeetCode — 1247. Minimum Swaps to Make Strings Equal
By: Cheng-Che Hsieh
Tags: Leetcode, Ｍedium, Algorithms, Swift

1. The Problem

You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j] . Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

Example 1:

Input: s1 = "xx", s2 = "yy"

Output: 1

Explanation:

Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".

Example 2:

Input: s1 = "xy", s2 = "yx"

Output: 2

Explanation:

Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".

Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".

Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.

Example 3:

Input: s1 = "xx", s2 = "xy"

Output: -1

Example 4:

Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"

Output: 4

Constraints:

1 <= s1.length, s2.length <= 1000

s1, s2 only contain 'x' or 'y' .

2. Description

Switch letters to make two strings are even. Return the minimum times if makes them the same. -1 if it can’t be.

3. Needs Attention

Some cases may return -1 All x and y

4. Values recommendation

“xxyxyxxyyxyyx”, “yyxxyxyyxxyxy” “xxxxxxxxxx”, “yyyyyyyyyy”

5. Reference Code (Beats 100%, 4ms)

x1, y1: What difference between s1 and s2 in s1

x2, y2: differ from s1 in s2

For example s1 = “xxxyyy”, s2 = “yyxyxx”, in s1, there are 2x and 2y is different from s2, so x1=2, y1=2. Because we need to have the same amount of x in both s1 and s2, x1 + x2/ y1+y2 must be divisible by 2. Or return -1.

s1=“xxyy”, s2=“yyxx” after first moving would be “xyyy” and “xyxx”, second ”xyxy” and “xyxy”. Each time we are switching a x to a y or a y to a x. Two x switches one time, then we will know x1/2 + y1/2. If the count of x or y is not even, we have to make them even first and do the same switching again. For example “xy” and “yx” first step is to switch to “xx” and “yy” then “xy” and “xy”.

In sum, if x1 and x2 is even, every two counts we switch once. If not, twice. That is (x1+y1)/2 * 1 + x1%2 + y1%2
[Leet Code] Height Checker
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Leetcode: https://leetcode.com/problems/height-checker/

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.

Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.

Example 1:

Input: heights = [1,1,4,2,1,3]

Output: 3

Explanation:

Current array : [1,1,4,2,1,3]

Target array : [1,1,1,2,3,4]

On index 2 (0-based) we have 4 vs 1 so we have to move this student.

On index 4 (0-based) we have 1 vs 3 so we have to move this student.

On index 5 (0-based) we have 3 vs 4 so we have to move this student.

Solution:

class Solution(object):

def heightChecker(self, heights):

"""

:type heights: List[int]

:rtype: int

"""

counter = 0

sorted_array = sorted(heights)

for i in range(len(heights)):

if heights[i] != sorted_array[i]:

counter = counter + 1



return counter

Explanation:

We want to sort the array, then we just compare the unsorted array with the sorted one and count the each position that doesn’t have the same value at each of their respective indexes.
Leetcode MySQL 626. Exchange Seats
By: Sharko Shen
Tags: Leetcode

題目:

倆倆交換座位。

Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids.

The column id is continuous increment.

Mary wants to change seats for the adjacent students.

Can you write a SQL query to output the result for Mary?

+---------+---------+

| id | student |

+---------+---------+

| 1 | Abbot |

| 2 | Doris |

| 3 | Emerson |

| 4 | Green |

| 5 | Jeames |

+---------+---------+

For the sample input, the output is:

+---------+---------+

| id | student |

+---------+---------+

| 1 | Doris |

| 2 | Abbot |

| 3 | Green |

| 4 | Emerson |

| 5 | Jeames |

+---------+---------+

思路:

倆倆交換座位，當Id是奇數且不是最後一個id時+1。當id是偶數時-1 當id是最後一個id且是奇數時保持不變。 計算最後一個id數字counts 運用CASE WHEN THEN ELSE END判斷情況

CASE WHEN

三個條件

1. input odd_id & odd_id <count(*) -> output odd_id + 1

2. input even_id -> output id — 1

3. input odd_id and odd_id=count(*) -> id

Coding:

# Write your MySQL query statement below

SELECT (CASE WHEN mod(id,2) =1 AND id = counts THEN id

WHEN mod(id,2) =1 AND id != counts THEN id + 1

ELSE id - 1

END) as id, student

FROM seat, (SELECT count(*) as counts FROM seat) as ttt

ORDER BY id;

注意，每個table都需要alias。
[Leet Code] Decrypt String from Alphabet to Integer Mapping
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

LeetCode: https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/

Problem:

Given a string s formed by digits ( '0' - '9' ) and '#' . We want to map s to English lowercase characters as follows:

Characters ( 'a' to 'i') are represented by ( '1' to '9' ) respectively.

Characters ( 'j' to 'z') are represented by ( '10#' to '26#' ) respectively.

Return the string formed after mapping.

It's guaranteed that a unique mapping will always exist.
Leetcode MySQL 182. Duplicate Emails
By: Sharko Shen
Tags: Leetcode

題目: 找出有重複的email。

Write a SQL query to find all duplicate emails in a table named Person .

+----+---------+

| Id | Email |

+----+---------+

| 1 | a@b.com |

| 2 | c@d.com |

| 3 | a@b.com |

+----+---------+

For example, your query should return the following for the above table:

+---------+

| Email |

+---------+

| a@b.com |

+---------+

思路:

不同id 同email

Coding: