Skip to content

Added Leetcode September challenge Questions #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions LeetCode/September Challenge/best_time_to_sell_and_buy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
121. Best Time to Buy and Sell Stock
------------------------------------
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.

Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
"""

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit = 0
min_price = float('inf')

for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
37 changes: 37 additions & 0 deletions LeetCode/September Challenge/bulls_and_cows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""
299. Bulls and Cows
-------------------
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.
Please note that both secret number and friend's guess may contain duplicate digits.

Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.

Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
"""

class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""

bulls = 0

for idx, char in enumerate(secret):
if char == guess[idx]:
bulls+=1

cows = 0

cows = sum((Counter(secret)&Counter(guess)).values()) - bulls

return str(bulls) + "A" + str(cows) + "B"
48 changes: 48 additions & 0 deletions LeetCode/September Challenge/car_pooling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
Car Pooling
-----------
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.

Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false

Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true

Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true

Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
"""

class Solution(object):
def carPooling(self, trips, capacity):
"""
:type trips: List[List[int]]
:type capacity: int
:rtype: bool
"""
time = []

for trip in trips:
time.append([trip[1], trip[0]])
time.append([trip[2], - trip[0]])

time.sort()

total_passengers_at_a_time = 0

for ele in time:
total_passengers_at_a_time+=ele[1]
if total_passengers_at_a_time > capacity:
return False

return True

53 changes: 53 additions & 0 deletions LeetCode/September Challenge/compare_version_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.

Example 1:
Input: version1 = "0.1", version2 = "1.1"
Output: -1

Example 2:
Input: version1 = "1.0.1", version2 = "1"
Output: 1

Example 3:
Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1

Example 4:
Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1”

Example 5:
Input: version1 = "1.0", version2 = "1.0.0"
Output: 0
Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0"


Note:
Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes.
Version strings do not start or end with dots, and they will not be two consecutive dots.
"""
class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
versions1 = version1.split(".")
versions2 = version2.split(".")
for i in range(max(len(versions1),len(versions2))):
v1 = int(versions1[i]) if i < len(versions1) else 0
v2 = int(versions2[i]) if i < len(versions2) else 0
if v1 > v2:
return 1
elif v1 <v2:
return -1
return 0

39 changes: 39 additions & 0 deletions LeetCode/September Challenge/house_robber.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
198. House Robber
-----------------
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.


Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 400
"""
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

prev, cur = 0, 0
for house in nums:
cur, prev = max(prev + house, cur), cur
return cur

"""
Runtime: 16 ms, faster than 90.05% of Python online submissions for House Robber.
Memory Usage: 12.6 MB, less than 95.99% of Python online submissions for House Robber.
"""
41 changes: 41 additions & 0 deletions LeetCode/September Challenge/insert_interval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
57. Insert Interval
-------------------
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.

Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
"""
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
ans = []
idx = -1

for idx, (x,y) in enumerate(intervals):
if y < newInterval[0]:
ans.append([x,y])
elif newInterval[1] < x:
idx-=1
break
else:
newInterval[0] = min(newInterval[0], x)
newInterval[1] = max(newInterval[1], y)

return ans + [newInterval] + intervals[idx+1:]

"""
Runtime: 56 ms, faster than 96.90% of Python online submissions for Insert Interval.
Memory Usage: 16.2 MB, less than 31.60% of Python online submissions for Insert Interval.
"""
34 changes: 34 additions & 0 deletions LeetCode/September Challenge/larget_time_for_given_digits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
949. Largest Time for Given Digits

Given an array of 4 digits, return the largest 24 hour time that can be made.
The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
Return the answer as a string of length 5. If no valid time can be made, return an empty string.

Example 1:
Input: [1,2,3,4]
Output: "23:41"
"""
class Solution(object):
def largestTimeFromDigits(self, A):
"""
:type A: List[int]
:rtype: str
"""
max_time = -1
for h, i, j, k in itertools.permutations(A):
hour = h*10 + i
minute = j*10 + k
if hour < 24 and minute < 60:
max_time = max(max_time, hour * 60 + minute)

if max_time == -1:
return ""
else:
return "{:02d}:{:02d}".format(max_time // 60, max_time % 60)


"""
Runtime: 24 ms, faster than 79.77% of Python online submissions for Largest Time for Given Digits.
Memory Usage: 12.8 MB, less than 42.75% of Python online submissions for Largest Time for Given Digits.
"""
32 changes: 32 additions & 0 deletions LeetCode/September Challenge/length_of_last_word.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""
Length of Last Word
-------------------
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:
Input: "Hello World"
Output: 5
"""

class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""

s = s.split(' ')


i = len(s) - 1

while i>=0:
if str(s[i]) == '':
pass
else:
return len(s[i])
i-=1

return 0
35 changes: 35 additions & 0 deletions LeetCode/September Challenge/partition_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
"""
class Solution(object):
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
ans = []
lastIndex = {}
for idx, char in enumerate(S):
lastIndex[char] = idx
start = end = 0

for idx, char in enumerate(S):
end = max(end, lastIndex[char])
if idx == end:
ans.append(idx - start + 1)
start = idx + 1

return ans

"""
Runtime: 20 ms, faster than 98.32% of Python online submissions for Partition Labels.
Memory Usage: 12.7 MB, less than 83.64% of Python online submissions for Partition Labels.
"""
Loading