fabiochiu/medium-articles huggingface dataset:
[LeetCode]#1603. Design Parking System
By: Fatboy Slim
Tags: Leetcode, Python3, Leetcode Easy, Python

Environment: Python 3.7

Key technique: class, _init_, self

Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.

Implement the ParkingSystem class:

ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.

Initializes object of the class. The number of slots for each parking space are given as part of the constructor. bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1 , 2 , and 3 respectively. A car can only park in a parking space of its carType . If there is no space available, return false , else park the car in that size space and return true .

Example 1:

Input

["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]

[[1, 1, 0], [1], [2], [3], [1]]

Output

[null, true, true, false, false] Explanation

ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);

parkingSystem.addCar(1); // return true because there is 1 available slot for a big car

parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car

parkingSystem.addCar(3); // return false because there is no available slot for a small car

parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.

Analysis:

Input parking space [1:1, 2:1, 3:0] means big, medium, and small parking space. Input parking car size. If parking space is larger than 1, return True and subtract 1. If parking space is equal to 0, return False.

Solution:

class ParkingSystem:

def __init__(self, big, medium, small):

self.slots = {1: big, 2: medium, 3: small}



def addCar(self, carType):



if self.slots[carType] == 0:

return False

else:

self.slots[carType] -= 1

return True

Submissions:

Reference:

https://leetcode.com/problems/design-parking-system/discuss/960876/Python3-Hashtable-implementation
Leetcode MySQL 627. Swap Salary
By: Sharko Shen
Tags: Leetcode

題目:

利用UPDATE 與 SET 將SEX的m與f互換。

SQL Schema

Given a table salary , such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update statement and no intermediate temp table.

Note that you must write a single update statement, DO NOT write any select statement for this problem.

Example:

| id | name | sex | salary |

|----|------|-----|--------|

| 1 | A | m | 2500 |

| 2 | B | f | 1500 |

| 3 | C | m | 5500 |

| 4 | D | f | 500 |

After running your update statement, the above salary table should have the following rows:

| id | name | sex | salary |

|----|------|-----|--------|

| 1 | A | f | 2500 |

| 2 | B | m | 1500 |

| 3 | C | f | 5500 |

| 4 | D | m | 500 |

思路:

UPDATE salary

SET sex=(IF sex="f","m","f")

如果sex是f，替換成m，原本不是f的，替換成f。

Coding:
Leetcode MySQL 601. Human Traffic of Stadium
By: Sharko Shen
Tags: Leetcode

題目:

給一個TABLE Stadium，找出至少連續三天，人數大於100的天數。

Write an SQL query to display the records with three or more rows with consecutive id 's, and the number of people is greater than or equal to 100 for each.

Return the result table ordered by visit_date in ascending order.

The query result format is in the following example.

Stadium table:

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

| id | visit_date | people |

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

| 1 | 2017-01-01 | 10 |

| 2 | 2017-01-02 | 109 |

| 3 | 2017-01-03 | 150 |

| 4 | 2017-01-04 | 99 |

| 5 | 2017-01-05 | 145 |

| 6 | 2017-01-06 | 1455 |

| 7 | 2017-01-07 | 199 |

| 8 | 2017-01-09 | 188 |

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

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

| id | visit_date | people |

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

| 5 | 2017-01-05 | 145 |

| 6 | 2017-01-06 | 1455 |

| 7 | 2017-01-07 | 199 |

| 8 | 2017-01-09 | 188 |

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

思路:

用三個表比較，人數至少都大於100，並且id是連續

比較tb1.id、tb2.id、tb3.id三者順序，列出三種情況，

(1,2,3) (2,1,3) (3,2,1) 並取distinct

Coding:

# Write your MySQL query statement below

SELECT distinct tb1.id as id, tb1.visit_date, tb1.people

FROM Stadium as tb1, Stadium as tb2, Stadium as tb3

WHERE (tb1.people >= 100 and tb2.people >= 100 and tb3.people >= 100) and

(

(tb1.id+1=tb2.id and tb1.id+2=tb3.id) or

(tb1.id-1=tb2.id and tb1.id+1=tb3.id) or

tb1.id-1=tb2.id and tb1.id-2=tb3.id

)

ORDER BY id

重點:

重點

1. 用三個表 比較id大小 因為至少要連續三天people大於100

2. 因此先三個表個至少people大於100，然後tb1.id 可能是最低 中間 最高的id

3. SELECT要記得distinct，最後要order by
JavaScript Algorithms: Merge intervals (LeetCode)
By: Anatolii Kurochkin
Tags: Leetcode, Data Structures, Interview, Algorithms, JavaScript

Description

Given an array of intervals where intervals[i] = [starti, endi] , merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]

Output: [[1,6],[8,10],[15,18]]

Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: intervals = [[1,4],[4,5]]

Output: [[1,5]]

Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Constraints:

1 <= intervals.length <= 104

intervals[i].length == 2

0 <= starti <= endi <= 104

Solution

In this problem, we can sort the intervals in advance and after that we can go through the sorted array and try to merge somehow these intervals. The key thing here is to come up with how we can merge the intervals.

An idea is pretty simple. We need to check if the current interval begins after the previous interval ends. We can easily check it because we’ve sorted the intervals .

The time complexity is O(nlogn) because of the sort, and space complexity is O(n) because we use result to store merged intervals .

I hope, it was useful for you. Thanks for reading! Looking forward to your feedback. See you soon ✌️
Leetcode MySQL 620. Not Boring Movies
By: Sharko Shen
Tags: Leetcode

題目:

找出奇數ID 描述不是"BORING”的名單。

X city opened a new cinema, many people would like to go to this cinema. The cinema also gives out a poster indicating the movies’ ratings and descriptions.

Please write a SQL query to output movies with an odd numbered ID and a description that is not ‘boring’. Order the result by rating.

For example, table cinema :

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

| id | movie | description | rating |

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

| 1 | War | great 3D | 8.9 |

| 2 | Science | fiction | 8.5 |

| 3 | irish | boring | 6.2 |

| 4 | Ice song | Fantacy | 8.6 |

| 5 | House card| Interesting| 9.1 |

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

For the example above, the output should be:

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

| id | movie | description | rating |

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

| 5 | House card| Interesting| 9.1 |

| 1 | War | great 3D | 8.9 |

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

思路:

奇偶數用mod判斷餘數，mod(id,2)=1 是奇數。

Coding:
Leetcode MySQL 595. Big Countries
By: Sharko Shen
Tags: Leetcode

題目:

給一個world table，用兩個條件，篩選area 跟 population。

There is a table World

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

| name | continent | area | population | gdp |

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

| Afghanistan | Asia | 652230 | 25500100 | 20343000 |

| Albania | Europe | 28748 | 2831741 | 12960000 |

| Algeria | Africa | 2381741 | 37100000 | 188681000 |

| Andorra | Europe | 468 | 78115 | 3712000 |

| Angola | Africa | 1246700 | 20609294 | 100990000 |

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

A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.

Write a SQL solution to output big countries’ name, population and area.

For example, according to the above table, we should output:

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

| name | population | area |

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

| Afghanistan | 25500100 | 652230 |

| Algeria | 37100000 | 2381741 |

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

Coding:
Leetcode 596. Classes More Than 5 Students
By: Sharko Shen
Tags: Leetcode

題目:

給一個courses的table，找出哪個科目學生人數大於5人。

SQL Schema

There is a table courses with columns: student and class

Please list out all classes which have more than or equal to 5 students.

For example, the table:

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

| student | class |

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

| A | Math |

| B | English |

| C | Math |

| D | Biology |

| E | Math |

| F | Computer |

| G | Math |

| H | Math |

| I | Math |

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

Should output:

+---------+

| class |

+---------+

| Math |

+---------+

Note:

The students should not be counted duplicate in each course.

思路:

重點: WHERE 在GROUP BY 之前，HAVING在GROUP BY 之後

SQL syntax running priority

FROM -> JOIN -> ON -> WHERE -> GROUP BY -> WITH -> HAVING -> SELECT -> DISTINCT -> ORDER BY

(1)FROM JOIN ON

(2)WHERE

(3)GROUP BY

(4)HAVING

(5)SELECT DISTINCT TOP()

(6)ORDER BY

Coding:
The kth Factor of n
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given two positive integers n and k .

A factor of an integer n is defined as an integer i where n % i == 0 .

Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.

Example 1:

Input: n = 12, k = 3

Output: 3

Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.

Example 2:

Input: n = 7, k = 2

Output: 7

Explanation: Factors list is [1, 7], the 2nd factor is 7.

Example 3:

Input: n = 4, k = 4

Output: -1

Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.

Example 4:

Input: n = 1, k = 1

Output: 1

Explanation: Factors list is [1], the 1st factor is 1.

Example 5:

Input: n = 1000, k = 3

Output: 4

Explanation: Factors list is [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000].

Constraints:

1 <= k <= n <= 1000

Check below blog for solution with explanation
Special Matrix II
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given a positive integer n , generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

Input: n = 3

Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

Input: n = 1

Output: [[1]]

Constraints:

1 <= n <= 20

For Solution with explanation, visit below link

For more problems with solution, programming tutorials refer here-
Leetcode 1679: Max Number of K-Sum Pairs
By: Pierre-Marie Poitevin
Tags: Leetcode, Interview, Algorithms, Java, Coding

In this Leetcode problem, we are given an array nums of integers. In one operation, we can take any pair of integers adding up to k and take it out of the array. We want to know the maximum number of operations that we can do following that rule.

For any number num in nums , it can only be paired with k — num for the sum to be equal to k . Then, for any number 1 ≤ p ≤ k — 1 , if we have the value p repeated x times in nums , and the value k — p repeated y times, we can form min(x,y) pairs using these 2 values, unless p and k — p are the same.

If k is pair, if the value k/2 is repeated x times in nums , we can only make x/2 pairs using these values. If we ignore this, and apply the same previous formula, min(x, x) , we will count twice as many pairs as needed.

However, we can notice that if we count the pair (p, k — p) , and later on count the pair (k — p, p) , we also will double the number of operations.

Therefore, in the algorithms, we will count all operations twice, by ignoring the special case of k/2 , and by counting the pairs (p, k - p) and (k — p, p) . We will only need to divide the result by 2 at the end.

To solve the problem, we count the number of occurrences of each 1 ≤ p < k , in a map count . Then for each key in the map we add

min(count.get(key), count.get(k — key))

to the final result. As explained before, doing this will exactly double the expected final result.

Here is the full Java solution:
Leetcod MySQL 197. Rising Temperature
By: Sharko Shen
Tags: Leetcode

題目:

給定一個Weather Table，列出日期與溫度，日期要比前一天溫度還高。

Table: Weather

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

| Column Name | Type |

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

| id | int |

| recordDate | date |

| temperature | int |

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

id is the primary key for this table.

This table contains information about the temperature in a certain day.

Write an SQL query to find all dates’ id with higher temperature compared to its previous dates (yesterday).

Return the result table in any order.

The query result format is in the following example:

Weather

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

| id | recordDate | Temperature |

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

| 1 | 2015-01-01 | 10 |

| 2 | 2015-01-02 | 25 |

| 3 | 2015-01-03 | 20 |

| 4 | 2015-01-04 | 30 |

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

+----+

| id |

+----+

| 2 |

| 4 |

+----+

In 2015-01-02, temperature was higher than the previous day (10 -> 25).

In 2015-01-04, temperature was higher than the previous day (30 -> 20).

思路:

1. 找高於前一天溫度的id

2. INNER JOIN

3. 兩個條件 日期前一天(用DATEDFF())、tb1溫度較高

4. 用WHERE 判斷哪個日期在後面

5. 這題比較特別的地方是在ON，以往都是等於，這題用到了大於跟AND

Coding:
[Leet Code] Subtract the Product and Sum of Digits of an Integer
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Leetcode: https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/

Problem:

Given an integer number n , return the difference between the product of its digits and the sum of its digits.

Example:

Input: n = 234

Output: 15

Explanation:

Product of digits = 2 * 3 * 4 = 24

Sum of digits = 2 + 3 + 4 = 9

Result = 24 - 9 = 15

Solution:

class Solution(object):

def subtractProductAndSum(self, n):

"""

:type n: int

:rtype: int

"""

product_of_digits = 0

sum_of_digits = 0



list_of_nums = list(str(n))

for v,i in enumerate(list_of_nums):

if v == 0:

product_of_digits = int(i)

else:

product_of_digits = product_of_digits * int(i)

sum_of_digits = sum_of_digits + int(i)



return product_of_digits - sum_of_digits

Explanation:

Create two variables, one to hold the balues of the product of the digits, and the other for the sum of the digits. Then we turn the string of numbers into a list. If we enumerate the list of nums, then we can check if the first index is 0, then we need to make the product the first number, otherwise it would always multiple by 0 for the first number. Then after that we can do the product multiplied by itself. Same for the digit, then we just return the product_of_digits minus sum_of_digits.
[LeetCode]#1678. Goal Parser Interpretation
By: Fatboy Slim
Tags: Leetcode, Leetcode Easy, Python, Algorithms, Python3

Environment: Python 3.7

Key technique: dictionary

You own a Goal Parser that can interpret a string command . The command consists of an alphabet of "G" , "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G" , "()" as the string "o" , and "(al)" as the string "al" . The interpreted strings are then concatenated in the original order.

Given the string command , return the Goal Parser's interpretation of command .

Example 1:

Input: command = "G()(al)"

Output: "Goal"

Explanation: The Goal Parser interprets the command as follows:

G -> G

() -> o

(al) -> al

The final concatenated result is "Goal".

Analysis:

Use a dictionary for checking every input. If match, output related answer. Combine all answer.

Solution:

class Solution:

def interpret(self, s):

check = {"(al)":"al", "()":"o","G":"G"}

t,ans ="",""

for i in range(len(s)):

t+=s[i]

if t in check:

ans+=check[t]

t="" return ans

Submissions:

Reference:

https://leetcode.com/problems/goal-parser-interpretation/discuss/961466/Python-Simple-solution-using-dictionary
Leetcode MySQL 262. Trips and Users
By: Sharko Shen
Tags: Leetcode

題目:

這題依照題目需求條件將名單列出。

The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are both foreign keys to the Users_Id at the Users table. Status is an ENUM type of (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’).

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

| Id | Client_Id | Driver_Id | City_Id | Status |Request_at|

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

| 1 | 1 | 10 | 1 | completed |2013-10-01|

| 2 | 2 | 11 | 1 | cancelled_by_driver|2013-10-01|

| 3 | 3 | 12 | 6 | completed |2013-10-01|

| 4 | 4 | 13 | 6 | cancelled_by_client|2013-10-01|

| 5 | 1 | 10 | 1 | completed |2013-10-02|

| 6 | 2 | 11 | 6 | completed |2013-10-02|

| 7 | 3 | 12 | 6 | completed |2013-10-02|

| 8 | 2 | 12 | 12 | completed |2013-10-03|

| 9 | 3 | 10 | 12 | completed |2013-10-03|

| 10 | 4 | 13 | 12 | cancelled_by_driver|2013-10-03|

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

The Users table holds all users. Each user has an unique Users_Id, and Role is an ENUM type of (‘client’, ‘driver’, ‘partner’).

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

| Users_Id | Banned | Role |

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

| 1 | No | client |

| 2 | Yes | client |

| 3 | No | client |

| 4 | No | client |

| 10 | No | driver |

| 11 | No | driver |

| 12 | No | driver |

| 13 | No | driver |

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

Write a SQL query to find the cancellation rate of requests made by unbanned users (both client and driver must be unbanned) between Oct 1, 2013 and Oct 3, 2013. The cancellation rate is computed by dividing the number of canceled (by client or driver) requests made by unbanned users by the total number of requests made by unbanned users.

For the above tables, your SQL query should return the following rows with the cancellation rate being rounded to two decimal places.

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

| Day | Cancellation Rate |

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

| 2013-10-01 | 0.33 |

| 2013-10-02 | 0.00 |

| 2013-10-03 | 0.50 |

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

思路:

# 條件很多

#重點:

#1. 用兩個INNER JOIN 對應 id: 找出client 中 unbanned，跟driver中 unbanned

#2. WHERE 時間範圍 用 BETWEEN 接著記得用GROUP BY

#3. 計算Cancellation Rate 用到(CASE WHEN THEN ELSE END)

#4. ORDER BY Day

#5. Cancellation Rate 要加引號 # #計算步驟

# #1.CASE WHEN

# CASE WHEN tb1.Status = "completed" THEN 0

# ELSE 1

# END # #2.加上SUM/COUNT

# SUM(CASE WHEN tb1.Status = "completed" THEN 0

# ELSE 1

# END) / COUNT(*) # #3. 取小數點後兩位 ROUND(...,2)

# ROUND(SUM(CASE WHEN tb1.Status = "completed" THEN 0

# ELSE 1

# END) / COUNT(*),2)

Coding:
Check whether two strings are anagram of each other or not
By: Sivareddy Uppathi
Tags: Leetcode, Competitive Programming, Geeksforgeeks

This the frequently asked question in FANG & All Top campiness.. solution in Java.

Approach-1: (By Using Sorting Method) : Time Complexity : O(nlog(n))

package chalanges.compitative; import java.util.Arrays;

*

*

*/

public class Anagram { /** @author SivaReddy Uppathi*/public class Anagram { public static void main(String[] args) {

char str1[] = {'s', 'i', 'v', 'a'};

char str2[] = {'s', 'v', 'a', 'i'}; boolean isAnagram = checkAnagramUsingSorting(str1, str2);

System.out.println(isAnagram); } private static boolean checkAnagramUsingSorting(char[] str1, char[] str2) {

if (str1.length != str2.length) {

return false;

}

Arrays.sort(str1);

Arrays.sort(str2);

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

if (str1[i] != str2[i]) {

return false;

}

}

return true;

}

}

Approach-2: (By Using 2 Char Arrays) : Time Complexity : O(n)

private static boolean checkAnagramByCharCount2Arrays(char[] str1, char[] str2) {

if (str1.length != str2.length) {

return false;

}

int count1[] = new int[256];

Arrays.fill(count1, 0);

int count2[] = new int[256];

Arrays.fill(count2, 0); for (int i = 0; i < str1.length; i++) {

count1[str1[i]]++;

count2[str2[i]]++;

} for (int i = 0; i < NO_OF_CHARS; i++) {

if (count1[i] != count2[i]) {

return false;

}

}

return true;

}

Approach-3: (By Using 1Char Array) : Time Complexity : O(n)

private static boolean checkAnagramByCharCount1Array(char[] str1, char[] str2) {

if (str1.length != str2.length) {

return false;

}

int[] count = new int[256];

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

count[str1[i] - 'a']++;

count[str2[i] - 'a']--;

}

for (int i = 0; i < NO_OF_CHARS; i++) {

if (count[i] != 0) {

return false;

}

}

return true;

}

Approach-4: (Taking sum) : Time Complexity : O(n) & Space: O(1)

This is the best way to solve this question

In first loop summing ASCII values of first string characters.

In second loop reducing the sum to wards zero by comparing with ASCII values of second string characters.

After completing two loops if count =0 means both strings are same so that we can conclude both are anagrams of each other.

If count !=0 then those two are not anagrams.
[C#][LeetCode]21. Merge Two Sorted Lists
Tags: Leetcode, C Sharp Programming, Linklist

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Leetcode MySQL 196. Delete Duplicate Emails
By: Sharko Shen
Tags: Leetcode

題目:

DELETE 相同的Email，留下小的Id。

Write a SQL query to delete all duplicate email entries in a table named Person , keeping only unique emails based on its smallest Id.

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

| Id | Email |

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

| 1 | john@example.com |

| 2 | bob@example.com |

| 3 | john@example.com |

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

Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:

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

| Id | Email |

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

| 1 | john@example.com |

| 2 | bob@example.com |

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

思路:

DELETE 的用法

DELET FROM table.name

WHERE [condition] 建立兩個相同表格tb1 tb2

在tb1中，把tb1,tb2同email 且tb1大於tb2 id 的部分刪除(因為這樣才會留下比較小的id)

Coding:
177. Nth Highest Salary Write a SQL query to get the nth highest salary from the Employee table. For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no…
By: Jen-Li Chen
Tags: Leetcode, Sql, MySQL, Solutions

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Leetcode MySQL 185. Department Top Three Salaries
By: Sharko Shen
Tags: Leetcode

題目:

列出各Department 中Salary 前三高的名單。

The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.

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

| Id | Name | Salary | DepartmentId |

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

| 1 | Joe | 85000 | 1 |

| 2 | Henry | 80000 | 2 |

| 3 | Sam | 60000 | 2 |

| 4 | Max | 90000 | 1 |

| 5 | Janet | 69000 | 1 |

| 6 | Randy | 85000 | 1 |

| 7 | Will | 70000 | 1 |

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

The Department table holds all departments of the company.

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

| Id | Name |

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

| 1 | IT |

| 2 | Sales |

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

Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows (order of rows does not matter).

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

| Department | Employee | Salary |

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

| IT | Max | 90000 |

| IT | Randy | 85000 |

| IT | Joe | 85000 |

| IT | Will | 70000 |

| Sales | Henry | 80000 |

| Sales | Sam | 60000 |

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

思路:

先用INNER JOIN對應department Id 要找出前三名，利用的方法是:

再多新增一個表格tb3，去count，tb3中，超過tb1 Salary個數在兩個以內

例如:

tb1中90000，在b3中超過90000的分數有0個，

tb1中85000，tb3中有1個salary超過

tb1中70000，在tb3中有2個超過

3. 利用WHERE篩選出來 ，不超過2個 (<3)

WHERE裡面SELECT的WHERE有兩個條件:

同部門

Salary較高

4. count注意要distinct 因為可能很多90000 或85000

Coding:
Number of Steps to Reduce a Number to 0 — LeetCode
By: Soren Rood
Tags: Leetcode, Leetcode Easy, Software Engineering, Software Development, Soren Rood

Number of Steps to Reduce a Number to 0 — LeetCode Soren Rood ·Dec 5, 2020

This question has been asked by Microsoft in the past 6 months:

This problem is solved by utilizing the modulus (%) operator. It is used to discover if our problem is even. If num % 2 == 0, it is an even number.

Here is my solution:

carbon.now.sh

All source code is located at my Github.

Links to all of my socials are here.
[Leet Code] Create Target Array in the Given Order
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Leetcode: https://leetcode.com/problems/create-target-array-in-the-given-order/

Problem:

Given two arrays of integers nums and index . Your task is to create target array under the following rules:

Initially target array is empty.

From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.

the value in target array. Repeat the previous step until there are no elements to read in nums and index.

Return the target array.

It is guaranteed that the insertion operations will be valid.

Example:

Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]

Output: [0,4,1,3,2]

Explanation:

nums index target

0 0 [0]

1 1 [0,1]

2 2 [0,1,2]

3 2 [0,1,3,2]

4 1 [0,4,1,3,2]

Solution:

class Solution(object):

def createTargetArray(self, nums, index):

"""

:type nums: List[int]

:type index: List[int]

:rtype: List[int]

"""



new_list = [None] * len(nums)

counter = 0

for i in index:

new_list.insert(i,nums[counter])

counter = counter + 1

return new_list[:-len(nums)]

We create a new list and fill it with None for the length of nums. Then we go through the indices in a for loop and insert at index the nums while incrementing counter. This will return a list like so:

[0,4,1,3,2,None,None,None,None,None]

so we return the answer minus the length of nums

therefore:
Reverse Integer
Tags: Leetcode, Leetcode Easy, Reverse Integer

My Solution

const reverse = (x) => {

let reverseX = parseInt(x.toString().split("").reverse().join(""));

let result = +reverseX;

if (x < 0 && -1 * result < Math.pow(-2, 31)) {

return 0;

} else if (x < 0) {

return (result *= -1);

}

if (result > Math.pow(2, 31) - 1) return 0;

return result;

};
Maximum Depth of a Binary Tree
By: Fellow Programmer
Tags: Leetcode, The Fellow Programmer, Java, Coding, Programming

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:

Input: root = [3,9,20,null,null,15,7]

Output: 3

Example 2:

Input: root = [1,null,2]

Output: 2

Example 3:

Input: root = []

Output: 0

Example 4:

Input: root = [0]

Output: 1

Constraints:
[LeetCode]#1672. Richest Customer Wealth
By: Fatboy Slim
Tags: Leetcode, Python3, Leetcode Easy, Python

Environment: Python 3.7

Key technique: for, max

You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th ​​​​ bank. Return the wealth that the richest customer has.

A customer’s wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.

Example 1:

Input: accounts = [[1,2,3],[3,2,1]]

Output: 6

Explanation:

1st customer has wealth = 1 + 2 + 3 = 6

2nd customer has wealth = 3 + 2 + 1 = 6

Both customers are considered the richest with a wealth of 6 each, so return 6.

Example 2:

Input: accounts = [[1,5],[7,3],[3,5]]

Output: 10

Explanation:

1st customer has wealth = 6

2nd customer has wealth = 10

3rd customer has wealth = 8

The 2nd customer is the richest with a wealth of 10.

Example 3:

Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]

Output: 17

Analysis:

Sum list a, b, c Find the largest one.

Solution:

class Solution:

def maximumWealth(self, accounts):

ans, curr= 0, 0

for i in accounts:

for j in i:

curr+=j

ans=max(ans,curr)

curr=0

return ans

Submissions:

Reference:

https://leetcode.com/problems/richest-customer-wealth/discuss/959863/Simple-Naive-Python-constant-space-O(1)
Merge Two Sorted Lists — LeetCode
By: Soren Rood
Tags: Leetcode, Computer Science, Leetcode Easy, Software Engineering, Software Development

In the past 6 months, this question has been asked by companies such as:

This one stumped me at first. I was not expecting a recursive solution. I had been trying to do it iteratively the entire time. You can do it iteratively, but it’s a lot more complicated than doing it recursively.

With the iterative solution, we only need to check the heads of both linked-lists. We do not even need to loop at all. We check if list1 or list2 is None. If either of them are None values, we return the other list. After the initial check, we check if list1.value < list2.value and if so, we set list1.next = self.mergeTwoLists(list1.next, list2). Basically sending everything but the head to mergeTwoLists() method. Doing this will recursively shorten the list until eventually one of the lists is == to None.

Here’s my code that solves this problem:

Snippet from carbon.now.sh

Here are the solution submission statistics:

All source code is located at my Github.

Links to all of my socials are here.
Leetcode MySQL 184. Department Highest Salary
By: Sharko Shen
Tags: Leetcode

題目:

列出在各部門薪水最高的名單。

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

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

| Id | Name | Salary | DepartmentId |

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

| 1 | Joe | 70000 | 1 |

| 2 | Jim | 90000 | 1 |

| 3 | Henry | 80000 | 2 |

| 4 | Sam | 60000 | 2 |

| 5 | Max | 90000 | 1 |

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

The Department table holds all departments of the company.

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

| Id | Name |

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

| 1 | IT |

| 2 | Sales |

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

Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter).

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

| Department | Employee | Salary |

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

| IT | Max | 90000 |

| IT | Jim | 90000 |

| Sales | Henry | 80000 |

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

思路:

1. LEFT JOIN tb1 跟 tb1

2. 重點是 WHERE ( columns name) IN (要選擇的值)

也就是WHERE (tb2.Id, tb1.Salary) IN ( 有ID 與 max(Salary) 的表格)

3. 這裡要放的值 是最高的薪水，因此用SELECT FROM再建造一個表格

SELECT id, max(salary)

FROM

GROUP BY id

Coding:
Leetcode SQL
By: Jen-Li Chen
Tags: Leetcode, Sql, Solutions

Leetcode SQL

185. Department Top Three Salaries

The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.

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

| Id | Name | Salary | DepartmentId |

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

| 1 | Joe | 85000 | 1 |

| 2 | Henry | 80000 | 2 |

| 3 | Sam | 60000 | 2 |

| 4 | Max | 90000 | 1 |

| 5 | Janet | 69000 | 1 |

| 6 | Randy | 85000 | 1 |

| 7 | Will | 70000 | 1 |

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

The Department table holds all departments of the company.

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

| Id | Name |

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

| 1 | IT |

| 2 | Sales |

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

Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows (order of rows does not matter).

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

| Department | Employee | Salary |

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

| IT | Max | 90000 |

| IT | Randy | 85000 |

| IT | Joe | 85000 |

| IT | Will | 70000 |

| Sales | Henry | 80000 |

| Sales | Sam | 60000 |

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

Explanation:

In IT department, Max earns the highest salary, both Randy and Joe earn the second highest salary, and Will earns the third highest salary. There are only two employees in the Sales department, Henry earns the highest salary while Sam earns the second highest salary.

Solution:

select d.Name as Department,

e.Name as Employee,

Salary

from Employee e

inner join

Department d

on e.DepartmentId = d.Id

where

(

select count(distinct Salary) from Employee t1

where t1.DepartmentId = d.Id

and t1.Salary >= e.Salary

) <= 3;

Link
Leetcode MySQL 183. Customers Who Never Order
By: Sharko Shen
Tags: Leetcode

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Leetcode 1353: Maximum Number of Events That Can Be Attended
By: Aaron Yan
Tags: Leetcode, Priority Queue, Python

Given an array of events where events[i] = [startDayi, endDayi] . Every event i starts at startDayi and ends at endDayi .

You can attend an event i at any day d where startTimei <= d <= endTimei. Notice that you can only attend one event at any time d .

Return the maximum number of events you can attend.
Median of Two Sorted Arrays(Leetcode)
By: Vipul Gupta
Tags: Leetcode, Coding, Arrays

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Follow up: The overall run time complexity should be O(log (m+n)) .

Example 1:

Input: nums1 = [1,3], nums2 = [2]

Output: 2.00000

Explanation: merged array = [1,2,3] and median is 2.

Example 2:

Input: nums1 = [1,2], nums2 = [3,4]

Output: 2.50000

Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

Example 3:

Input: nums1 = [0,0], nums2 = [0,0]

Output: 0.00000

Example 4:

Input: nums1 = [], nums2 = [1]

Output: 1.00000

Example 5:

Input: nums1 = [2], nums2 = []

Output: 2.00000

Constraints:

nums1.length == m

nums2.length == n

0 <= m <= 1000

0 <= n <= 1000

1 <= m + n <= 2000

-106 <= nums1[i], nums2[i] <= 106

class Solution {

public double findMedianSortedArrays(int[] nums1, int[] nums2) {



if(nums1.length>nums2.length){

return findMedianSortedArrays(nums2,nums1);

}

int x = nums1.length;

int y = nums2.length;



int low =0;

int high = x;



while(low<=high){

int partitionX = (low+high)/2;

int partitionY = (x+y+1)/2 - partitionX;



int maxLeftX = (partitionX == 0)?Integer.MIN_VALUE:nums1[partitionX-1];

int minRightX = ( partitionX == x)?Integer.MAX_VALUE:nums1[partitionX];



int maxLeftY = (partitionY == 0)?Integer.MIN_VALUE:nums2[partitionY-1];

int minRightY = (partitionY == y)?Integer.MAX_VALUE:nums2[partitionY];



if((maxLeftX<=minRightY) &&(maxLeftY<=minRightX)){

if((x+y)%2==0){

return (double)(Math.max(maxLeftX,maxLeftY)+Math.min(minRightX,minRightY))/2;

}else{

return (double)(Math.max(maxLeftX,maxLeftY));

}

}else if(maxLeftX>minRightY){

high=partitionX-1;

}else{

low=partitionX+1;

}



}

throw new IllegalArgumentException();

}

}

Thank you for Reading!!
Intersection Point of 2 LinkedList
By: Vipul Gupta
Tags: Leetcode, Coding, Singly Linked List

Write a program to find the node at which the intersection of two singly linked lists begins. (Leetcode : 160)

Two Linkedlist having 15 as intersection point.

class Node { int val; Node next; public Node() { } public Node(int val, Node next) { this.val = val; this.next = next; } } public class IntersectionPointOfLinkedLists { public static void main(String[] args) { Node node2 = new Node(10, new Node()); Node node = new Node(3, new Node()); node.next = new Node(6, new Node()); node.next.next = new Node(9, new Node()); node.next.next.next = new Node(15, new Node()); node2.next = node.next.next.next; node.next.next.next.next = new Node(30, null); Node node = findIntersection(node, node2);

System.out.println(node.val); } public static Node findIntersection(Node node1, Node node2) { int len1 = getCount(node1); int len2 = getCount(node2); Node interSectionPoint = null; if (len1 > len2) { return interSectionPoint = getIntersection(node1, node2, len1 - len2); } else { return interSectionPoint = getIntersection(node2, node1, len2 - len1); } } public static int getIntersection(Node node1, Node node2, int d) { int count = 0; while (count != d) { node1 = node1.next; count++; } while (node1 != null && node2 != null) { if (node1 == node2) { return node1.val; } else { node1 = node1.next; node2 = node2.next; } }

return null; //throw new IllegalArgumentException(); } public static int getCount(Node node) { int len = 0; while (node != null) { // System.out.print(node.val + " "); node = node.next; len++; } return len; } }

Thank you for reading!!
Two Sum
Tags: Leetcode, Two Sum, Leetcode Easy

Two Sum

Problem

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.

Example 1:

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

Output: [0,1]

Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

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

Output: [1,2]

Example 3:

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

Output: [0,1]

Constraints:
[Leet Code] Missing Number
By: Matthew Boyd
Tags: Leetcode, Leetcode Easy, Data Structures, Algorithms, Leetcode Solution

Leetcode: https://leetcode.com/problems/missing-number/submissions/

Problem:

Given an array nums containing n distinct numbers in the range [0, n] , return the only number in the range that is missing from the array. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

Example:

Input: nums = [3,0,1]

Output: 2

Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Input: nums = [0,1]

Output: 2

Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.

Solution:

class Solution(object):

def missingNumber(self, nums):

"""

:type nums: List[int]

:rtype: int

"""



length = len(nums) + 1

for i in range(length):

if i not in nums:

return i

Explanation:

First we get the length of the list, then we add 1 to this list as that will give us all numbers included in the sequence. Then we check if the number at i is in nums, if not, return i.
This is the first day to challenge the Leet Code Problem!
Tags: Leetcode, Challenge

This is the first day to challenge the Leet Code Problem!

I don’t know what to say…but I just try my best to finish this hard sh**!!

So, this is the declaration of my goal of the Leet Code!

I am going to solve 1 hard level / 10 medium level / 100 easy level problems of leet code for the next 6 months.

Plus, will post about my experience here on how to solve problems.

So, again, I don’t know what to say…but I want to prove to myself that I can do this.

So let’s see what is gonna coming up next!
Leetcode MySQL 180. Consecutive Numbers
By: Sharko Shen
Tags: Leetcode

題目: 找出連續三次出現的數字

Write a SQL query to find all numbers that appear at least three times consecutively.

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

| Id | Num |

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

| 1 | 1 |

| 2 | 1 |

| 3 | 1 |

| 4 | 2 |

| 5 | 1 |

| 6 | 2 |

| 7 | 2 |

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

For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.

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

| ConsecutiveNums |

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

| 1 |

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

思路:

比較三個同樣的表格tb1 tb2 tb3，

兩種條件: 連續三個數字、值要相同。

Coding:

# Write your MySQL query statement below

SELECT distinct tb1.Num as ConsecutiveNums

FROM Logs as tb1, Logs as tb2, Logs as tb3

WHERE tb1.Id + 1 = tb2.ID AND tb2.Id + 1 = tb3.Id AND tb1.Num = tb2.Num AND tb2.Num = tb3.Num

Select 要記的distinct 因為可能有連續四個數字出現一樣，那output就會出現兩次。
[C#][LeetCode]19. Remove Nth Node From End of List
Tags: Leetcode, Linklist, C Sharp Programming

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
LeetCode — 983. Minimum Cost For Tickets
By: Cheng-Che Hsieh
Tags: Leetcode, Midium, Algorithms, Swift

1. The Problem

In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days . Each day is an integer from 1 to 365 . Train tickets are sold in 3 different ways: a 1-day pass is sold for costs[0] dollars; a 7-day pass is sold for costs[1] dollars; a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8. Return the minimum number of dollars you need to travel every day in the given list of days .

Example 1:

Input: days = [1,4,6,7,8,20], costs = [2,7,15]

Output: 11

Explanation:

For example, here is one way to buy passes that lets you travel your travel plan:

On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.

On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.

On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.

In total you spent $11 and covered all the days of your travel.

Example 2:

Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]

Output: 17

Explanation:

For example, here is one way to buy passes that lets you travel your travel plan:

On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.

On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.

In total you spent $17 and covered all the days of your travel.

Note:

1 <= days.length <= 365 1 <= days[i] <= 365 days is in strictly increasing order. costs.length == 3 1 <= costs[i] <= 1000

2. Description

To calculate how mach is the minimum spend for all trips. “Days” is the numbers like you are supposed to go on those days. There are three kinds of tickets to choose. Find the cheapest cost to cover all travel days.

3. Needs Attention

Because it can be inputed any values of cost, it won’t be the specific rank for all tickets. cost:[1, 50, 100] is also possible. To calculate the rate in cost is unrealistic. Can allow multiple sets if and the only if the cost is the same.

4. Values recommendation

Cost is not in the reasonable price. Ex. cost: [1,50,100], [100,101,102] Don’t follow the cost which is only 1-day < 7-day < 30-Day. Ex. [7,2,6]

5. Reference Code (Beats 91.67%, 8ms)

“travelRecord”: To record all days. False represents the days we are not planning to travel, true means yes.

“costRecord”: The money we have spent so far in that day. Begin from 0.

Walk though all the days. If travelRecord is false, copy the cost to the next day. (means doesn’t spend any at that day). If it’s true, we need to buy a ticket to travel then we have three choices:

A 1-day ticket: The cost yesterday add the cost today(cost[0]). A 7-day ticket: If i-7≤0 no need to pay extra tee. Add cost[1] after 7 days A 30-Day ticket: The same as 7-Day.

“costRecord” inserts the minimum cost.
Leetcode 1670: Design Front Middle Back Queue
By: Pierre-Marie Poitevin
Tags: Leetcode, Data Structures, Algorithms, Java, Coding

In this Leetcode problem, we are implementing a Queue from from with we can push and pop from the front, back, or middle.

Problem statement

Solution

Obviously, the pop and push from the middle are the core of the problem. Otherwise we could use a LinkedList.

To solve this problem, we break up the linked list into 2 linked lists. We split it in the middle, so that it is easier when we need to push or pop from the middle.

Now, the lists can become unbalanced, so we ensure that after each operations, the lists have the same sizes, or differ by 1 only, and if the sizes differ by one, then the back list is the bigger list.

So, we rebalance after each operation to ensure this is always the case.

Here is the implementation for rebalancing:

private void balance() {

if (front.size() == back.size()) {

return;

}

if (front.size() > back.size()) {

frontToBack();

}

if (front.size() < back.size() - 1) {

backToFront();

}

}



private void frontToBack() {

back.addFirst(front.removeLast());

} private void backToFront() {

front.addLast(back.removeFirst());

}

All the push operations are then implemented very simply:

public void pushFront(int val) {

front.addFirst(val);

balance();

}



public void pushMiddle(int val) {

front.addLast(val);

balance();

}



public void pushBack(int val) {

back.addLast(val);

balance();

}

Popping is also quite simple, but we need 2 remember and take into account 2 things:

The list might be empty in which case we return -1

The front list might be empty while the back list has 1 element, which means we need to take the element from the back in popFront() .

Here is the full implementation:

class FrontMiddleBackQueue { LinkedList<Integer> front = new LinkedList<>();

LinkedList<Integer> back = new LinkedList<>();



public FrontMiddleBackQueue() {

}



public void pushFront(int val) {

front.addFirst(val);

balance();

}



public void pushMiddle(int val) {

front.addLast(val);

balance();

}



public void pushBack(int val) {

back.addLast(val);

balance();

}



public int popFront() {

int v;

if (front.size() == 0) {

if (back.size() == 0) {

return -1;

} else {

v = back.removeFirst();

}

} else {

v = front.removeFirst();

}

balance();

return v;

}



public int popMiddle() {

int v;

if (front.size() == back.size()) {

if (front.size() == 0) {

return -1;

}

v = front.removeLast();

} else {

v = back.removeFirst();

}

balance();

return v;

}



public int popBack() {

if (back.size() == 0) {

return -1;

}

int v = back.removeLast();

balance();

return v;

}



private void balance() {

if (front.size() == back.size()) {

return;

}

if (front.size() > back.size()) {

frontToBack();

}

if (front.size() < back.size() - 1) {

backToFront();

}

}



private void frontToBack() {

back.addFirst(front.removeLast());

} private void backToFront() {

front.addLast(back.removeFirst());

}

}

All operations are O(1), in particular because rebalancing involves at most one element switching between front and back.