Skip to content

Commit 7f8b56c

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 6, 12, 13, 14, 28, 42, 58, 68, 134, 135, 151, 238, 274 and 380
1 parent d5e402d commit 7f8b56c

29 files changed

+768
-0
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,27 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
2626

2727
- [1 Two Sum](https://leetcode.com/problems/two-sum/description/)
2828
- [2 Add Two Numbers](https://leetcode.com/problems/add-two-numbers/description/)
29+
- [6 Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion/description/)
30+
- [12 Integer to Roman](https://leetcode.com/problems/integer-to-roman/description/)
31+
- [13 Roman to Integer](https://leetcode.com/problems/roman-to-integer/description/)
32+
- [14 Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/description/)
2933
- [19 Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/)
3034
- [20 Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)
3135
- [21 Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/)
3236
- [25 Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/description/)
3337
- [26 Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
3438
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
39+
- [28 Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/)
40+
- [42 Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/description/)
3541
- [45 Jump Game II](https://leetcode.com/problems/jump-game-ii/description/)
3642
- [49 Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)
3743
- [55 Jump Game](https://leetcode.com/problems/jump-game/description/)
44+
- [58 Length of Last Word](https://leetcode.com/problems/length-of-last-word/description/)
3845
- [56 Merge Intervals](https://leetcode.com/problems/merge-intervals/description/)
3946
- [57 Insert Interval](https://leetcode.com/problems/insert-interval/description/)
4047
- [61 Rotate List](https://leetcode.com/problems/rotate-list/description/)
4148
- [67 Add Binary](https://leetcode.com/problems/add-binary/description/)
49+
- [68 Text Justification](https://leetcode.com/problems/text-justification/description/)
4250
- [71 Simplify Path](https://leetcode.com/problems/simplify-path/description/)
4351
- [80 Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/)
4452
- [82 Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/)
@@ -65,12 +73,15 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
6573
- [129 Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/description/)
6674
- [130 Surrounded Regions](https://leetcode.com/problems/surrounded-regions/description/)
6775
- [133 Clone Graph](https://leetcode.com/problems/clone-graph/description/)
76+
- [134 Gas Station](https://leetcode.com/problems/gas-station/description/)
77+
- [135 Candy](https://leetcode.com/problems/candy/description/)
6878
- [136 Single Number](https://leetcode.com/problems/single-number/description/)
6979
- [137 Single Number II](https://leetcode.com/problems/single-number-ii/description/)
7080
- [138 Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/description/)
7181
- [141 Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/description/)
7282
- [146 LRU Cache](https://leetcode.com/problems/lru-cache/description/)
7383
- [150 Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/)
84+
- [151 Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/description/)
7485
- [155 Min Stack](https://leetcode.com/problems/min-stack/description/)
7586
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
7687
- [173 Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/description/)
@@ -92,8 +103,11 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
92103
- [228 Summary Ranges](https://leetcode.com/problems/summary-ranges/description/)
93104
- [230 Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/)
94105
- [236 Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/)
106+
- [238 Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/description/)
95107
- [242 Valid Anagram](https://leetcode.com/problems/valid-anagram/description/)
108+
- [274 H-Index](https://leetcode.com/problems/h-index/description/)
96109
- [290 Word Pattern](https://leetcode.com/problems/word-pattern/description/)
110+
- [380 Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/description/)
97111
- [383 Ransom Note](https://leetcode.com/problems/ransom-note/description/)
98112
- [392 Is Subsequence](https://leetcode.com/problems/is-subsequence/description/)
99113
- [399 Evaluate Division](https://leetcode.com/problems/evaluate-division/description/)
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution:
2+
"""Base class for all LeetCode Problems."""
3+
4+
def intToRoman(self, num: int) -> str:
5+
"""
6+
Seven different symbols represent Roman numerals with the following values:
7+
8+
Symbol Value
9+
I 1
10+
V 5
11+
X 10
12+
L 50
13+
C 100
14+
D 500
15+
M 1000
16+
17+
Roman numerals are formed by appending the conversions of decimal place values
18+
from highest to lowest. Converting a decimal place value into a Roman numeral
19+
has the following rules:
20+
- If the value does not start with 4 or 9, select the symbol of the maximal
21+
value that can be subtracted from the input, append that symbol to the result,
22+
subtract its value, and convert the remainder to a Roman numeral.
23+
- If the value starts with 4 or 9 use the subtractive form representing one
24+
symbol subtracted from the following symbol, for example, 4 is 1 (I) less than
25+
5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive
26+
forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).
27+
- Only powers of 10 (I, X, C, M) can be appended consecutively at most 3 times
28+
to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D)
29+
multiple times. If you need to append a symbol 4 times use the subtractive form.
30+
31+
Given an integer, convert it to a Roman numeral.
32+
"""
33+
itr = {
34+
1: "I",
35+
4: "IV",
36+
5: "V",
37+
9: "IX",
38+
10: "X",
39+
40: "XL",
40+
50: "L",
41+
90: "XC",
42+
100: "C",
43+
400: "CD",
44+
500: "D",
45+
900: "CM",
46+
1000: "M",
47+
}
48+
roman = ""
49+
for key in reversed(itr):
50+
num_symbols = num // key
51+
if num_symbols == 0:
52+
continue
53+
roman += num_symbols * itr[key]
54+
num = num - num_symbols * key
55+
return roman
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
8+
"""
9+
There are n gas stations along a circular route, where the amount of gas at the
10+
ith station is gas[i].
11+
12+
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel
13+
from the ith station to its next (i + 1)th station. You begin the journey with
14+
an empty tank at one of the gas stations.
15+
16+
Given two integer arrays gas and cost, return the starting gas station's index
17+
if you can travel around the circuit once in the clockwise direction, otherwise
18+
return -1. If there exists a solution, it is guaranteed to be unique.
19+
"""
20+
if sum(gas) < sum(cost):
21+
return -1
22+
23+
res = 0
24+
total = 0
25+
for i in range(len(gas)):
26+
total += gas[i] - cost[i]
27+
if total < 0:
28+
total = 0
29+
res = i + 1
30+
return res
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def candy(self, ratings: List[int]) -> int:
8+
"""
9+
There are n children standing in a line. Each child is assigned a rating value
10+
given in the integer array ratings.
11+
12+
You are giving candies to these children subjected to the following
13+
requirements:
14+
- Each child must have at least one candy.
15+
- Children with a higher rating get more candies than their neighbors.
16+
- Return the minimum number of candies you need to have to distribute the
17+
candies to the children.
18+
"""
19+
candy = [1 for i in range(len(ratings))]
20+
21+
# From left to right
22+
for i in range(1, len(ratings)):
23+
if ratings[i] > ratings[i - 1]:
24+
candy[i] = max(candy[i], candy[i - 1]) + 1
25+
26+
# From right to left
27+
for i in range(len(ratings) - 2, -1, -1):
28+
if ratings[i] > ratings[i + 1] and candy[i] <= candy[i + 1]:
29+
candy[i] = max(candy[i], candy[i + 1]) + 1
30+
return sum(candy)
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution:
2+
"""Base class for all LeetCode Problems."""
3+
4+
def romanToInt(self, s: str) -> int:
5+
"""
6+
Roman numerals are represented by seven different symbols: I, V, X, L, C, D
7+
and M.
8+
9+
Symbol Value
10+
I 1
11+
V 5
12+
X 10
13+
L 50
14+
C 100
15+
D 500
16+
M 1000
17+
18+
For example, 2 is written as II in Roman numeral, just two ones added together.
19+
12 is written as XII, which is simply X + II. The number 27 is written as
20+
XXVII, which is XX + V + II.
21+
22+
Roman numerals are usually written largest to smallest from left to right.
23+
However, the numeral for four is not IIII. Instead, the number four is written
24+
as IV. Because the one is before the five we subtract it making four. The same
25+
principle applies to the number nine, which is written as IX. There are six
26+
instances where subtraction is used:
27+
- I can be placed before V (5) and X (10) to make 4 and 9.
28+
- X can be placed before L (50) and C (100) to make 40 and 90.
29+
- C can be placed before D (500) and M (1000) to make 400 and 900.
30+
31+
Given a roman numeral, convert it to an integer.
32+
"""
33+
rti = {
34+
"I": 1,
35+
"V": 5,
36+
"X": 10,
37+
"L": 50,
38+
"C": 100,
39+
"D": 500,
40+
"M": 1000,
41+
}
42+
before, total = None, 0
43+
for r in reversed(s):
44+
if not before:
45+
total += rti[r]
46+
elif (before, r) in [
47+
("V", "I"),
48+
("X", "I"),
49+
("L", "X"),
50+
("C", "X"),
51+
("D", "C"),
52+
("M", "C"),
53+
]:
54+
total -= rti[r]
55+
else:
56+
total += rti[r]
57+
before = r
58+
return total
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def longestCommonPrefix(self, strs: List[str]) -> str:
8+
"""
9+
Write a function to find the longest common prefix string amongst an array of
10+
strings.
11+
12+
If there is no common prefix, return an empty string "".
13+
"""
14+
prefix = ""
15+
for i, c in enumerate(strs[0]):
16+
for s in strs:
17+
if i >= len(s) or s[i] != c:
18+
return prefix
19+
prefix += c
20+
return prefix
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
"""Base class for all LeetCode Problems."""
3+
4+
def reverseWords(self, s: str) -> str:
5+
"""
6+
Given an input string s, reverse the order of the words.
7+
8+
A word is defined as a sequence of non-space characters. The words in s will be
9+
separated by at least one space.
10+
11+
Return a string of the words in reverse order concatenated by a single space.
12+
13+
Note that s may contain leading or trailing spaces or multiple spaces between
14+
two words. The returned string should only have a single space separating the
15+
words. Do not include any extra spaces.
16+
"""
17+
return " ".join(reversed(s.split()))
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def productExceptSelf(self, nums: List[int]) -> List[int]:
8+
"""
9+
Given an integer array nums, return an array answer such that answer[i] is
10+
equal to the product of all the elements of nums except nums[i].
11+
12+
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit
13+
integer.
14+
15+
You must write an algorithm that runs in O(n) time and without using the
16+
division operation.
17+
"""
18+
result = []
19+
prefix = 1
20+
for i in range(len(nums)):
21+
result.append(prefix)
22+
prefix *= nums[i]
23+
24+
suffix = 1
25+
for i in range(len(nums) - 1, -1, -1):
26+
result[i] *= suffix
27+
suffix *= nums[i]
28+
29+
return result
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import collections
2+
from typing import List
3+
4+
5+
class Solution:
6+
"""Base class for all LeetCode Problems."""
7+
8+
def hIndex(self, citations: List[int]) -> int:
9+
"""
10+
Given an array of integers citations where citations[i] is the number of
11+
citations a researcher received for their ith paper, return the researcher's
12+
h-index.
13+
14+
According to the definition of h-index on Wikipedia: The h-index is defined as
15+
the maximum value of h such that the given researcher has published at least h
16+
papers that have each been cited at least h times.
17+
"""
18+
# Sort citations by number of papers
19+
n = len(citations)
20+
count = collections.defaultdict(int)
21+
for i, val in enumerate(citations):
22+
index = min(val, n)
23+
count[index] += 1
24+
25+
# Find index h that have at least h paper with more than h citations
26+
num_paper = 0
27+
for h_index in range(n, -1, -1):
28+
num_paper += count[h_index]
29+
if num_paper >= h_index:
30+
return h_index
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
"""Base class for all LeetCode Problems."""
3+
4+
def strStr(self, haystack: str, needle: str) -> int:
5+
"""
6+
Given two strings needle and haystack, return the index of the first occurrence
7+
of needle in haystack, or -1 if needle is not part of haystack.
8+
"""
9+
return haystack.find(needle)

0 commit comments

Comments
 (0)