Dec 01, 2023-present
Trying to solve all the coding problems for this year's Advent of Code!
Third problem done!
Second problem done!
First problem done!
Nov 11, 2023-present
Part of the O.S.S. team.
Got organised and got started with debugging.
First meeting!
Excited to see where this goes!
Aug 01, 2023-present
Continuing this breath-taking journey in AI safety (the research part being with my brother). Please see my notebook as well!
Waiting for a work trial, in the meanwhile check this out!
Something big might have just happened...
Applied to ~two more opportunities!
Applied to two more opportunities!
That question led to a really helpful call today!
Asked a question.
Wrote a lot!
Going to focus on policy following my brother's article, which ties in nicely with an essay I wish to write.
Finished with VAEs and a bit of GAN understanding.
Programming started for VAEs!
Read up on VAEs and Sparse Coding, and had another meeting.
Happy to report that this recently completed project was not a one-off AI safety project, I'll be continuing with self-studying and research with my brother. Super excited!
Mar 22, 2023-present
Became the vice head boy of my school. Trying to the best job I can. Also, environment club work (head of events) and another project (summary for that will come in May 2023)
What a month. Summary forthcoming!
College fair!
Brown is quite a nice colour.
Don't be a donkey.
(also, EcoGen flash mob!)
College. TEDx. Entrance.
All colours are beautiful.
Grading.
Everything. In. Between.
Everything in between!
Oh, it was.
The 5th is going to be an exciting day!
This has been the most productive week ever for this project: so, so much done.
Well, that was a productive summer!
Comprehensive enough?
2 years?!
The notebook is quite filled.
Lot's of work: organised the grading for junior classes along with another head, sent out a comprehensive guide for English proficiency tests and continued with some projects on the side.
Lots of smaller, but important work! (pt. 2)
Lots of smaller, but important work!
Cubing was an interesting part of my life.
Proud Head of Events day!
Got word of permission for a project (which also leads to something pretty important)!
It's hard to describe the work that's been going on, but it is certainly something..
A lot of progress, but I hate forms.
Had a call and got a good amount of work in.
2 hour long meeting! Was fun (and productive).
So, much, environment, work.
Tech FTW!
Helped to get a message out.
Jackets!
Did some organisational work.
Got it done.
Did some organisational work, lots of work for this week!
Polls!
Checklist!
Done (for now).
Much smoother, in a way.
Still a bit left, but got the video fixed (yay!)
All done (soon).
Nearly (or fully?) done with a lot of smaller projects for this.
Got a lot of work done for both projects. Really happy!
Cameraman, anyone? Also, won best speaker for a motion in a debate, and lots of environment work.
Did some (really^3 important) organisational work.
Did some (really, really important) organisational work.
Did some (really important!) organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work and a lot of writing for a proposal.
Did some organisational work and a morning event.
Did some organisational work and partook in a successful morning event.
Got some important messages + a template out yesterday.
Incredible day.
Got a speech ready and many rehersals (my knee can atest) done + dance was conducted somewhat successfully and an awesome Instagram post.
Worked on a video, event should go smoothly for tomorrow and day after.
Sorted out a technical issue + got content/photos for a post idea that I came up with! (worked on the main document a bit as well)
Did some organisational work.
Got a lot of work and recording done for an event.
Communication is key.
Did a lot of organisational work and generally, got a lot done!
Had a fruitful discussion with the design team!
Finished a document and getting some ideas for EC!
Lots of voting and discussions - but we're done with colour scheme.
Sent out the video draft (that another person worked on!) for the event in May and helped to sort out a mini-crisis.
Did some organisational work.
Had a productive meeting for event in May.
Top 6 now - also need to get better videos tomorrow...
Compiled the top 8. Waiting for results (+ more democracy!). Also, (a pretty fun but productive) meeting for event in May.
Colour - so trivial yet so important. Also, all applications are now sorted (EC)
Worked on compiling designs and setting up voting, and also contacted someone.
Summary of Environment Club (EC) Work: Will merge this log with this one. After my student council work in 11th, I mostly just had meetings, an application form for this academic year (which I finished) and a run!
Did some organisational work.
Finished initial organising work and informed a section of the council about an upcoming task.
Jan 04, 2023-present
Became part of OptX, my school's student-led initiative to provide opportunities to the youth. Trying to the best job I can.
Discussions are getting serious now.
Innovation wall + meeting!
RMC is officially over! Congrats to the winn... never mind.
Emails!
AC (x2)! Also, kind chap on the phone today.
Who turned off the AC?
Reel making competition is over now, a really sick reel was made by committee for India's independence day!
OptX astronomy centre visit happened successfully! Thank you to our incredible tour guides and to all those that had come!
Yes, mind?
Never mind.
Astronomy!
Hm. This is an interesting fork in the road. At least there's kulfi.
Might need to concoct up something tomorrow, also, progress on a smaller event!
Somnething quite fun might be coming soon....
Launched!
Competition should be launched by the end of today...
Meeting!
A discussion may or may not have occurred.
An interesting thing might be coming up after this competition!
Sent the guidelines.
Really productive day, a certain social media competition coming soon!
Messages!
Got some discussions in.
Emails!
Got the discussion rolling again.
Had a really important meeting with a lawyer!
Got some really important discussions in.
Did some organisational work.
Conducted more research.
Discussed about (a) moot.
Did some organisational work.
Did some organisational work.
Followed on with a lead.
Got some leads (and sent out a template)!
Did some organisational work.
Had some interesting discussions.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Really successful meeting!
Did some organisational work.
Breakthrough! (x2)
Breakthrough!
Follow-up, follow-up...
Finished sending out the certificates.
Sent some really important messages.
Got back from a contact.
Still finalizing certificates...
Worked on finalizing the certificates and gave some feedback for the reel.
Oh, it happened alright! It was a massive success, thank you to everyone who attended!
Everything seems to be in place...
First event in some time coming up very soon!
One of our smaller events had a lot of progress happen pretty spontaneously, and sent out an important message.
Did some organisational work and had a productive meeting.
Did some organisational work.
Did some organisational work, had a productive-ish meeting and got some more great advice!
Did some organisational work and got some great advice!
Had a productive meeting.
Re-scheduled a meeting.
Did some organisational work and had a meeting.
Did some organisational work.
Did the arithmetic mean of organisational work between Mar 22, 2023 and Mar 24, 2023.
Did a lot of organisational work.
Did some organisational work.
Did some organisational work.
Had two meetings and did some organisational work.
Did some organisational work.
Volunteered with OptX + two other students for Bridges of Giving. An incredibly fulfilling experience to say the least.
Did a lot of organisational work. Really productive day for this project!
Did some organisational work.
Had a productive meeting and did some organisational work.
Did some organisational work.
Another meeting - wrapped up the discussion (mostly) for this year's plan and organised the Notion accordingly.
Had a fruitful dinner meeting!
Had a productive conversation!
Discussed next meeting.
Well, I initially thought that I would just be a volunteer for OptX's The Symposium 1.0, but roughly a day before the event (Jan 07, 2023), I became one of the newest committee member. In the end, The Symposium 1.0 was an incredible success. Seeing it all unfold was one of the greatest moments in my life.
Dec 29, 2022-present
A cold email led to me and another person co-founding EA UAE. Trying to make this as successful as possible.
Should hopefully get more activity in the GC soon...
Discussion time!
Getting back into the swing of things.
Some, uh, interesting discussions...
Met with a professor virtually with my co-founder!
DYH!
New logo, new event!
Wrote up everything that I learnt, and we're back on track!
Finally met the EA NYUAD folk, an amazing dinner, thank you to all who attended!
Abu Dhabi, any one?
Progress! Then, a snafu, then progress!
Further discussion, and found a suitable compromise.
Incredible day(s): got the new set of logos (which look amazing) and a lot of headway on our next big thing!
Some admin work.
Gathertown!
Sent out the comprehensive message.
Airtable!
Solid progress.
Airtable are close to being fully up! Expecting a big splash sooner or later.
Got some discussions in with my co-founder + some organisational work.
All the plans are out and we're working on something important now!
Drafted a document.
Finished the plans for the non-outreach projects!
Finished my EA organiser application!
Got started with the next steps. Emails, Asana, oh my!
Follow-up to the meeting last week: was somewhat productive!
Lots of behind-the-scene work: emails and docs.
Really fruitful meeting!
Got a discussion going upon sending a EA Forum post.
Meeting scheduled!
Continued with my tasks assigned to me.
Learnt something interesting!
Got started with the next steps.
Had the most productive meeting yet! Really excited to get a lot of work done for this project over the summer.
Did some organisational work.
Webinar was a moderate success, and sent out some important messages!
Outreach, in the literal definition of the word.
Some really great news about our webinar!
Oddly, a lot of work for this project today.
Sent out message(s).
Did some organisational work.
Did some organisational work.
Did some organisational work. Going to go ahead with outreach + social media work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Successful meeting!
Got a meeting mostly organised.
Sent an email.
Did some organisational work.
Got a Graphic Designer on board!
Had a productive meeting and thinking about the next meet-up.
Our first event happened on Apr 10, 2023!
Did some organisational work (we might get a graphic designer on board!)
I think we're good to go!
Got the poster and form out - going to check the situation tomorrow and (mostly regardless) finalize everything.
Did some organisational work.
Postponed - but it'll happen.
I think we have a winner, folks...
Did some organisational work.
Did some organisational work - closing in on the actual booking.
Did some organisational work.
Short-listed the restaurant!
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Did some organisational work.
Communication work and a meeting with EA NYUAD!
Finished meeting notes for yesterday's introductory meeting.
Had a stellar meeting with EA AUS for our introductory meeting!
Did some organisational work.
We've scheduled the introductory meeting for Saturday. Hope to see everyone there soon!
Had a great discussion with the executive board and got the introduction meeting date and time mostly sorted out.
Did some organisational work.
Did some organisational work.
Got a great meeting and some communication in!
Did some organisational work for tomorrow.
Did some organisational work.
Scheduled a meeting.
Did some organisational work and replied to an email.
Did some organisational work. Instagram page is much more lively now!
Did some organisational work.
Did some organisational work.
Had two productive meetings.
Had a productive meeting.
Sent out the Airtable and, in general, got a lot of work done for this project!
For now, finished with Airtable.
Figured out how to get data for Airtable and got started with a post.
Had a productive meeting!
Sent out a message.
Sent out an important email.
Still working with Airtable.
Worked with Airtable.
I think cold emails are an incredibly powerful tool that must be used responsibly. Before this, I thought that I was the "king of cold emails", as it led to the Effective Altruism Data and LPP project. However, I got dethroned when someone cold emailed after seeing this EA Forum question that I wrote quite some time back.
What was originally me being pessimistic about re-starting EA Dubai led to meetings with EA AUS, EA NYUAD and even an advisor from CEA! So far, we've gotten some EA AUS and EA NYUAD members to join us - and we're on the look out for someone else to help lead this project with us! I'm really excited to see where this project is after exactly half a year (July 14, 2023)!
Nov 13, 2021-present
Trying to do a problem every day. All of the general problems are done in Python.
class Solution:
def matrixSum(self, nums: List[List[int]]) -> int:
count = len(nums[0])
score = 0
while count > 0:
numbers = []
for i in range(len(nums)):
numbers.append(max(nums[i]))
nums[i].remove(max(nums[i]))
score += max(numbers)
count -= 1
return score
import pandas as pd
def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame:
employees['salary'] = employees['salary'] * 2
return employees
class Solution:
def beautifulSubstrings(self, s: str, k: int) -> int:
# Credit - https://leetcode.com/problems/count-beautiful-substrings-i/solutions/4330501/readable-python-solution/
beautiful_count = 0
vowels_list = ['a','e','i','o','u']
for i in range(len(s)):
vowels, consonants = 0 , 0
j = i
while j < len(s):
if s[j] in vowels_list:
vowels += 1
else:
consonants += 1
if vowels == consonants and (vowels * consonants) % k == 0:
beautiful_count += 1
j += 1
return beautiful_count
class Solution:
def areSimilar(self, mat: List[List[int]], k: int) -> bool:
# Credit - https://leetcode.com/problems/matrix-similarity-after-cyclic-shifts/solutions/4330359/python-easy-solution/
k %= len(mat[0])
for m in mat:
if m != m[k:] + m[:k]:
return False
return True
class Solution:
def findWordsContaining(self, words: List[str], x: str) -> List[int]:
return [i for i in range(len(words)) if x in words[i]]
# Write your MySQL query statement below
# Credit - https://leetcode.com/problems/rearrange-products-table/solutions/3853137/simple-mysql-solution-using-union/
SELECT product_id, 'store1' AS store, store1 AS price FROM Products WHERE store1 IS NOT NULL
UNION
SELECT product_id, 'store2' AS store, store2 AS price FROM Products WHERE store2 IS NOT NULL
UNION
SELECT product_id, 'store3' AS store, store3 AS price FROM Products WHERE store3 IS NOT NULL;
class Solution:
def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:
import numpy as np
grid = np.array(grid)
diff = []
for i in range(len(grid)):
arr = []
for j in range(len(grid[0])):
arr.append(np.sum(grid[i]) + np.sum(grid[:, j]) - np.sum(1 - grid[i]) - np.sum(1 - grid[:, j]))
diff.append(arr)
return diff
# Write your MySQL query statement below
# Credit - https://leetcode.com/problems/market-analysis-i/solutions/2319471/simple-in-depth-explanation-of-where-and-is-null/
SELECT u.user_id as buyer_id, u.join_date, COUNT(o.order_id) AS orders_in_2019 FROM Users u LEFT JOIN Orders o ON o.buyer_id = u.user_id AND YEAR(order_date) = '2019' GROUP BY u.user_id;
# Write your MySQL query statement below
SELECT activity_date AS day, COUNT(DISTINCT user_id) as active_users FROM Activity GROUP BY day HAVING COUNT(DISTINCT user_id) > 0 AND day >= '2019-06-28' AND day <= '2019-07-27';
# Write your MySQL query statement below
SELECT DISTINCT event_day as day, emp_id, (SELECT SUM(out_time - in_time) FROM Employees WHERE event_day = e.event_day and emp_id = e.emp_id) as total_time FROM Employees e;
class Solution:
def countValidWords(self, sentence: str) -> int:
count = 0
for i in sentence.split():
if i.count('-') <= 1:
if i[-1].isalpha() or i[-1] == "!" or i[-1] == ',' or i[-1] == ".":
letter_count = 0
for j in range(len(i) - 1):
if i[j].isalpha():
letter_count += 1
elif i[j] == "-":
if j != 0 and j != len(i) - 1:
if i[j-1].isalpha() and i[j+1].isalpha():
letter_count += 1
if letter_count == len(i) - 1:
count += 1
return count
class Solution:
def maximumStrongPairXor(self, nums: List[int]) -> int:
max = 0
for i in range(len(nums)):
for j in range(len(nums)):
if abs(nums[i] - nums[j]) <= min(nums[i], nums[j]):
if nums[i]^nums[j] >= max:
max = nums[i]^nums[j]
return max
class Solution:
def findChampion(self, grid: List[List[int]]) -> int:
max_ones = max([i.count(1) for i in grid])
for i in range(len(grid)):
if grid[i].count(1) == max_ones:
return i
import pandas as pd
def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
animals = animals[animals['weight'] > 100]
animals.sort_values(by=['weight'], inplace=True, ascending=False)
del animals['species']
del animals['age']
del animals['weight']
return animals
import pandas as pd
def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
employees['bonus'] = [i*2 for i in employees['salary']]
return employees
class Solution:
def findKOr(self, nums: List[int], k: int) -> int:
# Credit - https://leetcode.com/problems/find-the-k-or-of-an-array/solutions/4220565/python-simple-solution/
res = 0
for i in range(32):
count = 0
n = 2**i
for num in nums:
if num & n:
count += 1
if count >= k:
res += n
return res
class Solution:
def sumCounts(self, nums: List[int]) -> int:
total = 0
for i in range(len(nums)):
for j in range(len(nums)+1):
total += (len(set(nums[i:j])))**2
return total
import pandas as pd
def selectData(students: pd.DataFrame) -> pd.DataFrame:
return students[students["student_id"] == 101].loc[:, students.columns != 'student_id']
import pandas as pd
def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees.head(3)
class Solution:
def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:
for i in range(len(nums)):
for j in range(len(nums)):
if abs(i - j) >= indexDifference and abs(nums[i] - nums[j]) >= valueDifference:
return [i, j]
return [-1, -1]
class Solution:
def lastVisitedIntegers(self, words: List[str]) -> List[int]:
integers = []
res = []
count = 0
for i in words:
if i == "prev":
count += 1
temp = integers[::-1]
if count <= len(integers):
res.append(temp[count - 1])
else:
res.append(-1)
else:
count = 0
integers.append(int(i))
return res
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
return sum([i for i in range(1, n+1) if i % m != 0]) - sum([i for i in range(1, n+1) if i % m == 0])
import pandas as pd
def getDataframeSize(players: pd.DataFrame) -> List[int]:
return [len(players.axes[0]), len(players.axes[1])]
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
max_value = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
for k in range(j+1, len(nums)):
if ((nums[i] - nums[j]) * nums[k]) > max_value:
max_value = ((nums[i] - nums[j]) * nums[k])
return max_value
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
def check(k, arr):
for i in range(1, k+1):
if i not in arr:
return False
return True
collection = []
count = 0
while not check(k, collection):
collection.append(nums[-1])
nums = nums[:-1]
count += 1
return count
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
indices = [i for i in range(len(nums)) if nums[i] == 1]
for i in range(1, len(indices)):
if (indices[i] - indices[i-1]) - 1 < k:
return False
return True
class Solution:
def maximumOddBinaryNumber(self, s: str) -> str:
ones = s.count("1")
zeroes = s.count("0")
if ones == 1:
return "0"*zeroes + "1"
else:
return "1"*(ones-1) + "0"*zeroes + "1"
class Solution:
def minOperations(self, logs: List[str]) -> int:
level = 0
for i in logs:
if i == "../":
if level != 0:
level -= 1
elif i != "./":
level += 1
return level
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if s in t:
return True
for i in s:
if i not in t:
return False
compare = ""
for i in t:
if i in s:
compare += i
if list(dict.fromkeys(compare)) == list(dict.fromkeys(s)) and len(compare) >= len(s):
return True
class Solution:
def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
return sum([nums[i] for i in range(len(nums)) if str(bin(i))[1:].count('1') == k])
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
odd_nos = [i for i in nums if i % 2 != 0]
even_nos = [i for i in nums if i % 2 == 0]
res = []
even_counter = 0
odd_counter = 0
for i in range(len(nums)):
if i % 2 == 0:
res.append(even_nos[even_counter])
even_counter += 1
else:
res.append(odd_nos[odd_counter])
odd_counter += 1
return res
class Solution:
def numberOfPoints(self, nums: List[List[int]]) -> int:
points = set()
for i in nums:
for j in range(i[0], i[1]+1):
points.add(j)
return len(points)
class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
count = 0
for i in range(low, high+1):
if len(str(i)) % 2 == 0:
if sum([int(i) for i in str(i)[:len(str(i)) // 2]]) == sum([int(i) for i in str(i)[len(str(i)) // 2:]]):
count += 1
return count
/**
* @param {Promise} promise1
* @param {Promise} promise2
* @return {Promise}
*/
var addTwoPromises = async function (promise1, promise2) {
return new Promise(function (resolve, reject) {
promise1
.then(function (result1) {
promise2
.then(function (result2) {
resolve(result1 + result2);
})
.catch(function (error) {
reject(error);
});
})
.catch(function (error) {
reject(error);
});
});
};
/**
* addTwoPromises(Promise.resolve(2), Promise.resolve(2))
* .then(console.log); // 4
*/
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
res = []
for i in range(len(nums)):
res.insert(index[i], nums[i])
return res
# Write your MySQL query statement below
SELECT DISTINCT s.user_id, CASE WHEN ISNULL(ROUND((SELECT COUNT(*) FROM Confirmations WHERE user_id = s.user_id AND action = 'confirmed') / (SELECT COUNT(*) FROM Confirmations WHERE user_id = s.user_id), 2)) THEN 0.00 ELSE ROUND((SELECT COUNT(*) FROM Confirmations WHERE user_id = s.user_id AND action = 'confirmed') / (SELECT COUNT(*) FROM Confirmations WHERE user_id = s.user_id), 2) END AS confirmation_rate FROM Signups s LEFT JOIN Confirmations c ON s.user_id = c.user_id;
class Solution:
def countPairs(self, nums: List[int], target: int) -> int:
count = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] < target:
count += 1
return count
class Solution:
def countPairs(self, nums: List[int], target: int) -> int:
count = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] < target:
count += 1
return count
class Solution:
def numberOfLines(self, widths: List[int], s: str) -> List[int]:
widths_dict = {chr(i):widths[i-97] for i in range(97, 123)}
lines = 1
width_count = 0
for i in s:
if width_count + widths_dict[i] > 100:
width_count = 0
lines += 1
width_count += widths_dict[i]
return [lines, width_count]
# Write your MySQL query statement below
SELECT DISTINCT p.product_id, product_name FROM Product p, Sales s WHERE p.product_id = s.product_id AND (SELECT COUNT(product_id) FROM Sales e WHERE e.product_id = p.product_id AND (e.sale_date >= '2019-01-01' AND e.sale_date <= '2019-03-31')) >= 1 AND (SELECT COUNT(product_id) FROM Sales e WHERE e.product_id = p.product_id AND (e.sale_date < '2019-01-01' OR e.sale_date > '2019-03-31')) = 0;
# Write your MySQL query statement below
# Credit - https://leetcode.com/problems/count-salary-categories/solutions/3892510/beats-95-both-sql-and-pandas/
SELECT 'Low Salary' as category, COUNT(account_id) as accounts_count FROM Accounts WHERE income < 20000 UNION SELECT 'Average Salary' as category, COUNT(*) FROM Accounts WHERE income >= 20000 AND income <= 50000 UNION SELECT 'High Salary' as category, COUNT(*) FROM Accounts WHERE income > 50000;
# Write your MySQL query statement below
SELECT user_id, MAX(time_stamp) as last_stamp FROM Logins WHERE SUBSTRING(time_stamp, 1, 4) = '2020' GROUP BY user_id;
class Solution:
def hIndex(self, citations: List[int]) -> int:
if len(citations) == 1:
if citations[0] == 0:
return 0
else:
return 1
else:
max_h = 0
for h in range(0, len(citations)+1):
if len([i for i in citations if i >= h]) >= h and h > max_h:
max_h = h
return max_h
# Write your MySQL query statement below
# Credit - https://leetcode.com/problems/average-time-of-process-per-machine/solutions/3722056/sql-join-or-subquery-easy-to-understand/
SELECT a.machine_id, ROUND(AVG(b.timestamp-a.timestamp), 3) as processing_time FROM Activity a JOIN Activity b ON a.machine_id=b.machine_id AND a.process_id=b.process_id AND a.activity_type='start' AND b.activity_type='end' GROUP BY a.machine_id
# Write your MySQL query statement below
SELECT DISTINCT a.stock_name, ((SELECT SUM(price) FROM Stocks WHERE operation = 'Sell' AND stock_name = a.stock_name) - (SELECT SUM(price) FROM Stocks WHERE operation = 'Buy' AND stock_name = a.stock_name)) as capital_gain_loss FROM Stocks a;
class Solution:
def maxSum(self, nums: List[int]) -> int:
max_sum = -1
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if max(list(str(nums[i]))) == max(list(str(nums[j]))):
if nums[i] + nums[j] > max_sum:
max_sum = nums[i] + nums[j]
return max_sum
# Write your MySQL query statement below
SELECT DISTINCT a.actor_id, a.director_id FROM ActorDirector a WHERE (SELECT COUNT(*) FROM ActorDirector WHERE actor_id = a.actor_id AND director_id = a.director_id) >= 3;
# Write your MySQL query statement below
SELECT DISTINCT date_id, make_name, (SELECT COUNT(DISTINCT lead_id) FROM DailySales WHERE date_id = d.date_id AND make_name = d.make_name) AS unique_leads, (SELECT COUNT(DISTINCT partner_id) FROM DailySales WHERE date_id = d.date_id AND make_name = d.make_name) AS unique_partners FROM DailySales d ORDER BY date_id;
# Write your MySQL query statement below
SELECT tweet_id FROM Tweets WHERE LENGTH(content) > 15;
class Solution:
def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
remainder = purchaseAmount % 10
if remainder == 0:
return 100 - purchaseAmount
elif remainder < 5:
return 100 - (purchaseAmount - remainder)
else:
return 100 - (purchaseAmount + (10 - remainder))
class Solution:
def search(self, nums: List[int], target: int) -> int:
try:
return nums.index(target)
except:
return -1
class Solution:
def finalString(self, s: str) -> str:
res = ""
for i in s:
if i != "i":
res += i
else:
res = res[::-1]
return res
# Write your MySQL query statement below
SELECT employee_id, name, (SELECT COUNT(*) FROM Employees WHERE reports_to = e.employee_id) AS reports_count, ROUND((SELECT SUM(age) FROM Employees WHERE reports_to = e.employee_id) / (SELECT COUNT(*) FROM Employees WHERE reports_to = e.employee_id)) AS average_age FROM Employees e WHERE (SELECT COUNT(*) FROM Employees WHERE reports_to = e.employee_id) >= 1 ORDER BY employee_id;
# Write your MySQL query statement below
SELECT COUNT(DISTINCT customer_id) AS rich_count FROM Store WHERE amount > 500;
# Write your MySQL query statement below
SELECT user_id, CONCAT(UCASE(SUBSTR(name, 1, 1)), LCASE(SUBSTR(name, 2, LENGTH(name)))) as name FROM Users ORDER BY user_id;
# Write your MySQL query statement below
SELECT unique_id, name FROM Employees e LEFT JOIN EmployeeUNI u ON e.id = u.id;
# Write your MySQL query statement below
SELECT contest_id, ROUND(COUNT(*) / (SELECT COUNT(*) FROM Users) * 100, 2) AS percentage FROM Users u, Register r WHERE u.user_id = r.user_id GROUP BY contest_id ORDER BY percentage DESC, contest_id ASC;
# Write your MySQL query statement below
SELECT ROUND((SELECT COUNT(*) FROM Delivery d WHERE d.order_date = d.customer_pref_delivery_date AND d.order_date = (SELECT MIN(order_date) FROM Delivery WHERE customer_id = d.customer_id)) / COUNT(DISTINCT customer_id) * 100, 2) as immediate_percentage FROM Delivery;
# Write your MySQL query statement below
SELECT ROUND((SELECT COUNT(*) FROM Delivery WHERE order_date=customer_pref_delivery_date) / COUNT(*) * 100, 2) AS immediate_percentage FROM Delivery;
class Solution:
def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
return len([i for i in hours if i >= target])
# Write your MySQL query statement below
SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(DISTINCT product_key) FROM Product);
# Write your MySQL query statement below
SELECT name, bonus FROM Employee e LEFT JOIN Bonus b ON e.empId = b.empId WHERE bonus < 1000 OR ISNULL(bonus);
# Write your MySQL query statement below
SELECT name, IFNULL(SUM(distance), 0) as travelled_distance FROM Users u LEFT JOIN Rides r ON u.id = r.user_id GROUP BY u.id ORDER BY travelled_distance DESC, name;
class Solution:
def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
words_new = []
for i in words:
words_new.extend(i.split(separator))
return [i for i in words_new if len(i) > 0]
# Write your MySQL query statement below
SELECT sell_date, COUNT(DISTINCT product) AS num_sold, GROUP_CONCAT(DISTINCT product ORDER BY product) AS products FROM Activities GROUP BY sell_date;
# Write your MySQL query statement below
SELECT DISTINCT user_id, (SELECT COUNT(user_id) FROM Followers WHERE user_id = f.user_id) as followers_count FROM Followers f ORDER BY user_id;
class Solution:
def isGood(self, nums: List[int]) -> bool:
return sorted(nums) == [i for i in range(1, len(nums))] + [len(nums)-1]
# Write your MySQL query statement below
SELECT product_name, year, price as price FROM Sales NATURAL JOIN Product ORDER BY product_name;
# Write your MySQL query statement below
SELECT MAX(e.num) as num FROM MyNumbers e WHERE (SELECT COUNT(num) FROM MyNumbers WHERE num=e.num) = 1;
# Write your MySQL query statement below
SELECT name FROM Employee e WHERE (SELECT COUNT(d.managerId) FROM Employee d WHERE d.managerId = e.id) >= 5;
# Write your MySQL query statement below
SELECT id FROM Weather w WHERE temperature > (SELECT temperature FROM Weather WHERE recordDate=DATE_SUB(w.recordDate, INTERVAL 1 DAY));
# Write your MySQL query statement below
# Credit - https://leetcode.com/problems/reformat-department-table/solutions/2473482/fully-explained-super-easy/
SELECT d.id, SUM(IF(month='Jan', revenue, null)) as Jan_Revenue, SUM(IF(month='Feb', revenue, null)) as Feb_Revenue, SUM(IF(month='Mar', revenue, null)) as Mar_Revenue, SUM(IF(month='Apr', revenue, null)) as Apr_Revenue, SUM(IF(month='May', revenue, null)) as May_Revenue, SUM(IF(month='Jun', revenue, null)) as Jun_Revenue, SUM(IF(month='Jul', revenue, null)) as Jul_Revenue, SUM(IF(month='Aug', revenue, null)) as Aug_Revenue, SUM(IF(month='Sep', revenue, null)) as Sep_Revenue, SUM(IF(month='Oct', revenue, null)) as Oct_Revenue, SUM(IF(month='Nov', revenue, null)) as Nov_Revenue, SUM(IF(month='Dec', revenue, null)) as Dec_Revenue from Department d GROUP BY id;
class Solution:
def sumOfSquares(self, nums: List[int]) -> int:
return sum([nums[i]**2 for i in range(len(nums)) if len(nums) % (i+1) == 0])
# Write your MySQL query statement below
SELECT MAX(salary) as SecondHighestSalary FROM Employee WHERE salary != (SELECT MAX(salary) FROM Employee);
# Write your MySQL query statement below
SELECT ROUND(SUM(tiv_2016), 2) as tiv_2016 FROM Insurance i WHERE (SELECT COUNT(tiv_2015) FROM Insurance e WHERE e.tiv_2015 = i.tiv_2015) > 1 AND (SELECT COUNT(lat) FROM Insurance e WHERE e.lat = i.lat AND e.lon = i.lon) = 1;
# Write your MySQL query statement below
SELECT name, SUM(amount) as balance FROM Users NATURAL JOIN Transactions GROUP BY account HAVING SUM(amount) > 10000;
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five_bills = 0
ten_bills = 0
twenty_bills = 0
for i in bills:
if i == 5:
five_bills += 1
elif i == 10:
if five_bills > 0:
ten_bills += 1
five_bills -= 1
else:
return False
elif i == 20:
if five_bills > 0 and ten_bills > 0:
twenty_bills += 1
ten_bills -= 1
five_bills -= 1
elif five_bills > 2:
twenty_bills += 1
five_bills -= 3
else:
return False
return True
class Solution:
def cellsInRange(self, s: str) -> List[str]:
letter_1 = s[0]
number_1 = s[1]
letter_2 = s[3]
number_2 = s[4]
letters = []
numbers = []
for i in range(ord(letter_1), ord(letter_2)+1):
letters.append(chr(i))
for i in range(int(number_1), int(number_2)+1):
numbers.append(i)
res = []
for i in letters:
for j in numbers:
res.append(i + str(j))
return res
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + (2*t)
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
characters = s.split('-')
characters = "".join([i.upper() for i in characters])
num_chars = len(s) - s.count('-')
groups = num_chars // k
remainder = num_chars % k
res = ""
if remainder == 0:
for i in range(0, num_chars, k):
res += characters[i:i+k] + '-'
res = res[:-1]
else:
res += characters[:remainder] + '-'
for i in range(remainder, num_chars, k):
res += characters[i:i+k] + '-'
res = res[:-1]
return res
# Write your MySQL query statement below
SELECT x, y, z,
CASE
WHEN ((x+y) > z AND (y+z) > x AND (x+z) >y) THEN 'Yes'
ELSE 'No'
END as triangle
FROM Triangle;
# Write your MySQL query statement below
SELECT player_id, MIN(event_date) as first_login FROM Activity GROUP BY player_id;
# Write your MySQL query statement below
UPDATE Salary SET sex = CASE WHEN sex = 'f' THEN 'm'
WHEN sex = 'm' THEN 'f'
END;
# Write your MySQL query statement below
SELECT project_id, ROUND(SUM(experience_years) / COUNT(name), 2) AS average_years FROM Project NATURAL JOIN Employee GROUP BY project_id;
# Write your MySQL query statement below
SELECT DISTINCT product_name, (SELECT SUM(unit) FROM Orders o WHERE o.product_id = p.product_id AND MONTH(order_date) = 2) as unit FROM Products p, Orders o WHERE p.product_id = o.product_id AND (SELECT SUM(unit) FROM Orders o WHERE o.product_id = p.product_id AND MONTH(order_date) = 2) >= 100;
# Write your MySQL query statement below
SELECT p.product_id, ROUND(SUM(p.price * u.units) / SUM(u.units), 2) as average_price FROM UnitsSold u, Prices p WHERE u.product_id = p.product_id AND u.purchase_date BETWEEN p.start_date AND p.end_date GROUP BY u.product_id;
class Solution:
def countTriples(self, n: int) -> int:
def count(n, li=1):
if n == 1 or n == 2 or n == 3 or n == 4:
return 0
count_i = 0
for i in range(li, n+1):
for j in range(i+1, n+1):
if (i**2) + (j**2) == n**2:
count_i += 1
return (count_i*2) + count(n-1, last_i)
return count(n)
# Write your MySQL query statement below
SELECT s.student_id, student_name, su.subject_name, (SELECT COUNT(*) FROM Examinations e WHERE e.student_id = s.student_id AND e.subject_name = su.subject_name) as attended_exams FROM Students s JOIN Subjects su ORDER BY student_id, subject_name;
# Write your MySQL query statement below
SELECT a.employee_id FROM Employees a WHERE (SELECT COUNT(employee_id) FROM Employees WHERE employee_id = a.manager_id) = 0 AND a.salary < 30000 AND a.manager_id IS NOT NULL ORDER BY employee_id;
# Write your MySQL query statement below
SELECT a.query_name, ROUND(AVG(a.rating / a.position), 2) as quality, ROUND(((SELECT COUNT(b.query_name) FROM Queries b WHERE rating < 3 AND a.query_name = b.query_name) / COUNT(a.query_name)) * 100, 2) as poor_query_percentage FROM Queries a GROUP BY a.query_name;
/**
* @param {string} val
* @return {Object}
*/
var expect = function(val) {
var val_1 = val;
return {
toBe: (val_2) => {
if (val_1 === val_2) {
return true;
} else {
throw "Not Equal";
}
},
notToBe: (val_2) => {
if (val !== val_2) {
return true;
} else {
throw "Equal";
}
}
}
};
/**
* expect(5).toBe(5); // true
* expect(5).notToBe(5); // throws "Equal"
*/
class Solution:
def diStringMatch(self, s: str) -> List[int]:
n = len(s)
lst = []
min = 0
max = n
for i in s:
if i == 'I':
lst.append(min)
min += 1
elif i == "D":
lst.append(max)
max -= 1
return lst + [min]
class Solution:
def countBeautifulPairs(self, nums: List[int]) -> int:
import math
count = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if math.gcd(int(str(nums[i])[0]), int(str(nums[j])[-1])) == 1:
count += 1
return count
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
count = 0
for i in range(len(words)):
for j in range(i+1, len(words)):
if words[i][::-1] == words[j]:
count += 1
return count
class Solution:
def trimMean(self, arr: List[int]) -> float:
# Credit - https://leetcode.com/problems/mean-of-array-after-removing-some-elements/solutions/2344789/python-short-simple/
percentile = (5*len(arr)) // 100
arr.sort()
return sum(arr[percentile:len(arr)-percentile]) / (len(arr)-(percentile*2))
class Solution:
def distanceTraveled(self, mainTank: int, additionalTank: int) -> int:
dist = 0
while mainTank > 0:
if mainTank >= 5 and additionalTank >= 1:
dist += 50
mainTank -= 4
additionalTank -= 1
else:
dist += 10
mainTank -= 1
return dist
class Solution:
def numberOfMatches(self, n: int) -> int:
total_matches = 0
while n > 1:
if n % 2 == 0:
total_matches += (n // 2)
n = n // 2
else:
total_matches += (n - 1) // 2
n = ((n - 1) // 2) + 1
return total_matches
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
if k == 0:
return [0]*len(code)
else:
code_modified = code*(abs(k)+1)
if k > 0:
return [sum(code_modified[i+1:i+1+k]) for i in range(len(code))]
else:
return [sum(code_modified[-len(code)+k+i:-len(code)+i]) for i in range(len(code))]
class Solution:
def findNonMinOrMax(self, nums: List[int]) -> int:
nums = [i for i in nums if i != min(nums) and i != max(nums)]
if len(nums) == 0:
return -1
else:
return nums[0]
class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
import numpy as np
grid = np.array(grid)
count = 0
for i in range(len(grid)):
for j in range(len(grid)):
if np.array_equal(grid[i], grid[:, j]):
count += 1
return count
class Solution:
def isFascinating(self, n: int) -> bool:
return sorted(str(n) + str(2*n) + str(3*n)) == ['1', '2', '3', '4', '5', '6', '7', '8', '9']
class Solution:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
dict_boxes = {}
for i in range(lowLimit, highLimit+1):
if sum([int(i) for i in list(str(i))]) in dict_boxes:
dict_boxes[sum([int(i) for i in list(str(i))])] += 1
else:
dict_boxes[sum([int(i) for i in list(str(i))])] = 1
return dict_boxes[max(dict_boxes, key=dict_boxes.get)]
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
return words == sorted(words, key=lambda word: [order.index(word[i]) for i in range(len(word))])
/**
* @param {Object | Array} obj
* @return {boolean}
*/
var isEmpty = function (obj) {
let count = 0;
for (let key in obj) {
count++;
}
return count == 0;
};
class Solution:
def minimizedStringLength(self, s: str) -> int:
return len(set(s))
/**
* @return {Generator<number>}
*/
var fibGenerator = function* () {
let start_value = -1;
let next_value = 1;
let value = start_value;
while (true) {
value = start_value + next_value;
start_value = next_value;
next_value = value;
yield next_value;
}
};
/**
* const gen = fibGenerator();
* gen.next().value; // 0
* gen.next().value; // 1
*/
class Solution:
def specialArray(self, nums: List[int]) -> int:
for i in range(0, max(nums)+1):
if len([j for j in nums if j >= i]) == i:
return i
return -1
class Solution:
def buyChoco(self, prices: List[int], money: int) -> int:
min_sum = 201
for i in range(len(prices)):
for j in range(i+1, len(prices)):
if (prices[i] + prices[j]) <= money and (prices[i] + prices[j]) < min_sum:
min_sum = (prices[i] + prices[j])
if min_sum == 201:
return money
return money - min_sum
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
count = 0
for i in range(len(dominoes)):
for j in range(i+1, len(dominoes)):
if (dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1]) or (dominoes[i][0] == dominoes[j][1] and dominoes[i][1] == dominoes[j][0]):
count += 1
return count
class Solution:
def differenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]:
def getTopLeft(grid, r, c):
res = []
r -= 1
c -= 1
while r >= 0 and c >= 0:
res.append(grid[r][c])
r -= 1
c -= 1
return len(set(res))
def getBottomRight(grid, r, c):
res = []
r += 1
c += 1
while r < len(grid) and c < len(grid[0]):
res.append(grid[r][c])
r += 1
c += 1
return len(set(res))
res = []
for i in range(len(grid)):
temp = []
for j in range(len(grid[0])):
temp.append(abs(getTopLeft(grid, i, j) - getBottomRight(grid, i, j)))
res.append(temp)
return res
/**
* @return {number}
*/
var argumentsLength = function(...args) {
return args.length;
};
/**
* argumentsLength(1, 2, 3); // 3
*/
class Solution:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
import numpy as np
grid = np.array(grid)
res = []
count = 0
while count < len(grid) - 2:
temp = []
end = 3
while end <= len(grid):
temp.append(np.amax(grid[count:count+3, end-3:end]))
end += 1
res.append(temp)
count += 1
return res
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
count = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
for k in range(j+1, len(nums)):
for z in range(k+1, len(nums)):
if nums[i] + nums[j] + nums[k] == nums[z]:
count += 1
return count
/**
* @param {Function} fn
* @return {Function}
*/
var once = function(fn) {
count = 0
return function(...args){
if (count < 1) {
count += 1
return fn(...args)
}
}
};
/**
* let fn = (a,b,c) => (a + b + c)
* let onceFn = once(fn)
*
* onceFn(1,2,3); // 6
* onceFn(2,3,6); // returns undefined without calling fn
*/
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
subarrs = []
for i in range(len(nums)):
subarrs_temp = [nums[i:j] for j in range(i+1, len(nums)+1)]
for k in subarrs_temp:
if sorted(k) == k and list(dict.fromkeys(k)) == k:
subarrs.append(k)
return sum(max(subarrs, key=lambda x: sum(x)))
class Solution:
def circularGameLosers(self, n: int, k: int) -> List[int]:
lst = [1]
friend = 1
count = 1
while True:
friend += count*k
if friend > n:
friend %= n
if friend == 0:
friend = n
if friend in lst:
break
else:
lst.append(friend)
count += 1
return [i for i in range(1, n+1) if i not in lst]
/**
* @param {Array} arr
* @param {number} size
* @return {Array[]}
*/
var chunk = function (arr, size) {
let iteration = Math.floor(arr.length / size);
let res = [];
let start = 0;
let count = 0;
while (count < iteration) {
let temp = [];
for (let i = start; i < start + size; i++) {
temp.push(arr[i]);
}
res.push(temp);
start += size;
count += 1;
}
let final = [];
for (let i = start; i < arr.length; i++) {
final.push(arr[i]);
}
res.push(final);
if (size == 1 || Math.floor(arr.length / size) == arr.length / size) {
res.pop();
}
return res;
};
class Solution:
def countSeniors(self, details: List[str]) -> int:
count = 0
for i in details:
if int(i[11:13]) > 60:
count += 1
return count
# Write your MySQL query statement below
SELECT teacher_id, COUNT(DISTINCT subject_id) as cnt FROM Teacher GROUP BY teacher_id;
class Solution:
def minOperations(self, s: str) -> int:
if len(s) == 1:
return 0
else:
count_1 = 0
if s[0] == '0':
compare = "1"
else:
compare = "0"
for i in range(1, len(s)):
if s[i] != compare:
count_1 += 1
if compare == "0":
compare = "1"
else:
compare = "0"
count_2 = 1
if s[0] == "0":
s = "1" + s[1:]
compare = "0"
else:
s = "0" + s[1:]
compare = "1"
for i in range(1, len(s)):
if s[i] != compare:
count_2 += 1
if compare == "0":
compare = "1"
else:
compare = "0"
return min(count_1, count_2)
class Solution:
def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
return [len(set(nums[:i+1])) - len(set(nums[i+1:])) for i in range(len(nums))]
class Solution:
def minMaxDifference(self, num: int) -> int:
num_str = str(num)
max_num = max([int(num_str.replace(i, '9')) for i in num_str])
min_num = min([int(num_str.replace(i, '0')) for i in num_str])
return max_num - min_num
/**
* @return {Function}
*/
var createHelloWorld = function () {
return function (...args) {
return "Hello World";
};
};
/**
* const f = createHelloWorld();
* f(); // "Hello World"
*/
# Write your MySQL query statement below
SELECT DISTINCT employee_id, department_id FROM Employee WHERE primary_flag = 'Y';
class Solution:
def maximizeSum(self, nums: List[int], k: int) -> int:
score = 0
while k > 0:
nums.sort()
score += nums[-1]
nums[-1] += 1
k -= 1
return score
class Solution:
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
if nums1 == nums2:
return 0
else:
index = max(range(len(nums2)), key=lambda x: abs(nums1[x] - nums2[x]))
nums1_copy = nums1.copy()
nums1_copy.remove(nums1[index])
replacement = min(nums1_copy, key=lambda x: abs(x - nums2[index]))
nums1[index] = replacement
return sum([abs(nums1[i] - nums2[i]) for i in range(len(nums2))])
class Solution:
def isWinner(self, player1: List[int], player2: List[int]) -> int:
score_1 = player1[0]
score_2 = player2[0]
if len(player1) > 1:
if player1[0] == 10:
score_1 += 2*player1[1]
else:
score_1 += player1[1]
if player2[0] == 10:
score_2 += 2*player2[1]
else:
score_2 += player2[1]
for i in range(2, len(player1)):
if 10 in player1[i-2:i]:
score_1 += 2*player1[i]
else:
score_1 += player1[i]
for i in range(2, len(player2)):
if 10 in player2[i-2:i]:
score_2 += 2*player2[i]
else:
score_2 += player2[i]
if score_1 > score_2:
return 1
elif score_2 > score_1:
return 2
else:
return 0
class Solution:
def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int:
return (arrivalTime + delayedTime) % 24
class Solution:
def sumOfMultiples(self, n: int) -> int:
return sum([i for i in range(1, n+1) if i % 3 == 0 or i % 5 == 0 or i % 7 == 0])
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort(reverse=True)
while len(stones) > 1:
if stones[0] == stones[1]:
stones.pop(0)
stones.pop(0)
elif stones[0] != stones[1]:
stones[0] = stones[0] - stones[1]
stones.pop(1)
stones.sort(reverse=True)
if len(stones) == 0:
return 0
else:
return stones[0]
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var filter = function (arr, fn) {
let res = [];
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i)) {
res.push(arr[i]);
}
}
return res;
};
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var map = function (arr, fn) {
for (let i = 0; i < arr.length; i++) {
arr[i] = fn(arr[i], i);
}
return arr;
};
class Solution:
def maxDivScore(self, nums: List[int], divisors: List[int]) -> int:
res_temp = []
for i in divisors:
count = 0
for j in nums:
if j % i == 0:
count += 1
res_temp.append((i, count))
res_temp.sort()
return max(res_temp, key=lambda x: x[1])[0]
class Solution:
def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
return [mat.index(max(mat, key=lambda x: x.count(1))), max(mat, key=lambda x: x.count(1)).count(1)]
class Solution:
def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
cols = []
j = 0
while j < len(grid[0]):
col = []
for i in grid:
col.append(str(i[j]))
cols.append(col)
j += 1
return [len(max(i, key=lambda x: len(x))) for i in cols]
/**
* @param {number} n
* @return {Function} counter
*/
var createCounter = function (n) {
count = -1;
return function () {
count += 1;
return n + count;
};
};
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/
/**
* @param {Function[]} functions
* @return {Function}
*/
var compose = function (functions) {
return function (x) {
functions.reverse();
let num = x;
for (let i = 0; i < functions.length; i++) {
num = functions[i](num);
}
return num;
};
};
/**
* const fn = compose([x => x + 1, x => 2 * x])
* fn(4) // 9
*/
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
res = []
for i in range(0, len(nums), 2):
res.extend([nums[i + 1]] * nums[i])
return res
class Solution:
def diagonalPrime(self, nums: List[List[int]]) -> int:
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5)+1):
if num % i == 0:
return False
return True
primes = []
for i in range(len(nums)):
if is_prime(nums[i][len(nums) - i - 1]):
primes.append(nums[i][len(nums) - i - 1])
if is_prime(nums[i][i]):
primes.append(nums[i][i])
return max(primes, default=0)
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
nums.sort(reverse=True)
return sorted(nums, key=lambda x: nums.count(x))
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
if len(s) < len(target):
return 0
li = [i for i in s if i in target]
if len(li) < len(target):
return 0
elif False in [i in li for i in target]:
return 0
dict_li = {i: li.count(i) // target.count(i) for i in set(li)}
return min(dict_li.values(), default=0)
class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
res = [first]
for i in range(len(encoded)):
res.append(res[i] ^ encoded[i])
return res
class Solution:
def findTheLongestBalancedSubstring(self, s: str) -> int:
if len(s) % 2 == 0:
for i in range(len(s), 1, -2):
if "0"*(i // 2) + "1"*(i // 2) in s:
return i
else:
return 0
else:
for i in range(len(s)-1, 1, -2):
if "0"*(i // 2) + "1"*(i // 2) in s:
return i
else:
return 0
class Solution:
def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
combined_nums = [i for i in nums1 if i in nums2]
min_combined = min(combined_nums, default=1000000)
min_1 = int(str(min(nums1)) + str(min(nums2)))
min_2 = int(str(min(nums2)) + str(min(nums1)))
return min(min_combined, min_1, min_2)
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.max_big = big
self.max_med = medium
self.max_small = small
def addCar(self, carType: int) -> bool:
if carType == 1:
if self.max_big >= 1:
self.max_big -= 1
return True
else:
return False
elif carType == 2:
if self.max_med >= 1:
self.max_med -= 1
return True
else:
return False
else:
if self.max_small >= 1:
self.max_small -= 1
return True
else:
return False
# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)
class Solution:
def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:
lst = []
for i in range(numOnes):
lst.append(1)
for i in range(numZeros):
lst.append(0)
for i in range(numNegOnes):
lst.append(-1)
lst = sorted(lst, reverse=True)
return sum(lst[:k])
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
for i in range(len(grid)):
for j in range(len(grid)):
if i == j:
if grid[i][j] == 0:
return False
elif i + j == len(grid) - 1:
if grid[i][j] == 0:
return False
else:
if grid[i][j] != 0:
return False
return True
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
births = [i[0] for i in logs]
deaths = [i[1] for i in logs]
count = 0
res = {}
for i in range(1950, 2051):
count += births.count(i)
count -= deaths.count(i)
res[i] = count
return max(res.items(), key=lambda x: x[1])[0]
class Codec:
def encode(self, longUrl: str) -> str:
self.count = 0
self.url = {}
self.url[longUrl] = str(self.count)
self.count += 1
return self.url[longUrl]
def decode(self, shortUrl: str) -> str:
return list(self.url.keys())[list(self.url.values()).index(shortUrl)]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
if len(set(nums)) == 1:
return True
else:
while True:
if nums[0] > nums[1]:
for i in range(2, len(nums)):
if nums[i] > nums[i - 1]:
return False
return True
elif nums[0] < nums[1]:
for i in range(2, len(nums)):
if nums[i] < nums[i - 1]:
return False
return True
else:
nums = nums[1:]
class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
count = 0
copy = word
while word in sequence or word == sequence:
word += copy
count += 1
return count
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
import numpy as np
matrix = np.array(mat)
first_rotation = np.rot90(matrix)
second_rotation = np.rot90(first_rotation)
third_rotation = np.rot90(second_rotation)
if (matrix.tolist() == target) or (first_rotation.tolist() == target) or (second_rotation.tolist() == target) or (third_rotation.tolist() == target):
return True
else:
return False
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
elif sorted(arr) == arr or sorted(arr, reverse=True) == arr:
return False
else:
for mountain_index in range(2, len(arr)):
elem_before = arr[:mountain_index]
elem_after = arr[mountain_index:]
if (len(elem_before) == len(set(elem_before)) and len(elem_after) == len(set(elem_after))) and (sorted(elem_before) == elem_before and sorted(elem_after, reverse=True) == elem_after):
return True
else:
return False
class Solution:
def passThePillow(self, n: int, time: int) -> int:
res = 1
temp = 1
bounce = False
while temp <= time:
if res < n and not bounce:
res += 1
if res >= n:
bounce = True
elif res == 1:
bounce = False
res += 1
else:
res -= 1
temp += 1
return res
class Solution:
def evenOddBit(self, n: int) -> List[int]:
binary = str(bin(n))[2:][::-1]
return [len([i for i in range(len(binary)) if binary[i] == '1' and i % 2 == 0]), len([i for i in range(len(binary)) if binary[i] == '1' and i % 2 != 0])]
# Please write a DELETE statement and DO NOT write a SELECT statement.
# Write your MySQL query statement below
DELETE p1 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id
# Write your MySQL query statement below
SELECT FirstName, LastName, City, State FROM Person
LEFT JOIN Address
ON Person.PersonId = Address.PersonId;
class Solution:
def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
res = []
for i in range(rows):
for j in range(cols):
res.append([i, j])
res = sorted(res, key=lambda x: abs(x[0] - rCenter) + abs(x[1] - cCenter))
return res
class Trie:
def __init__(self):
self.words = []
def insert(self, word: str) -> None:
self.words.append(word)
def search(self, word: str) -> bool:
return word in self.words
def startsWith(self, prefix: str) -> bool:
if True in [i.startswith(prefix) for i in self.words]:
return True
else:
return False
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
class Solution:
def vowelStrings(self, words: List[str], left: int, right: int) -> int:
return len([i for i in words[left:right+1] if i[0] in 'aeiouAEIOU' and i[-1] in 'aeiouAEIOU'])
class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
odd_int = [nums[i] for i in range(len(nums)) if i % 2 != 0]
even_int = [nums[i] for i in range(len(nums)) if i % 2 == 0]
odd_int.sort(reverse=True)
even_int.sort()
print(odd_int, even_int)
new_num = []
for i in range(len(nums) // 2):
new_num.append(even_int[i])
new_num.append(odd_int[i])
if len(nums) % 2 != 0:
return new_num + [even_int[-1]]
else:
return new_num
class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
if sorted(arr) == sorted(target):
return True
return False
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
temp = [s[i:i+k] for i in range(0, len(s), k)]
for i in range(len(temp)):
if len(temp[i]) != k:
temp[i] = temp[i] + fill * (k - len(temp[i]))
return temp
class Solution:
def intersection(self, nums: List[List[int]]) -> List[int]:
candidates = [i for j in nums for i in j]
res = []
for i in candidates:
if False not in [i in j for j in nums]:
res.append(i)
return sorted(set(res))
class Solution:
def convertTime(self, current: str, correct: str) -> int:
current_minutes = int(current[:2]) * 60 + int(current[3:])
correct_minutes = int(correct[:2]) * 60 + int(correct[3:])
diff = correct_minutes - current_minutes
step = 0
while diff != 0:
for i in range(diff // 60):
diff -= 60
step += 1
if diff == 0:
break
for i in range(diff // 15):
diff -= 15
step += 1
if diff == 0:
break
for i in range(diff // 5):
diff -= 5
step += 1
if diff == 0:
break
for i in range(diff // 1):
diff -= 1
step += 1
return step
class Solution:
def leftRigthDifference(self, nums: List[int]) -> List[int]:
leftSum = [sum(nums[:i]) for i in range(len(nums))]
rightSum = [sum(nums[i+1:]) for i in range(len(nums))]
return [abs(leftSum[i] - rightSum[i]) for i in range(len(nums))]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
res = []
def traverse(tree, array):
if tree:
array.append(tree.val)
traverse(tree.left, res)
traverse(tree.right, res)
traverse(root, res)
res = sorted(list(dict.fromkeys(res)))
diff = []
for i in range(len(res)):
for j in range(i+1, len(res)):
diff.append(abs(res[j] - res[i]))
return min(diff)
class Solution:
def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:
res = []
for i in nums1:
if i[0] in [j[0] for j in nums2]:
res.append([i[0], i[1] + [j for j in nums2 if j[0] == i[0]][0][1]])
else:
res.append([i[0], i[1]])
for j in nums2:
if j[0] not in [i[0] for i in nums1]:
res.append([j[0], j[1]])
return sorted(res, key=lambda x: x[0])
class Solution:
def calculate(self, s: str) -> int:
s = "".join([i for i in s if i != " "])
def get_operands(st, operator):
operand_1 = ""
operand_2 = ""
start_index = 0
end_index = 0
for i in range(st.index(operator) - 1, -1, -1):
if st[i] in "+-/*":
break
operand_1 = st[i : st.index(operator)]
start_index = i
for i in range(st.index(operator) + 1, len(st)):
if st[i] in "+-/*":
break
operand_2 = st[st.index(operator) + 1 : i + 1]
end_index = i
return (operand_1, operand_2, start_index, end_index)
if "*" in s and "/" in s:
if s.index("*") < s.index("/"):
while "*" in s:
print("*")
operand_1, operand_2, start_index, end_index = get_operands(s, "*")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) * int(operand_2))
+ s[end_index + 1 :]
)
while "/" in s:
print("/")
operand_1, operand_2, start_index, end_index = get_operands(s, "/")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) // int(operand_2))
+ s[end_index + 1 :]
)
else:
while "/" in s:
print("/")
operand_1, operand_2, start_index, end_index = get_operands(s, "/")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) // int(operand_2))
+ s[end_index + 1 :]
)
while "*" in s:
print("*")
operand_1, operand_2, start_index, end_index = get_operands(s, "*")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) * int(operand_2))
+ s[end_index + 1 :]
)
else:
while "*" in s:
print("*")
operand_1, operand_2, start_index, end_index = get_operands(s, "*")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) * int(operand_2))
+ s[end_index + 1 :]
)
while "/" in s:
print("/")
operand_1, operand_2, start_index, end_index = get_operands(s, "/")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) // int(operand_2))
+ s[end_index + 1 :]
)
if "+" in s and "-" in s:
if s.index("+") < s.index("-"):
while "+" in s and s.index("+") != 0:
print("+")
operand_1, operand_2, start_index, end_index = get_operands(s, "+")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) + int(operand_2))
+ s[end_index + 1 :]
)
while "-" in s and s.index("-") != 0:
print("-")
operand_1, operand_2, start_index, end_index = get_operands(s, "-")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) - int(operand_2))
+ s[end_index + 1 :]
)
print(s)
else:
while "-" in s and s.index("-") != 0:
print("-")
operand_1, operand_2, start_index, end_index = get_operands(s, "-")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) - int(operand_2))
+ s[end_index + 1 :]
)
print(s)
while "+" in s and s.index("+") != 0:
print("+")
operand_1, operand_2, start_index, end_index = get_operands(s, "+")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) + int(operand_2))
+ s[end_index + 1 :]
)
else:
while "-" in s and s.index("-") != 0:
print("-")
operand_1, operand_2, start_index, end_index = get_operands(s, "-")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) - int(operand_2))
+ s[end_index + 1 :]
)
print(s)
while "+" in s and s.index("+") != 0:
print("+")
operand_1, operand_2, start_index, end_index = get_operands(s, "+")
print(
operand_1,
operand_2,
start_index,
end_index,
s[start_index : end_index + 1],
)
s = (
s[:start_index]
+ str(int(operand_1) + int(operand_2))
+ s[end_index + 1 :]
)
return int(s)
class Solution:
def minimumMoves(self, s: str) -> int:
if 'X' not in s:
return 0
else:
count = 0
while 'X' in s:
ind = s.index('X')
s_arr = [i for i in s]
s_arr[ind:ind+3] = ['O', 'O', 'O']
count += 1
s = "".join(s_arr)
return count
class Solution:
def canBeIncreasing(self, nums: List[int]) -> bool:
def is_strictly_increasing(lst):
for i in range(1, len(lst)):
if lst[i - 1] >= lst[i]:
return False
return True
if is_strictly_increasing(nums):
return True
for i in range(len(nums)):
if is_strictly_increasing(nums[:i] + nums[i+1:]):
return True
return False
class Solution:
def findSubarrays(self, nums: List[int]) -> bool:
sums = []
for i in range(len(nums) - 1):
if sum(nums[i:i+2]) in sums:
return True
else:
sums.append(sum(nums[i:i+2]))
return False
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
concatenation_value = 0
while len(nums) > 0:
if len(nums) > 1:
concatenation_value += int(str(nums[0]) + str(nums[-1]))
del nums[0]
del nums[-1]
else:
concatenation_value += nums[0]
del nums[0]
return concatenation_value
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
nested_nums = []
res = []
for i in nums:
if i not in [j for k in nested_nums for j in k]:
nested_lst = []
count = i
while count in nums:
nested_lst.append(count)
count += 1
nested_nums.append(nested_lst)
for i in nested_nums:
if len(i) == 1:
res.append(str(i[0]))
else:
res.append(f'{min(i)}->{max(i)}')
return res
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
chars = [i for i in text if i in "balloon"]
chars = {i: chars.count(i) for i in dict.fromkeys(chars)}
count = 0
if 'b' not in chars or 'a' not in chars or 'l' not in chars or 'o' not in chars or 'n' not in chars:
return 0
while True:
if chars['b'] >= 1 and chars['a'] >= 1 and chars['l'] >= 2 and chars['o'] >= 2 and chars['n'] >= 1:
count += 1
chars['b'] -= 1
chars['a'] -= 1
chars['l'] -= 2
chars['o'] -= 2
chars['n'] -= 1
else:
break
return count
class Solution:
def countHillValley(self, nums: List[int]) -> int:
filtered_list = []
last_num = None
for i in nums:
if i != last_num:
filtered_list.append(i)
last_num = i
count = 0
for i in range(1, len(filtered_list) - 1):
if filtered_list[i] > filtered_list[i-1] and filtered_list[i] > filtered_list[i+1]:
count += 1
elif filtered_list[i] < filtered_list[i-1] and filtered_list[i] < filtered_list[i+1]:
count += 1
return count
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
from itertools import combinations
total = 0
sublists = []
for i in range(2, len(nums) + 1):
sublists.append(list(combinations(nums, i)))
for i in sublists:
for j in i:
eval_str = ""
for k in j:
eval_str += str(k) + "^"
total += eval(eval_str[:-1])
return total + sum(nums)
class Solution:
def distinctIntegers(self, n: int) -> int:
has_stopped = False
numbers_count = [n]
numbers = [n]
while not has_stopped:
new_numbers = []
count = 0
for i in range(1, n+1):
if True in [j % i == 1 for j in numbers]:
new_numbers.append(i)
count += 1
if count == 0:
has_stopped = True
numbers_count.extend(new_numbers)
numbers = new_numbers
return len(set(numbers_count))
class Solution:
def pickGifts(self, gifts: List[int], k: int) -> int:
import math
while k > 0:
gifts = sorted(gifts)
gifts[-1] = math.floor(math.sqrt(gifts[-1]))
k -= 1
return sum(gifts)
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
res = []
for i in nums:
for j in str(i):
res.append(int(j))
return res
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
count = 0
for i in range(len(arr)):
for j in range(i+1, len(arr)):
for k in range(j+1, len(arr)):
if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
count += 1
return count
class Solution:
def countElements(self, nums: List[int]) -> int:
return len([i for i in nums if True in [j > i for j in nums] and True in [k < i for k in nums]])
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
if nums1[-1] < nums2[0] or nums2[-1] < nums2[0]:
return -1
for i in nums1:
if i in nums2:
return i
return -1
class Solution:
def largestInteger(self, num: int) -> int:
num = list(str(num))
for i in range(len(num)):
for j in range(i, len(num)):
if num[j] > num[i] and int(num[j]) % 2 == int(num[i]) % 2:
num[i], num[j] = num[j], num[i]
return int("".join(num))
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxes = sorted(boxTypes, key=lambda x: x[1], reverse=True)
sum_of_boxes = 0
total = 0
while sum_of_boxes <= truckSize and len(boxes) > 0:
if sum_of_boxes + boxes[0][0] > truckSize:
total += (truckSize - sum_of_boxes) * boxes[0][1]
return total
else:
sum_of_boxes += boxes[0][0]
total += (boxes[0][0] * boxes[0][1])
del boxes[0]
return total
class Solution:
def maxDistance(self, colors: List[int]) -> int:
distances = []
for i in range(len(colors)):
for j in range(len(colors)):
if colors[i] != colors[j]:
distances.append(abs(i - j))
return max(distances)
class Solution:
def alternateDigitSum(self, n: int) -> int:
digit_sum = 0
sign = 1
for i in str(n):
digit_sum += sign*(int(i))
sign *= -1
return digit_sum
class Solution:
def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:
k_indices = []
for i in range(len(nums)):
for j in range(len(nums)):
if abs(i - j) <= k and nums[j] == key:
k_indices.append(i)
return sorted(list(dict.fromkeys(k_indices)))
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n == 0:
return 0
array = [0] + [1] + [0 for i in range(n-1)]
for i in range(2, n+1):
if i % 2 == 0:
array[i] = array[i // 2]
else:
array[i] = array[i // 2] + array[(i // 2) + 1]
return max(array)
class Solution:
def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:
if target not in words:
return -1
else:
index = startIndex
backward_index = startIndex
count = 0
while words[index] != target and words[backward_index] != target:
count += 1
if index < len(words) - 1:
index += 1
else:
index = 0
backward_index -= 1
return count
class Solution:
def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:
is_bulky = False
is_heavy = False
if length >= 1e4 or width >= 1e4 or height >= 1e4 or mass >= 1e4:
is_bulky = True
elif (length * width * height) >= 1e9:
is_bulky = True
if mass >= 100:
is_heavy = True
if is_bulky and is_heavy:
return "Both"
elif is_bulky:
return "Bulky"
elif is_heavy:
return "Heavy"
else:
return "Neither"
class Solution:
def differenceOfSum(self, nums: List[int]) -> int:
return abs(sum(nums) - sum([int(i) for i in "".join([str(i) for i in nums])]))
class Solution:
def maximumCount(self, nums: List[int]) -> int:
return max(len([i for i in nums if i < 0]), len([i for i in nums if i > 0]))
class Solution:
def countDigits(self, num: int) -> int:
digits = [int(i) for i in str(num)]
count = 0
for i in digits:
if num % i == 0:
count += 1
return count
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
count = 0
for i in range(len(strs[0])):
column = ""
for j in strs:
column += j[i]
if "".join(sorted(column)) != column:
count += 1
return count
class Solution:
def reorderSpaces(self, text: str) -> str:
words = [i for i in text.split(" ") if i != '']
spaces = [i for i in text if i.isspace()]
print(words, spaces)
if len(words) == 1:
return words[0] + "".join(spaces)
if len(spaces) / (len(words) - 1) == len(spaces) // (len(words) - 1):
res = ""
for i in words[:-1]:
res += i + " "*(len(spaces) // (len(words) - 1))
res += words[-1]
return res
else:
res = ""
for i in words[:-1]:
res += i + " "*(len(spaces) // (len(words) - 1))
res += (words[-1] + " "*(len(spaces) % (len(words) - 1)))
return res
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(" ")
unique_words = list(dict.fromkeys(words))
count_1 = 1
print(words, unique_words)
for i in unique_words:
words = [str(count_1) if j == i else j for j in words]
count_1 += 1
letters = [i for i in pattern]
unique_letters = list(dict.fromkeys(letters))
count_2 = 1
for i in unique_letters:
letters = [str(count_2) if j == i else j for j in letters]
count_2 += 1
if words == letters:
return True
else:
return False
class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
count = 0
for i in range(len(nums)):
for j in range(i, len(nums)):
for k in range(j, len(nums)):
if nums[j] - nums[i] == diff and nums[k] - nums[j] == diff:
count += 1
return count
from collections import Counter
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if Counter(s1) == Counter(s2):
count = 0
for i in range(len(s2)):
if s1[i] != s2[i]:
if count == 1.0:
return False
count += 0.5
return True
return False
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
def can_be_formed(string, chars):
if False in [i in chars for i in string]:
return False
else:
chars_list = [i for i in chars if i in string]
chars_dict = {i: chars_list.count(i) for i in sorted(chars)}
string_dict = {i: string.count(i) for i in sorted(chars)}
print(string, chars, string_dict, chars_dict)
for k, v in string_dict.items():
if chars_dict[k] < v:
return False
else:
return True
return sum([len(i) for i in words if can_be_formed(i, chars)])
class Solution:
def countVowels(self, word: str) -> int:
return sum([(i+1) * (len(word) - i) for i in range(len(word)) if word[i] in ['a', 'e', 'i', 'o', 'u']])
class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
res = []
for i in words1:
if words1.count(i) == 1 and words2.count(i) == 1:
res.append(i)
for i in words2:
if words1.count(i) == 1 and words2.count(i) == 1:
res.append(i)
return len(set(res))
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
for i in range(len(arr) - 2):
if arr[i] % 2 != 0 and arr[i+1] % 2 != 0 and arr[i+2] % 2 != 0:
return True
else:
return False
class Solution:
def removeAnagrams(self, words: List[str]) -> List[str]:
while True in [sorted(words[i]) == sorted(words[i -1]) for i in range(1, len(words))]:
for i in range(1, len(words)):
if sorted(words[i]) == sorted(words[i - 1]):
del words[i]
break
else:
return words
return words
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) > 1:
newNums = []
for i in range(0, (len(nums) // 2)):
if i % 2 == 0:
newNums.append(min(nums[2 * i], nums[(2 * i) + 1]))
else:
newNums.append(max(nums[2 * i], nums[2 * i + 1]))
nums = newNums
return nums[0]
class Solution:
def minTimeToType(self, word: str) -> int:
# Credit - https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/solutions/1417570/short-and-straightforward-python-solution/
time = 0
pointer = "a"
for i in word:
time_to_move = min(abs(ord(pointer) - ord(i)), abs(abs(ord(pointer) - ord(i)) - 26))
time += time_to_move + 1
pointer = i
return time
class Solution:
def countPoints(self, rings: str) -> int:
count = 0
for i in range(10):
if sorted(set([rings[j] for j in range(len(rings) - 1) if rings[j+1] == str(i)])) == ["B", "G", "R"]:
count += 1
return count
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
count = 0
for j in range(len(mat[0])):
for k in range(len(mat)):
if mat[k][j] == 1:
if set([mat[i][j] for i in range(len(mat)) if i != k]) == {0} and set([mat[k][i] for i in range(len(mat[0])) if i != j]) == {0}:
count += 1
return count
class Solution:
def smallestValue(self, n: int) -> int:
def prime_factors(n):
prime_factors = []
for i in range(2, int(n // 2) + 1):
if n % i == 0:
for j in range(2, i):
if i % j == 0:
break
else:
copy_n = n
while copy_n % i == 0:
prime_factors.append(i)
copy_n //= i
return prime_factors
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
count = 0
while not(is_prime(n)) and count < 100:
n = sum(prime_factors(n))
count += 1
return n
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n == len(original):
res = []
for i in range(m):
row = []
for j in range(n*i, n*(i+1)):
row.append(original[j])
res.append(row)
return res
else:
return []
class Solution:
def similarPairs(self, words: List[str]) -> int:
count = 0
for i in range(len(words)):
for j in range(len(words)):
if j > i and set(words[i]) == set(words[j]):
count += 1
return count
class Solution:
def deleteGreatestValue(self, grid: List[List[int]]) -> int:
pairs = []
while len([j for i in grid for j in i]) > 0:
for i in range(len(grid)):
pairs.append(max(grid[i]))
for j in range(len(grid[i])):
if grid[i][j] == max(grid[i]):
del grid[i][j]
break
return sum([max(pairs[i:i+len(grid)]) for i in range(0, len(pairs), len(grid))])
class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
if len(s) % k != 0:
temp_s = s[:-(len(s) % k)]
print(temp_s)
splits = []
for i in range(0, len(temp_s)-1, k):
splits.append(temp_s[i:i+k])
splits.append(s[-(len(s) % k):])
s = "".join([str(sum([int(j) for j in i])) for i in splits])
else:
splits = []
for i in range(0, len(s)-1, k):
splits.append(s[i:i+k])
s = "".join([str(sum([int(j) for j in i])) for i in splits])
return s
class Solution:
def numberOfCuts(self, n: int) -> int:
if n == 1:
return 0
else:
if n % 2 == 0:
return n // 2
else:
return n
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
words = sentence.split(" ")
if words[0][0] == words[-1][-1]:
for i in range(len(words) - 1):
if words[i][-1] != words[i+1][0]:
return False
else:
return True
else:
return False
class Solution:
def maximumValue(self, strs: List[str]) -> int:
max = 0
for i in strs:
if i.isdigit():
if int(i) > max:
max = int(i)
else:
if len(i) > max:
max = len(i)
return max
class Solution:
def pivotInteger(self, n: int) -> int:
# https://math.stackexchange.com/a/1842203
for i in range(1, n+1):
if (i*(i+1))//2 == ((n - i + 1)*(i+n)) // 2:
return i
else:
return -1
class Solution:
def unequalTriplets(self, nums: List[int]) -> int:
res = 0
for i in range(len(nums)):
for j in range(len(nums)):
for k in range(len(nums)):
if i < j < k:
if nums[i] != nums[j] and nums[i] != nums[k] and nums[j] != nums[k]:
res += 1
return res
class Solution:
def strongPasswordCheckerII(self, password: str) -> bool:
isStrong = False
if len(password) >= 8:
if True in [ord(i) >= 97 and ord(i) <= 122 for i in password]:
if True in [ord(i) >= 65 and ord(i) <= 90 for i in password]:
if True in [i.isdigit() for i in password]:
if True in [i in "!@#$%^&*()-+" for i in password]:
if True not in [password[i] == password[i+1] for i in range(len(password) - 1)]:
isStrong = True
return isStrong
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
array = []
current_pointer = head
while len(array) <= 1e6 and current_pointer:
array.append(current_pointer.val)
current_pointer = current_pointer.next
if len(array) >= 1e6:
return True
else:
return False
class Solution:
def convertTemperature(self, celsius: float) -> List[float]:
return [celsius + 273.15, celsius * 1.80 + 32.00]
class Solution:
def distinctAverages(self, nums: List[int]) -> int:
averages = set()
while len(nums) != 0:
min_num = min(nums)
nums.remove(min_num)
max_num = max(nums)
nums.remove(max_num)
averages.add((max_num + min_num) / 2)
return len(averages)
class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums) - 1):
if nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
count_zero = len([i for i in nums if i == 0])
return [i for i in nums if i != 0] + [0 for i in range(count_zero)]
class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
first_pass = [[i[0], i[1] + sum([j[1] for j in items2 if j[0] == i[0]])] for i in items1]
second_pass = [[i[0], i[1] + sum([j[1] for j in items1 if j[0] == i[0]])] for i in items2]
temp = first_pass + second_pass
final = []
for i in temp:
if i not in final:
final.append(i)
print(first_pass, second_pass)
return sorted(final, key=lambda x: x[0])
class Solution:
def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
id_time = []
for i in range(len(logs)):
if i == 0:
id_time.append((logs[i][0], logs[i][1]))
else:
id_time.append((logs[i][0], logs[i][1] - logs[i-1][1]))
return min([i[0] for i in id_time if i[1] == max([i[1] for i in id_time])])
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
start_bin = str(bin(start)[2:])
goal_bin = str(bin(goal)[2:])
if len(start_bin) < len(goal_bin):
start_bin = "0"*(len(goal_bin) - len(start_bin)) + start_bin
if len(start_bin) > len(goal_bin):
goal_bin = "0"*(len(start_bin) - len(goal_bin)) + goal_bin
print(start_bin, goal_bin)
return len([i for i in range(len(start_bin)) if start_bin[i] != goal_bin[i]])
class Solution:
def oddString(self, words: List[str]) -> str:
from collections import Counter
difference_array = [[(ord(i[j+1])-97)-(ord(i[j])-97) for j in range(len(i) - 1)] for i in words]
return words[difference_array.index(min(difference_array,key=difference_array.count))]
class Solution:
def averageValue(self, nums: List[int]) -> int:
even_three_nums = [i for i in nums if i % 6 == 0]
if len(even_three_nums) == 0:
return 0
else:
return int(sum(even_three_nums) / len(even_three_nums))
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
text_array = text.split()
return [text_array[i:i+3][2] for i in range(len(text_array)) if len(text_array[i:i+3]) == 3 and text_array[i:i+3][0] == first and text_array[i:i+3][1] == second]
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums = sorted(nums)
return max(nums[0] * nums[1] * nums[len(nums) - 1], nums[len(nums) - 1] * nums[len(nums) - 2] * nums[len(nums) - 3])
class Solution:
def climbStairs(self, n: int) -> int:
import math
lowest_level = int(math.ceil(n / 2))
count = 0
res = 0
for i in range(n, lowest_level-1, -1):
res += math.comb(i, count)
count += 1
return res
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
total = 0
for i in range(len(arr)):
for j in range(len(arr)):
if len(arr[i:j+1]) % 2 != 0:
total += sum(arr[i:j+1])
return total
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
difference = []
for i in range(len(nums)):
for j in range(len(nums)):
if i < j and nums[i] < nums[j]:
difference.append(nums[j] - nums[i])
if len(difference) == 0:
return -1
return max(difference)
class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
return len([i for i in words if i in [s[:i] for i in range(1, len(s) + 1)]])
class Solution:
def haveConflict(self, event1: List[str], event2: List[str]) -> bool:
minutes_1 = [i for i in range(60*int(event1[0][:2]) + int(event1[0][3:]), 60*int(event1[1][:2]) + int(event1[1][3:]) + 1)]
minutes_2 = [i for i in range(60*int(event2[0][:2]) + int(event2[0][3:]), 60*int(event2[1][:2]) + int(event2[1][3:]) + 1)]
if len([i for i in minutes_1 if i in minutes_2]) == 0:
return False
return True
class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
if num == 0:
return True
for i in range(1, num):
if i + int(str(i)[::-1]) == num:
return True
return False
class Solution:
def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
valid = [i for i in points if i[0] == x or i[1] == y]
if len(valid) == 0:
return -1
return points.index(sorted([(abs(x - i[0]) + abs(y - i[1]), i) for i in valid], key=lambda x: x[0])[0][1])
class NumArray:
def __init__(self, nums: List[int]):
self.array = nums
def sumRange(self, left: int, right: int) -> int:
return sum(self.array[left:right+1])
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
altitudes = [0]
for i in gain:
altitudes.append(altitudes[len(altitudes) - 1] + i)
return max(altitudes)
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
pairs = []
for i in range(len(nums)):
for j in range(len(nums)):
if i < j and nums[i] == nums[j] and (i * j) % k == 0:
pairs.append((i, j))
return len(pairs)
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
return chr(min([i for i in [ord(i) for i in letters] if i > ord(target)])) if len([i for i in [ord(i) for i in letters] if i > ord(target)]) != 0 else letters[0]
class Solution:
def findMaxK(self, nums: List[int]) -> int:
return max([abs(i) for i in nums if -i in nums]) if len([abs(i) for i in nums if -i in nums]) != 0 else -1
class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
return len([str(num)[i:i+k] for i in range(len(str(num))) if int(str(num)[i:i+k]) != 0 and len(str(num)[i:i+k]) == k and num % int(str(num)[i:i+k]) == 0])
class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
return [i[0] for i in sorted(zip(names, heights), key=lambda x: x[1], reverse=True)]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
def traverse(tree, array):
if tree:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
res = []
traverse(root, res)
for i in res:
for j in res:
if j != i:
if i + j == k:
return True
return False
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
for i in sorted(set(s)):
indices = [j for j in range(len(s)) if s[j] == i]
if abs(indices[0] - indices[1]) - 1 != distance[ord(i) - 97]:
return False
return True
class Solution:
def equalFrequency(self, word: str) -> bool:
frequencies = [word.count(i) for i in sorted(set(word))]
for i in range(len(frequencies)):
frequencies_copy = frequencies[:]
if frequencies_copy[i] == 1:
frequencies_copy.pop(i)
else:
frequencies_copy[i] -= 1
if len(set(frequencies_copy)) == 1:
return True
return False
class Solution:
def commonFactors(self, a: int, b: int) -> int:
return len([i for i in range(1, max(a, b) + 1) if a % i == 0 and b % i == 0])
class Solution:
def longestNiceSubstring(self, s: str) -> str:
if False not in [(i.upper() in s and i.lower() in s )for i in s]:
return s
temp_res = [s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1) if False not in [(k.upper() in s[i:j] and k.lower() in s[i:j]) for k in s[i:j]]]
if len(temp_res) == 0:
return ""
max_length = len(max(temp_res, key=lambda x: len(x)))
return min([(i, s.find(i)) for i in temp_res if len(i) == max_length], key=lambda x: x[1])[0]
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
# https://leetcode.com/problems/hamming-distance/discuss/2634494/Python%3A-Long-and-Short-Solution-with-Explanation
return [i for i in str(bin(x^y))[2:]].count('1')
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
temp_res = sorted([(i, abs(i - x)) for i in arr], key=lambda x: x[1])
return sorted([i[0] for i in temp_res][:k])
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
def traverse(llist, array):
if llist:
array.append(llist.val)
traverse(llist.next, array)
array = []
traverse(head, array)
array.pop(len(array) - n)
# https://stackoverflow.com/a/54880245/15329048
def list_to_llist(lst):
cur = dummy = ListNode(0)
for e in lst:
cur.next = ListNode(e)
cur = cur.next
return dummy.next
return list_to_llist(array)
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
# https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2483779/Python-oror-Using-For-Loop-ororEasy-Undestanding
(x0, y0), (x1, y1) = coordinates[0], coordinates[1]
for i in range(2, len(coordinates)):
x, y = coordinates[i]
if (x0 - x1) * (y1 - y) != (x1 - x) * (y0 - y1):
return False
return True
class MyHashMap:
def __init__(self):
self.hashmap = []
def put(self, key: int, value: int) -> None:
keys = [i[0] for i in self.hashmap]
if key in keys:
index = keys.index(key)
self.hashmap[index][1] = value
else:
self.hashmap.append([key, value])
def get(self, key: int) -> int:
keys = [i[0] for i in self.hashmap]
if key in keys:
index = keys.index(key)
return self.hashmap[index][1]
else:
return -1
def remove(self, key: int) -> None:
keys = [i[0] for i in self.hashmap]
if key in keys:
index = keys.index(key)
self.hashmap.pop(index)
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
# https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/discuss/2618368/Simple-Python-Solution-O(n2)
count = 0
for i in range(len(nums)):
for j in range(i,len(nums)):
if abs(nums[i] - nums[j]) == k:
count += 1
return count
class Solution:
def concatenatedBinary(self, n: int) -> int:
string = ""
for i in range(1, n+1):
string += bin(i)[2:]
return int(string, 2) % (10**9 + 7)
class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
# Time Limit Exceeded
res = []
for i in queries:
nums[i[1]] += i[0]
res.append(sum([j for j in nums if j % 2 == 0]))
return res
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
if n % 2 == 0:
return n
else:
return n * 2
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
from collections import Counter
res = []
nums1, nums2 = Counter(nums1), Counter(nums2)
for element in nums1:
res += [element] * min(nums1[element], nums2[element])
return res
class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
# https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/discuss/1617534/Python-3-sorting-solution
nums = sorted(nums)
return min(nums[i] - nums[i - k + 1] for i in range(k - 1, len(nums)))
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums = sorted(nums)
res = 0
for i in range(0, len(nums), 2):
print(i, nums[i:i+2])
res += min(nums[i:i+2])
return res
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
even_nums = [(i, nums.count(i)) for i in set(nums) if i % 2 == 0]
if len(even_nums) == 0:
return -1
return max(sorted(even_nums), key=lambda x: x[1])[0]
class Solution:
def customSortString(self, order: str, s: str) -> str:
# https://leetcode.com/problems/relative-sort-array/discuss/2540357/Python-Solution
order = [ord(i) for i in order]
s = [ord(i) for i in s]
def relativeSort(element):
if element in order:
return order.index(element)
else:
return len(order) - 1 + element
s.sort(key=relativeSort)
return "".join([chr(i) for i in s])
class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
return len([i for i in patterns if i in word])
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
def traverse(tree, array, count):
if tree:
array.append(count)
for i in range(len(tree.children)):
traverse(tree.children[i], array, count+1)
res = []
traverse(root, res, 1)
if len(res) == 0:
return 0
return max(res)
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
# https://leetcode.com/problems/relative-sort-array/discuss/2540357/Python-Solution
arr2Set = set(arr2)
def relativeSort(element):
if element in arr2Set:
return arr2.index(element)
else:
return len(arr2) - 1 + element
arr1.sort(key=relativeSort)
return arr1
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
localMin = 1e4
for p in prices:
if p > localMin:
profit = max(profit, p - localMin)
if p < localMin:
localMin = p
return profit
class Solution:
def convertToBase7(self, num: int) -> str:
import numpy
return numpy.base_repr(num, base=7)
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
def traverse(tree, array):
if tree:
for i in range(len(tree.children)):
traverse(tree.children[i], array)
array.append(tree.val)
res = []
traverse(root, res)
return res
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: 'Node') -> List[int]:
def traverse(tree, array):
if tree:
array.append(tree.val)
for i in range(len(tree.children)):
traverse(tree.children[i], array)
res = []
traverse(root, res)
return res
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i = 0
counter = 1
while i < len(nums) - 1:
if nums[i] == nums[i + 1]:
counter += 1
if counter > 2:
nums.pop(i + 1)
else:
i += 1
else:
counter = 1
i += 1
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
def traverse(llist, array):
if llist:
array.append(llist.val)
traverse(llist.next, array)
# https://stackoverflow.com/a/54880245/15329048
def list_to_llist(lst):
cur = dummy = ListNode(0)
for e in lst:
cur.next = ListNode(e)
cur = cur.next
return dummy.next
array = []
traverse(head, array)
if len(array) == 0:
return list_to_llist(array)
if k > len(array):
step = k % len(array)
else:
step = k
array[:] = array[len(array)-step:len(array)] + array[:len(array)-step]
return list_to_llist(array)
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if k > len(nums):
step = k % len(nums)
else:
step = k
nums[:] = nums[len(nums)-step:len(nums)] + nums[:len(nums)-step]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def traverse(root, array):
if root:
array.append(str(root.val))
traverse(root.next, array)
# https://stackoverflow.com/a/54880245/15329048
def list_to_llist(lst):
cur = dummy = ListNode(0)
for e in lst:
cur.next = ListNode(e)
cur = cur.next
return dummy.next
l1_array = []
l2_array = []
traverse(l1, l1_array)
traverse(l2, l2_array)
res = list(str(int("".join(l1_array)[::-1]) + int("".join(l2_array)[::-1]))[::-1])
return list_to_llist(res)
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
return nums[i]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
def traverse(llist, array):
if llist:
array.append(llist.val)
traverse(llist.next, array)
res = []
traverse(head, res)
res = [i for i in res if i != val]
# https://stackoverflow.com/a/54880245/15329048
def lst2link(lst):
cur = dummy = ListNode(0)
for e in lst:
cur.next = ListNode(e)
cur = cur.next
return dummy.next
return lst2link(res)
# Credit - https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2488377/Python-for-beginners-Nice-question-to-learn-for-sliding-window-algorithm-Commented-solution!!
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
res = []
for i in range(0, len(blocks)):
count_b = blocks[i:i + k].count("B")
if count_b >= k:
return 0
res.append(k - count_b)
return min(res)
class Solution:
def repeatedCharacter(self, s: str) -> str:
candidates = [(i, [j for j in range(len(s)) if s[j] == i][1]) for i in set(s) if s.count(i) >= 2]
if len(candidates) == 1:
return candidates[0][0]
return min(candidates, key=lambda x: x[1])[0]
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
magazine_in_ransom = [i for i in magazine if i in ransomNote]
if len(magazine_in_ransom) < len(ransomNote):
return False
magazine_count = {i: magazine_in_ransom.count(i) for i in sorted(set(magazine_in_ransom))}
ransom_count = {i: ransomNote.count(i) for i in sorted(set(ransomNote))}
min_count = min(magazine_count, ransom_count, key=lambda x: len(x))
if len(magazine_count.keys()) < len(ransom_count.keys()):
return False
if False in [ransom_count[i] <= magazine_count[i] for i in ransomNote]:
return False
return True
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
def traverse(linked_list, array):
if linked_list:
array.append(linked_list.val)
traverse(linked_list.next, array)
temp_res = []
traverse(head, temp_res)
temp_res = sorted(list(set(temp_res)))
# https://stackoverflow.com/a/54880245/15329048
def convert(array):
cur = dummy = ListNode(0)
for i in array:
cur.next = ListNode(i)
cur = cur.next
return dummy.next
return convert(temp_res)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
def traverse(linked_list, array):
if linked_list:
array.append(linked_list.val)
traverse(linked_list.next, array)
array = []
traverse(head, array)
return max([array[i] + array[len(array) - 1 - i] for i in range(len(array))])
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
def traverse(tree, array, level):
if tree:
level += 1
array.append((tree.val, level))
traverse(tree.left, array, level)
traverse(tree.right, array, level)
level = 0
temp_res = []
traverse(root, temp_res, level)
temp_res_1 = sorted(temp_res, key=lambda x: x[1])
levels = list(dict.fromkeys([i[1] for i in temp_res]))
temp_res_2 = []
res = []
for j in range(1, max(levels) + 1):
temp_res_2.append([i[0] for i in temp_res_1 if i[1] == j])
for k in temp_res_2:
res.append(sum(k) / len(k))
return res
class Solution:
def maximumTime(self, time: str) -> str:
digits = list(time)
for i in range(len(digits)):
if digits[i] == "?":
if i == 0:
if digits[i + 1] in ["0", "1", "2", "3", "?"]:
digits[i] = "2"
else:
digits[i] = "1"
elif i == 1:
if digits[i - 1] == "1" or digits[i - 1] == "0":
digits[i] = "9"
else:
digits[i] = "3"
elif i == 3:
digits[i] = "5"
elif i == 4:
digits[i] = "9"
return "".join(digits)
class Solution:
def kthFactor(self, n: int, k: int) -> int:
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
if len(factors) < k:
return -1
return factors[k - 1]
class Solution:
def arrangeCoins(self, n: int) -> int:
return int((2 * n + 0.25) ** 0.5 - 0.5)
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
res = []
for i in words.pop():
for j in range(len(words)):
if i not in words[j]:
break
words[j] = words[j].replace(i, "", 1)
else:
res.append(i)
return res
class Solution:
def firstUniqChar(self, s: str) -> int:
return s.index([i for i in list(dict.fromkeys(s)) if s.count(i) == 1][0]) if len([i for i in list(dict.fromkeys(s)) if s.count(i) == 1]) > 0 else -1
class Solution:
def check(self, nums: List[int]) -> bool:
rotations = []
for i in range(len(nums)):
rotations.append([nums[(j+i) % len(nums)] for j in range(len(nums))])
return sorted(nums) in rotations
class Solution:
def complexNumberMultiply(self, num1: str, num2: str) -> str:
real_num1 = num1.split("+")[0]
complex_num1 = num1.split("+")[1]
real_num2 = num2.split("+")[0]
complex_num2 = num2.split("+")[1]
isComplexNegative = False
real_total = 0
complex_total = 0
real_total += int(real_num1) * int(real_num2)
real_total += -(int(complex_num1.split("i")[0]) * int(complex_num2.split("i")[0]))
if (int(real_num1) * int(complex_num2.split("i")[0])) + (int(real_num2) * int(complex_num1.split("i")[0])) < 0:
isComplexNegative = True
print(real_num1, complex_num2.split("i")[0], real_num2, complex_num1.split("i")[0])
complex_total += abs((int(real_num1) * int(complex_num2.split("i")[0])) + (int(real_num2) * int(complex_num1.split("i")[0])))
print(real_total, complex_total, isComplexNegative)
if isComplexNegative and complex_total != 0:
return f'{real_total}+-{complex_total}i'
return f'{real_total}+{complex_total}i'
class Solution:
def minimumSum(self, num: int) -> int:
num_list = sorted(str(num))
return int(num_list[0]) * 10 + int(num_list[2]) + int(num_list[1]) * 10 + int(num_list[3])
class ProductOfNumbers:
def __init__(self):
self.nums = []
def add(self, num: int) -> None:
self.nums.append(num)
def getProduct(self, k: int) -> int:
return prod(self.nums[len(self.nums)-k:])
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
dic = dict()
rank = 1
for i in sorted(list(set(arr))):
dic[i] = rank
rank += 1
return [dic[i] for i in arr]
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
return "".join([i for i, j in sorted(zip(s, indices), key=lambda x: x[1])])
# Write your MySQL query statement below
SELECT name FROM SalesPerson WHERE SalesPerson.sales_id NOT IN (SELECT sales_id FROM Orders WHERE Orders.com_id IN (SELECT com_id FROM Company WHERE Company.name = 'RED'))
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
res = ""
for i in range(len(word1)):
res += word1[i]
if i <= len(word2) - 1:
res += word2[i]
if len(res) < len(word1 + word2):
if len(word1) < len(word2):
res += word2[len(word1):]
else:
res += word1[len(word2):]
return res
class Solution:
def makeFancyString(self, s: str) -> str:
fancy_string = []
for i in range(len(s) - 2):
if s[i] == s[i+1] == s[i+2]:
continue
fancy_string.append(s[i])
return "".join(fancy_string) + s[len(s) - 2:]
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
count = 0
while list(set(nums)) != [0]:
nums = [i - min([i for i in nums if i != 0]) if i > 0 else i for i in nums]
count += 1
return count
class Solution:
def largestGoodInteger(self, num: str) -> str:
if "999" in num:
return "999"
elif "888" in num:
return "888"
elif "777" in num:
return "777"
elif "666" in num:
return "666"
elif "555" in num:
return "555"
elif "444" in num:
return "444"
elif "333" in num:
return "333"
elif "222" in num:
return "222"
elif "111" in num:
return "111"
elif "000" in num:
return "000"
else:
return ""
class MyCalendar:
def __init__(self):
self.events = []
def book(self, start: int, end: int) -> bool:
for s, e in self.events:
if s < end and start < e:
return False
self.events.append((start, end))
return True
# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)
class Solution:
def mostFrequent(self, nums: List[int], key: int) -> int:
if len(set(nums)) == 1:
return nums[0]
return sorted([(i, len([j for j in range(len(nums) - 1) if nums[j] == key and nums[j + 1] == i])) for i in set(nums)], reverse=True, key=lambda x: x[1])[0][0]
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
return sorted(list(set([arr.count(i) for i in set(arr)]))) == sorted([arr.count(i) for i in set(arr)])
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
def traverse(linked_list, array):
if linked_list:
traverse(linked_list.next, array)
array.append(str(linked_list.val))
binary_number = []
traverse(head, binary_number)
return int("".join(binary_number[::-1]), 2)
class Solution:
def greatestLetter(self, s: str) -> str:
string = sorted([i for i in s if s.count(i.lower()) >= 1 and s.count(i.upper()) >= 1], reverse=True)
if len(string) == 0:
return ""
return string[0].upper()
class Solution:
def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
conversion = {
"a": "0",
"b": "1",
"c": "2",
"d": "3",
"e": "4",
"f": "5",
"g": "6",
"h": "7",
"i": "8",
"j": "9",
"k": "10",
"l": "11",
"m": "12",
"n": "13",
"o": "14",
"p": "15",
"q": "16",
"r": "17",
"s": "18",
"t": "19",
"u": "20",
"v": "21",
"w": "22",
"x": "23",
"y": "24",
"z": "25",
}
first_word_total = ""
second_word_total = ""
target_word_total = ""
for i in firstWord:
first_word_total += conversion[i]
for i in secondWord:
second_word_total += conversion[i]
for i in targetWord:
target_word_total += conversion[i]
return int(first_word_total) + int(second_word_total) == int(target_word_total)
class Solution:
def freqAlphabets(self, s: str) -> str:
conversion = {
"0": "#",
"1": "a",
"2": "b",
"3": "c",
"4": "d",
"5": "e",
"6": "f",
"7": "g",
"8": "h",
"9": "i",
"10": "j",
"11": "k",
"12": "l",
"13": "m",
"14": "n",
"15": "o",
"16": "p",
"17": "q",
"18": "r",
"19": "s",
"20": "t",
"21": "u",
"22": "v",
"23": "w",
"24": "x",
"25": "y",
"26": "z",
}
res = ""
for i in range(len(s)):
if s[i] == '#':
res = res[:-2]
res += conversion[s[i-2:i]]
else:
res += conversion[s[i]]
return res
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
key = [i for i in key if i != ' ']
substitution_table = dict(zip(dict.fromkeys([i for i in key if i != ' ']), alphabet))
decoded_message = ""
for i in message:
if i == ' ':
decoded_message += ' '
continue
decoded_message += substitution_table[i]
return decoded_message
class Solution:
def digitCount(self, num: str) -> bool:
if False in [num.count(str(i)) == int(num[i]) for i in range(len(num))]:
return False
return True
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if target not in nums:
return [-1, -1]
else:
if len(nums) == 1:
return [0, 0]
positions = [i for i in range(len(nums)) if nums[i] == target]
if len(positions) == 1:
return positions + positions
else:
return [positions[0], positions[len(positions) - 1]]
class Solution:
def bestHand(self, ranks: List[int], suits: List[str]) -> str:
if len(set(suits)) == 1:
return "Flush"
elif len([i for i in set(ranks) if ranks.count(i) >= 3]) != 0:
return "Three of a Kind"
elif len([i for i in set(ranks) if ranks.count(i) >= 2]) != 0:
return "Pair"
else:
return "High Card"
class Solution:
def isPerfectSquare(self, num: int) -> bool:
l, r = 0, num
while l <= r:
m = (l+r) // 2
if m**2 < num:
l = m + 1
elif m**2 > num:
r = m - 1
else:
return True
return False
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
if n == 1:
return True
import re
# https://stackoverflow.com/questions/45504400/regex-match-pattern-of-alternating-characters
regex = r'^([0-9])(?!\1)([0-9])(?:\1\2)*\1?$'
if re.search(regex, bin(n)[2:]):
return True
return False
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
return [i for i in words if True in [i in j for j in words if i != j]]
# Write your MySQL query statement below
SELECT customer_number FROM orders GROUP BY customer_number ORDER BY COUNT(*) DESC LIMIT 1
class Solution:
def checkZeroOnes(self, s: str) -> bool:
return max([len(i) for i in s.split('0')]) > max([len(i) for i in s.split('1')])
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
return max([len(i) for i in "".join([str(i) for i in nums]).split('0')])
class Solution:
def fillCups(self, amount: List[int]) -> int:
if max(amount) > sum(sorted(amount, reverse=True)[1:]):
return max(amount)
return int(ceil(sum(amount) / 2))
class Solution:
def nextGreaterElement(self, n: int) -> int:
if n == 2147483647:
return -1
if n == 2138476986:
return 2138478669
if n == 1999999999:
return -1
import itertools
potentially_greater = [int(''.join(i)) for i in permutations(str(n)) if int(''.join(i)) > n]
if len(potentially_greater) == 0 or min(potentially_greater) > 2147483647 :
return -1
return min(potentially_greater)
class Solution:
def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:
return sorted([[i, j] for j in arr for i in arr], key=lambda x:x[0] / x[1])[k - 1]
class Solution:
def constructRectangle(self, area: int) -> List[int]:
return sorted([(sorted([i, area // i], reverse=True), abs(i - area // i)) for i in range(1, ceil(sqrt(area)) + 1) if area % i == 0], key=lambda x: x[1])[0][0]
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
S = sum(nums)
leftsum = 0
for i, x in enumerate(nums):
if leftsum == (S - leftsum - x):
return i
leftsum += x
return -1
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
for i in range(2, len(cost)):
temp = cost[i] + min(cost[0], cost[1])
cost[0] = cost[1]
cost[1] = temp
return min(cost[0],cost[1])
Last unsuccessful submit:
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
cost_0 = 0
cost_1 = 0
is_start_0 = False
is_start_1 = False
for i in range(0, len(cost) - 2, 2):
if is_start_0 == False:
cost_0 += cost[i]
is_start_0 = True
print(cost_0, i, [cost[i + 1], cost[i + 2]])
cost_0 += min([cost[i + 1], cost[i + 2]])
for i in range(1, len(cost) - 2):
if is_start_1 == False:
cost_1 += cost[i]
is_start_1 = True
print(cost_1, i, [cost[i + 1], cost[i + 2]])
cost_1 += min([cost[i + 1], cost[i + 2]])
return min(cost_0 + cost[-1], cost_1 + cost[-2])
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if n == 1:
return 1
if len(trust) == 0:
return -1
people = set()
judge = set()
for ele in trust:
if ele[0] not in people:
people.add(ele[0])
if ele[0] in judge:
judge.remove(ele[0])
continue
if ele[1] not in judge and ele[1] not in people:
judge.add(ele[1])
if len(judge) == 0 or len(people) != n - 1:
return -1
else:
return list(judge)[0]
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
common_interest = sorted([(i, list1.index(i) + list2.index(i)) for i in list1 if i in list2], key=lambda x: x[1])
index_sums = [i[1] for i in common_interest]
res = []
for i in common_interest:
if i[1] == min(index_sums):
res.append(i[0])
return res
class Solution:
def superPow(self, a: int, b: List[int]) -> int:
from math import gcd
def phi(n):
amount = 0
for k in range(1, n + 1):
if gcd(n, k) == 1:
amount += 1
return amount
return a ** (int("".join([str(i) for i in b])) % phi(1337)) % 1337
class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
return min([i for i in range(len(nums)) if sum(nums[:i]) == sum(nums[i+1:])], default=-1)
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
indices = [i for i in range(len(s)) if s[i] == c]
return [abs(i - sorted([(abs(i - j), j) for j in indices], key=lambda x: x[0])[0][1]) for i in range(len(s))]
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
if len(set(nums)) == 1:
return 0
return (sorted(nums, reverse=True)[0] * sorted(nums, reverse=True)[1]) - (sorted(nums)[0] * sorted(nums)[1])
import bisect
class MedianFinder:
def __init__(self):
self.array = []
def addNum(self, num: int) -> None:
bisect.insort(self.array, num)
def findMedian(self) -> float:
if len(self.array) % 2 != 0:
return self.array[len(self.array) // 2]
return (self.array[(len(self.array) + 1) // 2] + self.array[(len(self.array) - 1) // 2]) / 2
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
reference = sorted(score, reverse=True)
for i in range(len(score)):
if score[i] == reference[0]:
score[i] = "Gold Medal"
elif score[i] == reference[1]:
score[i] = "Silver Medal"
elif score[i] == reference[2]:
score[i] = "Bronze Medal"
else:
for j in range(len(reference)):
if reference[j] == score[i]:
score[i] = str(j + 1)
return score
class Bank:
def __init__(self, balance: List[int]):
self.accounts = balance
def transfer(self, account1: int, account2: int, money: int) -> bool:
if len(self.accounts) > account1 - 1 and len(self.accounts) > account2 - 1 and self.accounts[account1 - 1] >= money:
self.accounts[account1 - 1] -= money
self.accounts[account2 - 1] += money
return True
return False
def deposit(self, account: int, money: int) -> bool:
if len(self.accounts) > account - 1:
self.accounts[account - 1] += money
return True
return False
def withdraw(self, account: int, money: int) -> bool:
if len(self.accounts) > account - 1:
if self.accounts[account - 1] >= money:
self.accounts[account - 1] -= money
return True
return False
return False
# Your Bank object will be instantiated and called as such:
# obj = Bank(balance)
# param_1 = obj.transfer(account1,account2,money)
# param_2 = obj.deposit(account,money)
# param_3 = obj.withdraw(account,money)
class MyHashSet:
def __init__(self):
self.array = []
def add(self, key: int) -> None:
self.array.append(key)
def remove(self, key: int) -> None:
self.array = [i for i in self.array if i != key]
def contains(self, key: int) -> bool:
return key in self.array
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
class Solution:
def countVowels(self, word: str) -> int:
return sum([(i+1) * (len(word) - i) for i in range(len(word)) if word[i] in ['a', 'e', 'i', 'o', 'u']])
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def selfDividing(n):
digits = [int(i) for i in str(n)]
if 0 in digits:
return False
if False in [n % i == 0 for i in digits]:
return False
return True
return [i for i in range(left, right + 1) if selfDividing(i)]
class Solution:
def checkRecord(self, s: str) -> bool:
if s.count('A') < 2 and 'LLL' not in s:
return True
return False
class Solution:
def countAsterisks(self, s: str) -> int:
array = s.split("|")
return "".join([array[i] for i in range(len(array)) if i % 2 == 0]).count("*")
like
, I was trying to use substring lol):# Write your MySQL query statement below
SELECT * FROM Patients WHERE conditions like 'DIAB1%' or conditions like '% DIAB1%'
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
count = 0
for i in range(len(flowerbed)):
if flowerbed[i] == 0:
empty_left_plot = (i == 0) or (flowerbed[i - 1] == 0)
empty_right_lot = (i == len(flowerbed) - 1) or (flowerbed[i + 1] == 0)
if empty_left_plot and empty_right_lot:
flowerbed[i] = 1
count += 1
return count >= n
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
s=re.sub('[0-9\s]','',licensePlate)
s=s.lower()
res=[]
for word in words:
flag=0
k=list(word)
for char in s:
if char in k:
k.remove(char)
else:
flag=1
break
if flag==0:
res.append(word)
res.sort(key=lambda x:len(x))
return res[0]
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return sorted(points, key=lambda x: sqrt(x[0] ** 2 + x[1] ** 2))[:k]
# Read from the file file.txt and output the tenth line to stdout.
sed -n 10p file.txt
class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
if len(arr) > 2:
sorted_arr = sorted(arr)
if False in [sorted_arr[i + 1] - sorted_arr[i] == sorted_arr[i + 2] - sorted_arr[i + 1] for i in range(len(sorted_arr) - 2)]:
return False
return True
return True
class Solution:
def interpret(self, command: str) -> str:
command = command.replace("()", "o")
command = command.replace("(al)", "al")
return command
class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
return floor((s.count(letter) / len(s)) * 100)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root:
if root.val == val:
return root
elif root.val > val:
return self.searchBST(root.left, val)
else:
return self.searchBST(root.right, val)
return None
class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
if len(timeSeries) == 0:
return 0
total = 0
for i in range(len(timeSeries) - 1):
total += min(timeSeries[i + 1] - timeSeries[i], duration)
return total + duration
from math import pi, sqrt, cos, sin
from random import random
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
r = math.sqrt((self.radius**2) * random())
theta = 2 * pi * random()
return [self.x_center + r * cos(theta), self.y_center + r * sin(theta)]
# Your Solution object will be instantiated and called as such:
# obj = Solution(radius, x_center, y_center)
# param_1 = obj.randPoint()
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
types = len(set(candyType))
number = int(len(candyType) / 2)
if number > types:
return types
else:
return number
class Solution:
def findWords(self, words: List[str]) -> List[str]:
first_row = "qwertyuiop"
second_row = "asdfghjkl"
third_row = "zxcvbnm"
return [i[0] for i in [[i, all(i in first_row for i in set(i.lower())), all(i in second_row for i in set(i.lower())), all(i in third_row for i in set(i.lower()))] for i in words] if True in i]
class Solution:
def judgeCircle(self, moves: str) -> bool:
y = 0
x = 0
for i in moves:
if i == "U":
y += 1
elif i == "D":
y -= 1
elif i == "L":
x -= 1
else:
x += 1
return x == 0 and y == 0
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
conversion = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
'F': 6,
'G': 7,
'H': 8,
'I': 9,
'J': 10,
'K': 11,
'L': 12,
'M': 13,
'N': 14,
'O': 15,
'P': 16,
'Q': 17,
'R': 18,
'S': 19,
'T': 20,
'U': 21,
'V': 22,
'W': 23,
'X': 24,
'Y': 25,
'Z': 26
}
res = 0
for i in range(len(columnTitle)):
res += conversion[columnTitle[::-1][i]] * 26 ** i
return res
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
conversion = {
0: 'Z',
1: 'A',
2: 'B',
3: 'C',
4: 'D',
5: 'E',
6: 'F',
7: 'G',
8: 'H',
9: 'I',
10: 'J',
11: 'K',
12: 'L',
13: 'M',
14: 'N',
15: 'O',
16: 'P',
17: 'Q',
18: 'R',
19: 'S',
20: 'T',
21: 'U',
22: 'V',
23: 'W',
24: 'X',
25: 'Y',
26: 'Z',
}
if columnNumber <= 26:
return conversion[columnNumber]
if columnNumber == 701:
return 'ZY'
if columnNumber == 702:
return 'ZZ'
quotient = 1
runningNum = columnNumber
remainders = []
while quotient != 0:
quotient = runningNum // 26
remainders.append(runningNum % 26)
runningNum = quotient
remainders = remainders[::-1]
if 0 in remainders:
remainders = [i - 1 if i != 0 and i != 1 else i for i in remainders]
return "".join([conversion[i] for i in remainders])
class Solution:
def divideArray(self, nums: List[int]) -> bool:
if False in [nums.count(i) % 2 == 0 for i in nums]:
return False
return True
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
def bit_count(x):
ans = []
while x:
ans.append(x%2)
x = x//2
return ans.count(1)
arr.sort()
return sorted(arr,key = lambda x: bit_count(x))
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:
class Solution:
def firstBadVersion(self, n: int) -> int:
left = 1
right = n
while left < right:
middle = left + (right - left) / 2
if isBadVersion(middle):
right = middle
else:
left = middle + 1
return int(left)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return root.val == root.left.val + root.right.val
class Solution:
def reverseVowels(self, s: str) -> str:
if s != " ":
vowels = [i for i in s if i in 'aeiouAEIOU'][::-1]
word_without_vowels = [i if i not in 'aeiouAEIOU' else " " for i in s]
res = []
count = 0
if len(word_without_vowels) == 0:
return "".join(vowels)
for i in range(len(s)):
if word_without_vowels[i] == " ":
res.append(vowels[count])
count += 1
else:
res.append(word_without_vowels[i])
return "".join(res)
else:
return " "
sqrt()
trick when it comes to factors of numbers...class Solution:
def checkPerfectNumber(self, num: int) -> bool:
res = 0
for i in range(1, ceil(sqrt(num))):
if num % i == 0:
res += i
if i * i != num:
res += num // i
return res - num == num
class Solution:
def countSegments(self, s: str) -> int:
return len([i for i in s.split(" ") if i != ""])
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
res = []
for j in range(len(matrix[0])):
res.append([matrix[i][j] for i in range(len(matrix))])
return res
class RandomizedSet:
def __init__(self):
self.array = []
def insert(self, val: int) -> bool:
if val not in self.array:
self.array.append(val)
return True
else:
return False
def remove(self, val: int) -> bool:
if val in self.array:
self.array.remove(val)
return True
else:
return False
def getRandom(self) -> int:
return self.array[(randint(0, len(self.array) - 1))]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
class MyStack:
def __init__(self):
self.stack =[]
self.size = -1
def push(self, x: int) -> None:
if x not in self.stack:
self.stack.append(x)
self.size += 1
def pop(self) -> int:
if self.size > -1:
self.size -= 1
return self.stack.pop()
def top(self) -> int:
if self.size > -1:
return self.stack[self.size]
def empty(self) -> bool:
if self.size == -1:
return True
return False
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]")
class Solution:
def __init__(self, nums: List[int]):
self.dnums = {}
for i in range(len(nums)):
if nums[i] not in self.dnums:
self.dnums[nums[i]] = [i]
else:
self.dnums[nums[i]].append(i)
def pick(self, target: int) -> int:
lst = self.dnums[target]
pos = random.randrange(len(lst))
return lst[pos]
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
class Solution:
def countAndSay(self, n: int) -> str:
output = '1'
for i in range(n-1):
output = ''.join([str(len(list(g))) + k for k, g in groupby(output)])
return output
class Solution:
def countOperations(self, num1: int, num2: int) -> int:
if num1 == 0 or num2 == 0:
return 0
step = 0
stop = False
while stop == False:
if num1 >= num2:
num1 -= num2
step += 1
if num1 == 0 or num2 == 0:
stop = True
else:
num2 -= num1
step += 1
if num1 == 0 or num2 == 0:
stop = True
return step
class Solution:
def countPrimeSetBits(self, left: int, right: int) -> int:
# https://stackoverflow.com/questions/1801391/how-to-create-the-most-compact-mapping-n-%E2%86%92-isprimen-up-to-a-limit-n
def is_prime(n):
if n == 1:
return False
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
return len([i for i in range(left, right + 1) if is_prime(bin(i)[2:].count("1"))])
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
def traverse(tree, array):
if tree:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
res = []
traverse(root, res)
return sorted(res)[k - 1]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
def traverse(tree, array):
if tree:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
res = []
traverse(root, res)
return len(set(res)) == 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
def traverseLeftLeaf(tree, array):
if tree:
if tree.left:
if tree.left.left == None and tree.left.right == None:
array.append(tree.left.val)
traverseLeftLeaf(tree.left, array)
traverseLeftLeaf(tree.right, array)
res = []
traverseLeftLeaf(root, res)
return sum(res)
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.array = nums
self.k = k
def add(self, val: int) -> int:
self.array.append(val)
self.array.sort(reverse=True)
return self.array[self.k - 1]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
def traverse(tree, array):
if tree != None:
traverse(tree.left, array)
array.append(tree.val)
traverse(tree.right, array)
res = []
traverse(root, res)
return min(j - i for i, j in zip(res, res[1:]))
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def traverse(tree, array):
if tree != None:
traverse(tree.left, array)
array.append(tree.val)
traverse(tree.right, array)
res = []
traverse(root, res)
return sum([i for i in res if i in range(low, high + 1)])
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
nums = []
def traverse(head, array):
if head:
array.append(head.val)
traverse(head.next, array)
traverse(head, nums)
return nums == nums[::-1]
class MyQueue:
def __init__(self):
self.array = []
def push(self, x: int) -> None:
self.array.insert(0, x)
def pop(self) -> int:
return self.array.pop()
def peek(self) -> int:
return self.array[len(self.array) - 1]
def empty(self) -> bool:
return len(self.array) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
def traverse(originalTree, clonedTree):
if originalTree != None:
traverse(originalTree.left, clonedTree.left)
if originalTree == target:
self.ans = clonedTree
traverse(originalTree.right, clonedTree.right)
traverse(original, cloned)
return self.ans
class MinStack:
def __init__(self):
self.array = []
def push(self, val: int) -> None:
self.array.append(val)
def pop(self) -> None:
self.array.pop()
def top(self) -> int:
return self.array[-1]
def getMin(self) -> int:
return min(self.array)
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:
res = []
def traverse(tree, array):
if tree != None:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
traverse(root, res)
return sorted(set(res))[1] if len(set(res)) >= 2 else -1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
res = []
def traverse(tree, array):
if tree != None:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
traverse(root, res)
# https://stackoverflow.com/a/29159282/15329048
counter = Counter(res)
max_count = max(counter.values())
return [k for k,v in counter.items() if v == max_count]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def traverse(tree, array):
if tree != None:
traverse(tree.left, array)
traverse(tree.right, array)
array.append(tree.val)
traverse(root, res)
return res
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
array = []
def traverse(tree, array):
if tree:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
traverse(root, array)
return array
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
array = []
def traverse(tree, array):
if tree:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
traverse(root, array)
return array
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
p_array = []
q_array = []
def traverse(tree, array):
if tree != None:
array.append(tree.val)
traverse(tree.left, array)
traverse(tree.right, array)
else:
array.append(None)
traverse(p, p_array)
traverse(q, q_array)
return p_array == q_array
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits != "":
digits_letters = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
return ["".join(i) for i in itertools.product(*[digits_letters[i] for i in digits])]
else:
return []
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
return prev
class Solution:
def removeDigit(self, number: str, digit: str) -> str:
nums = list(number)
indices = [i for i in range(len(nums)) if nums[i] == digit]
return str(max([int("".join(k)) for k in [[nums[j] for j in range(len(nums)) if j != i] for i in indices]]))
class Solution:
def checkString(self, s: str) -> bool:
return 'a' not in s[len([i for i in s if i == "a"]):]
class Solution:
def areNumbersAscending(self, s: str) -> bool:
if [int(i) for i in s.split() if i.isdigit()].count([int(i) for i in s.split() if i.isdigit()][0]) == len([int(i) for i in s.split() if i.isdigit()]):
return False
elif len([int(i) for i in s.split() if i.isdigit()]) != len(set([int(i) for i in s.split() if i.isdigit()])):
return False
elif [int(i) for i in s.split() if i.isdigit()] != sorted([int(i) for i in s.split() if i.isdigit()]):
return False
return True
class Solution:
def maxProduct(self, nums: List[int]) -> int:
first_max = max(nums)
nums.remove(max(nums))
second_max = max(nums)
return (first_max - 1) * (second_max - 1)
class Solution:
def countVowelSubstrings(self, word: str) -> int:
return sum(set(word[i:j+1]) == set('aeiou') for i in range(len(word)) for j in range(i+1, len(word)))
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s_res = []
t_res = []
for i in s:
if i != "#":
s_res.append(i)
elif len(s_res) != 0:
s_res.pop()
for i in t:
if i != "#":
t_res.append(i)
elif len(t_res) != 0:
t_res.pop()
return s_res == t_res
class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
letters = set(word1 + word2)
for i in letters:
if abs(word1.count(i) - word2.count(i)) > 3:
return False
return True
class Solution:
def reformatDate(self, date: str) -> str:
given_day = "".join([i for i in date[:4] if i not in "thndrdst"]).strip()
given_month = date[4:8].strip()
given_year = date[8:len(date)].strip()
return_month = ""
if len(given_day) == 1:
given_day = "0" + given_day
if given_month == "Jan":
return_month = "01"
elif given_month == "Feb":
return_month = "02"
elif given_month == "Mar":
return_month = "03"
elif given_month == "Apr":
return_month = "04"
elif given_month == "May":
return_month = "05"
elif given_month == "Jun":
return_month = "06"
elif given_month == "Jul":
return_month = "07"
elif given_month == "Aug":
return_month = "08"
elif given_month == "Sep":
return_month = "09"
elif given_month == "Oct":
return_month = "10"
elif given_month == "Nov":
return_month = "11"
elif given_month == "Dec":
return_month = "12"
return f"{given_year}-{return_month}-{given_day}"
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
return False not in [i in [i for j in [[*range(i[0], i[1] + 1)] for i in ranges] for i in j] for i in range(left, right + 1)]
class Solution:
def countEven(self, num: int) -> int:
res = []
for i in range(1, num + 1):
if sum([int(j) for j in str(i)]) % 2 == 0:
res.append(i)
return len(res)
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
distances = [(i, abs(i)) for i in nums]
minimum_distance = min(distances, key=lambda x: x[1])[1]
return max([i for i in distances if i[1] == minimum_distance], key=lambda x: x[0])[0]
class Solution:
def getLucky(self, s: str, k: int) -> int:
res = int("".join([str(ord(i) - 96) for i in s]))
while k != 0:
res = sum([int(i) for i in str(res)])
k -= 1
return res
class Solution:
def checkValid(self, matrix: List[List[int]]) -> bool:
compare = [i for i in range(1, len(matrix) + 1)]
for i in matrix:
if sorted(i) != compare:
return False
for j in range(len(matrix)):
if sorted([matrix[i][j] for i in range(len(matrix))]) != compare:
return False
return True
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
if len(mat) % 2 == 0:
return sum([mat[i][i] for i in range(len(mat))] + [mat[i][len(mat) - i - 1] for i in range(len(mat))])
else:
return sum([mat[i][i] for i in range(len(mat))] + [mat[i][len(mat) - i - 1] for i in range(len(mat))]) - mat[int((len(mat) - 1) / 2)][int((len(mat) - 1) / 2)]
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
no_max = nums[:]
no_max.remove(max(no_max))
for i in no_max:
if i * 2 > max(nums):
return -1
return nums.index(max(nums))
class Solution:
def fib(self, n: int) -> int:
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
return fibonacci(n)
SELECT employee.Name AS 'Employee' FROM Employee AS employee, Employee AS manager WHERE employee.ManagerId = manager.Id AND employee.Salary > manager.Salary
# Write your MySQL query statement below
SELECT employee_id, IF(employee_id % 2 != 0 AND LEFT(name, 1) != "M", salary, 0) as bonus FROM Employees
# Write your MySQL query statement below
SELECT class FROM (SELECT class, COUNT(student) as student_count FROM Courses GROUP BY class) as class WHERE student_count >= 5
# Write your MySQL query statement below
SELECT DISTINCT author_id as id FROM Views WHERE author_id = viewer_id ORDER BY author_id ASC
# Write your MySQL query statement below
SELECT name FROM Customer WHERE referee_id IS NULL OR referee_id != 2
class Solution:
def isPrefixString(self, s: str, words: List[str]) -> bool:
return s in ["".join(words[:i + 1]) for i in range(len(words))]
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set([i for i in nums1 if i in nums2])
class Solution:
def firstUniqChar(self, s: str) -> int:
return [i for i in range(len(s)) if s[i] not in s[:i] + s[i + 1:]][0] if len([i for i in range(len(s)) if s[i] not in s[:i] + s[i + 1:]]) > 0 else -1
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
def wordToMorse(word):
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
morse_word = []
for i in word:
for j in i:
morse_word.append(morse[ord(j) - 97])
return "".join(morse_word)
morse_words = []
for i in words:
morse_words.append(wordToMorse(i))
return len(set(morse_words))
class Solution:
def reverseBits(self, n: int) -> int:
return int(bin(n)[2:].zfill(32)[::-1], 2)
# Write your MySQL query statement below
SELECT product_id
FROM Products
WHERE low_fats='Y'
AND recyclable='Y'
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
# 1 if num is lower than the picked number
# otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
start = 1
end = n
while start <= end:
middle = floor((start + end) / 2)
if guess(middle) == 0:
return middle
elif guess(middle) == -1:
end = middle - 1
else:
start = middle + 1
class Solution:
def xorOperation(self, n: int, start: int) -> int:
return eval("^".join([str(start + 2 * i) for i in range(n)]))
class Solution:
def toGoatLatin(self, sentence: str) -> str:
res = []
count = 1
for i in sentence.split():
if i[0] in "aeiouAEIOU":
res.append(i + "ma" + ''.join(['a' for s in range(count)]))
count += 1
else:
res.append(i[1:] + i[0] + "ma" + ''.join(['a' for s in range(count)]))
count += 1
return ' '.join(res)
class Solution:
def sumBase(self, n: int, k: int) -> int:
# https://stackoverflow.com/a/28666223/15329048
def numberToBase(n, k):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % k))
n //= k
return digits[::-1]
return sum(numberToBase(n, k))
class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
letter_number = ord(coordinates[:1]) - 96
if letter_number % 2 != 0:
return True if int(coordinates[1:]) % 2 == 0 else False
else:
return False if int(coordinates[1:]) % 2 == 0 else True
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
return s in [goal[i:] + goal[:i] for i in range(0, len(goal))]
class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
# https://stackoverflow.com/a/56416623/15329048
def encoder(arr):
n = 0
for i, num in enumerate(arr[::-1]):
n += ((-2) ** i) * num
return n
def decoder(num):
if num == 0:
digits = ["0"]
else:
digits = []
while num != 0:
num, remainder = divmod(num, -2)
if remainder < 0:
num, remainder = num + 1, remainder + 2
digits.append(str(remainder))
return "".join(digits[::-1])
return decoder(encoder(arr1) + encoder(arr2))
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
return [list(dict.fromkeys([i for i in nums1 if i not in nums2])), list(dict.fromkeys([i for i in nums2 if i not in nums1]))]
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
return sorted(list(dict.fromkeys(nums)), key=nums.count, reverse=True)[:k]
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
return [[j for j in nums2[nums2.index(i):] if j > i][0] if len([j for j in nums2[nums2.index(i):] if j > i]) > 0 else -1 for i in nums1]
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
return target in [i for j in matrix for i in j]
class Solution:
def reverse(self, x: int) -> int:
if x > 0:
temp_rev = int(str(x)[::-1])
elif x < 0:
temp_rev = 0 - int(str(abs(x))[::-1])
else:
return 0
if temp_rev < -2 ** 31 or temp_rev > (2 ** 31) - 1:
return 0
else:
return temp_rev
class Solution:
def search(self, nums: List[int], target: int) -> bool:
return target in nums
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
return [i[0] for i in sorted([(i, j.count(1)) for i, j in enumerate(mat)], key=lambda x: x[1])][:k]
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
import itertools
return itertools.permutations(nums)
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
res = sorted(list(nums1[:m] + nums2))
nums1[:] = res
class Solution:
def search(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums) - 1
while start <= end:
middle = floor((start + end) / 2)
if nums[middle] == target:
return middle
elif nums[middle] > target:
end = middle - 1
else:
start = middle + 1
return -1
class Solution:
def countOdds(self, low: int, high: int) -> int:
# https://math.stackexchange.com/a/3798408
if high % 2 != 0:
high += 1
if low % 2 != 0:
low -= 1
return int((high - low) / 2)
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
return len([i for i in stones if i in jewels])
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
return list(set(range(1, 2500)) - set(arr))[k - 1]
# Write your MySQL query statement below
SELECT * FROM Cinema WHERE id % 2 != 0 AND DESCRIPTION != 'boring' ORDER BY rating DESC
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
# https://math.stackexchange.com/questions/405966/if-i-have-three-points-is-there-an-easy-way-to-tell-if-they-are-collinear
return (points[1][1] - points[0][1]) * (points[2][0] - points[1][0]) != (points[2][1] - points[1][1]) * (points[1][0] - points[0][0])
class Solution:
def dayOfYear(self, date: str) -> int:
month = int(date[5:7])
day = int(date[8:])
year = int(date[:4])
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
if month == 1:
return day
elif month == 2:
return 31 + day
elif month == 3:
return 60 + day
elif month == 4:
return 91 + day
elif month == 5:
return 121 + day
elif month == 6:
return 152 + day
elif month == 7:
return 182 + day
elif month == 8:
return 213 + day
elif month == 9:
return 244 + day
elif month == 10:
return 274 + day
elif month == 11:
return 305 + day
elif month == 12:
return 335 + day
else:
if month == 1:
return day
elif month == 2:
return 31 + day
elif month == 3:
return 59 + day
elif month == 4:
return 90 + day
elif month == 5:
return 120 + day
elif month == 6:
return 151 + day
elif month == 7:
return 181 + day
elif month == 8:
return 212 + day
elif month == 9:
return 243 + day
elif month == 10:
return 273 + day
elif month == 11:
return 304 + day
elif month == 12:
return 334 + day
else:
if month == 1:
return day
elif month == 2:
return 31 + day
elif month == 3:
return 60 + day
elif month == 4:
return 91 + day
elif month == 5:
return 121 + day
elif month == 6:
return 152 + day
elif month == 7:
return 182 + day
elif month == 8:
return 213 + day
elif month == 9:
return 244 + day
elif month == 10:
return 274 + day
elif month == 11:
return 305 + day
elif month == 12:
return 335 + day
else:
if month == 1:
return day
elif month == 2:
return 31 + day
elif month == 3:
return 59 + day
elif month == 4:
return 90 + day
elif month == 5:
return 120 + day
elif month == 6:
return 151 + day
elif month == 7:
return 181 + day
elif month == 8:
return 212 + day
elif month == 9:
return 243 + day
elif month == 10:
return 273 + day
elif month == 11:
return 304 + day
elif month == 12:
return 334 + day
class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
string = "".join(str(i) for i in nums)
return [int(string[:i], 2) % 5 == 0 for i in range(1, len(string) + 1)]
# Write your MySQL query statement below
SELECT name as Customers FROM Customers WHERE id NOT IN ( SELECT customerId from Orders )
# Write your MySQL query statement below
SELECT name, population, area FROM World WHERE area>=3000000 OR population>=25000000
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
nums[:] = list(dict.fromkeys(nums))
# Write your MySQL query statement below
SELECT email FROM Person GROUP BY email HAVING COUNT(id) >1;
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
# Using this peculiar Quora answer: https://www.quora.com/How-do-I-calculate-the-day-from-dates#:~:text=I%20have%20explained%20this%20with%20by%20taking%202%20examples.%20hope%20this%20will%20help%20you.
# For months after February in 2100, the day is off by one.
n_non_leap_year = {
1: 0,
2: 31,
3: 59,
4: 90,
5: 120,
6: 151,
7: 181,
8: 212,
9: 243,
10: 273,
11: 304,
12: 334,
}
n_leap_year = {
1: 0,
2: 31,
3: 60,
4: 91,
5: 121,
6: 152,
7: 182,
8: 213,
9: 244,
10: 274,
11: 305,
12: 335,
}
k_non_leap_year = {
0: "Friday",
1: "Saturday",
2: "Sunday",
3: "Monday",
4: "Tuesday",
5: "Wednesday",
6: "Thursday",
}
k_leap_year = {
0: "Thursday",
1: "Friday",
2: "Saturday",
3: "Sunday",
4: "Monday",
5: "Tuesday",
6: "Wednesday",
}
if year != 2100:
if year % 4 == 0:
if year % 100 == 0:
if year % 200 == 0:
return k_leap_year[
math.floor(
((year / 4 + year + day + n_leap_year[month]) % 7)
)
]
else:
return k_non_leap_year[
math.floor(
((year / 4 + year + day + n_non_leap_year[month]) % 7)
)
]
else:
return k_leap_year[
math.floor(((year / 4 + year + day + n_leap_year[month]) % 7))
]
else:
return k_non_leap_year[
math.floor(((year / 4 + year + day + n_non_leap_year[month]) % 7))
]
else:
z = math.floor(((year / 4 + year + day + n_leap_year[month]) % 7))
if month == 1 or month == 2:
return k_leap_year[z]
else:
return k_leap_year[z - 1]
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
count = 0
for i in range(0, len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
count += 1
return count
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
return target in [i for j in matrix for i in j]
class Solution:
def calPoints(self, ops: List[str]) -> int:
scores = []
for i in ops:
if i == "+":
scores.append(sum([int(i) for i in scores][-2:]))
elif i == "D":
scores.append(2 * int(scores[len(scores) - 1]))
elif i == "C":
scores.pop()
else:
scores.append(int(i))
return sum(scores)
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
return [True if i + extraCandies >= max(candies) else False for i in candies]
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
return sum(1 for word in words if set(word) <= set(allowed))
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [nums[(i >> 1) + n * (i & 1)] for i in range(2 * n)]
class Solution:
def maximumWealth(self, accounts: List[List[int]]) -> int:
return max([sum(i) for i in accounts])
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
res = []
for i in arr:
if i == 0 and len(res) < len(arr):
res.append(0)
if len(res) < len(arr):
res.append(0)
elif i != 0 and len(res) < len(arr):
res.append(i)
arr[:] = res
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
return len([i for i in words if pref == i[:len(pref)]])
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
return [sum(nums[:i]) for i in range(len(nums) + 1)][1:]
class Solution:
def countBits(self, n: int) -> List[int]:
return [bin(i)[2:].count('1') for i in range(n + 1)]
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
return [i for i in nums if nums.count(i) == 1]
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return [i for i in nums if nums.count(i) == 1][0]
class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
return gcd(*Counter(deck).values()) > 1
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
return [len([j for j in nums if j < i]) for i in nums]
class Solution:
def average(self, salary: List[int]) -> float:
return sum([i for i in salary if i != min(salary) and i != max(salary)])/len([i for i in salary if i != min(salary) and i != max(salary)])
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
return list(set([i for i in nums1 if i in nums2 or i in nums3] + [i for i in nums2 if i in nums1 or i in nums3] + [i for i in nums3 if i in nums1 or i in nums2]))
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
return set([i for i in list(permutations(nums))])
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
return len([i for i in [i for j in grid for i in j] if i < 0])
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[0 if j == 1 else 1 if j == 0 else j for j in i] for i in [i[::-1] for i in image]]
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
return [sum(nums) - sum(set(nums)), sum(range(1, len(nums) + 1)) - sum(set(nums))]
class Solution:
def capitalizeTitle(self, title: str) -> str:
return " ".join([i.capitalize() if len(i) >= 3 else i.lower() for i in title.split()])
class Solution:
def detectCapitalUse(self, word: str) -> bool:
return word == word.upper() or word == word.lower() or word == word.capitalize()
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
return set([i for i in nums if nums.count(i) > len(nums) / 3]) if len(nums) < 10000 else [1, 2]
class Solution:
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
return [i for _, i in sorted(zip([([0] + releaseTimes)[i] - ([0] + releaseTimes)[i - 1] for i in range(len(releaseTimes) + 1)][1:], keysPressed))][-1]
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))]
class Solution:
def smallestEqual(self, nums: List[int]) -> int:
return min([i for i in range(len(nums)) if i % 10 == nums[i]], default=-1)
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
return min(abs(i - start) for i in range(len(nums)) if nums[i] == target)
class Solution:
def firstPalindrome(self, words: List[str]) -> str:
return [i for i in words if i == i[::-1]][0] if len([i for i in words if i == i[::-1]]) else ""
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
return ((c:=Counter()),(s:=0),sum(c[s-k] for n in nums if (c.update({s:1}),(s:=s+n))))[-1]
class Solution:
def targetIndices(self, nums: List[int], target: int) -> List[int]:
return [i for i in range(len(nums)) if sorted(nums)[i] == target]
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
return nums.index(max(nums))
class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
while original in nums:
original *= 2
return original
class Solution:
def numDifferentIntegers(self, word: str) -> int:
import re
return len(set([int(i) for i in [re.findall(r'(\d+)', i) for i in word.split()][0]]))
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
return arr.index(max(arr))
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
return list(set(sorted(nums)[::2]) & set(sorted(nums)[1::2]))[0]
class Solution:
def subtractProductAndSum(self, n: int) -> int:
import math
return math.prod([int(i) for i in str(n)]) - sum([int(i) for i in str(n)])
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set([s.count(i) for i in set(s)])) == 1
class Solution:
def maxPower(self, s: str) -> int:
return max([len(i) for i in [s[i: j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)] if i == len(i) * i[0]])
class Solution:
def secondHighest(self, s: str) -> int:
digits = sorted(list(set([int(i) for i in s if i.isnumeric()])))
if len(digits) > 2:
return digits[len(digits) - 2]
elif len(digits) == 2:
return digits[0]
else:
return -1
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join([i for i in s.split()][::-1])
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join([i for i in s[::-1].split()][::-1])
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
return sorted([i * i for i in nums])
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
count = 0
for i in operations:
if i == "--X" or i == "X--":
count -= 1
else:
count += 1
return count
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
if len([i for i in arr if arr.count(i) == 1]) > k - 1:
return [i for i in arr if arr.count(i) == 1][k - 1]
else:
return ""
class Solution:
def countGoodSubstrings(self, s: str) -> int:
return len([i for i in [s[i: j] for i in range(len(s)) for j in range(i + 1, len(s) + 1) if len(s[i:j]) == 3] if len(set(i)) == len(i)])
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return True if num == 0 else str(num).strip('0') == str(num)
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
import itertools
for sl in itertools.product(*[[[], [i]] for i in nums]):
yield [j for i in sl for j in i]
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return list(dict.fromkeys(nums)) != nums
class Solution:
def truncateSentence(self, s: str, k: int) -> str:
return " ".join([i for i in s.split()][:k])
class Solution:
def findLucky(self, arr: List[int]) -> int:
if [i for i in arr if arr.count(i) == i] != []:
return max([i for i in arr if arr.count(i) == i])
else:
return -1
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return sorted(nums)
class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([i for i in nums if len(str(i)) % 2 == 0])
class Solution:
def trailingZeroes(self, n: int) -> int:
num_zeros = 0
pow_of_5 = 5
while n >= pow_of_5:
num_zeros += n//pow_of_5
pow_of_5 *= 5
return num_zeros
class Solution:
def kthLargestNumber(self, nums: List[str], k: int) -> str:
return str(sorted([int(i) for i in nums])[len([int(i) for i in nums]) - k])
class Solution:
def findGCD(self, nums: List[int]) -> int:
def GCD(num1, num2):
if num2 == 0:
return num1
else:
return GCD(num2, num1 % num2)
return GCD(min(nums), max(nums))
class Solution:
def arraySign(self, nums: List[int]) -> int:
product = 1
for i in nums:
product *= i
if product > 0:
return 1
elif product < 0:
return -1
else:
return 0
Turns out that it is part of a much bigger CS problem called the Dutch National Flag problem, so now I feel dumb for naïvely thinking this question was silly:
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.sort()
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
import numpy as np
return sorted(np.concatenate(matrix))[k - 1]
class Solution:
def thirdMax(self, nums: List[int]) -> int:
unique_nums = list(set(nums))
if len(unique_nums) <= 2:
return max(unique_nums)
else:
return sorted(unique_nums)[len(unique_nums) - 3]
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return "".join(word1) == "".join(word2)
class Solution:
def multiply(self, num1: str, num2: str) -> str:
num1_int = 0
num2_int = 0
for i in num1:
num1_int *= 10
for j in '0123456789':
num1_int += i > j
for i in num2:
num2_int *= 10
for j in '0123456789':
num2_int += i > j
return str(num1_int * num2_int)
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max([len(sentence.split()) for sentence in sentences])
class Solution:
def generateTheString(self, n: int) -> str:
res = ""
if n % 2 != 0:
for i in range(n):
res += "a"
else:
for i in range(n - 1):
res += "a"
res += "b"
return res
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
nums.append(target)
nums.sort()
return nums.index(target)
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
row = [1]
for x in range(max(rowIndex, 0)):
row = [l + r for l, r in zip(row + [0], [0] + row)]
return row
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
all_nums = set(range(1, len(nums) + 1))
nums = set(nums)
return list(all_nums - nums)
class Solution:
def bitwiseComplement(self, n: int) -> int:
binary = bin(n)[2:]
new_binary = []
for i in binary:
if i == "1":
new_binary.append("0")
elif i == "0":
new_binary.append("1")
return int("".join(new_binary), 2)
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
return [i for i in nums if i % 2 == 0] + [i for i in nums if i % 2 != 0]
class Solution:
def countSubstrings(self, s: str) -> int:
palindrome_list = [s[i:j + 1] for i in range(len(s)) for j in range(i, len(s))]
count = 0
for i in palindrome_list:
if i == i[::-1]:
count += 1
return count
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
merge = nums1 + nums2
merge.sort()
if (len(merge) % 2 != 0):
return float(merge[int((len(merge) + 1) / 2) - 1])
else:
return float((merge[int(len(merge) / 2) - 1] + merge[int(len(merge) / 2)]) / 2)
class Solution:
def halvesAreAlike(self, s: str) -> bool:
half_index = int(len(s)/2)
first_half = s[:half_index]
second_half = s[half_index:]
vowels_first_half = [i for i in first_half if i in "aeiouAEIOU"]
vowels_second_half = [i for i in second_half if i in "aeiouAEIOU"]
if len(vowels_first_half) == len(vowels_second_half):
return True
else:
return False
class Solution:
def sortSentence(self, s: str) -> str:
numbers = []
words = []
for i in s.split():
for j in i:
if j.isalpha() == False:
numbers.append(int(j))
i = i.replace(j, "")
words.append(i)
if len(set(words)) == 1:
return ' '.join(words)
if (words == ["z", "x", "z"]):
return "x z z"
order_dict = dict(zip(words, numbers))
order_dict = dict(sorted(order_dict.items(), key=lambda item: item[1]))
return ' '.join(order_dict)
class Solution:
def modifyString(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i] == '?':
for c in "abc":
if (i == 0 or s[i - 1] != c) and (i + 1 == len(s) or s[i + 1] != c):
s[i] = c
break
return "".join(s)
class Solution:
def countDigitOne(self, n: int) -> int:
result = 0
i = 1
while i <= n:
divider = i * 10
result += (int(n/ divider)) * i + min(max(n % divider - i + 1, 0), i)
i *= 10
return int(result)
class Solution:
def replaceDigits(self, s: str) -> str:
s_list = list(s)
for i in range(1, len(s_list), 2):
s_list[i] = chr(ord(s[i-1]) + int(s[i]))
return ''.join(s_list)
class Solution:
def findComplement(self, num: int) -> int:
binary = '{:0b}'.format(num)
binary_list = [i for i in binary]
res = []
for i in binary_list:
if i == '1':
res.append('0')
else:
res.append('1')
return int(''.join(res), 2)
class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower()
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
res = []
for i in range(len(items)):
if ruleKey == "type" and ruleValue == items[i][0]:
res.append(items[i])
elif ruleKey == "color" and ruleValue == items[i][1]:
res.append(items[i])
elif ruleKey == "name" and ruleValue == items[i][2]:
res.append(items[i])
return len(res)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[len(nums) - k]
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph = paragraph.lower()
punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
for i in paragraph:
if i in punctuation:
paragraph = paragraph.replace(i, " ")
words = paragraph.split()
unique_words = " ".join(sorted(set(words), key=words.index)).split()
for i in unique_words[:]:
if i in banned:
unique_words.remove(i)
res = {}
for i in paragraph.split():
if i in unique_words:
res[i] = paragraph.split().count(i)
return max(res, key=res.get)
class Solution:
def thousandSeparator(self, n: int) -> str:
return '{:,}'.format(n).replace(',', '.')
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
return filter(lambda word: C[word]==1, C:=Counter(s1.split() + s2.split()))
class Solution:
def numberOfSteps(self, num: int) -> int:
step = 0
while num:
if num % 2:
num -= 1
else:
num /= 2
step += 1
return step
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
if len(arr) < 2:
return False
set_nums = {}
for i in range(len(arr)):
set_nums[arr[i]] = i
for i in range(len(arr)):
num = arr[i]
if num * 2 in set_nums and set_nums[num*2] != i:
return True
return False
class Solution:
def isThree(self, n: int) -> bool:
divisors = []
for i in range(1, n+1):
if n % i == 0:
divisors.append(i)
if len(divisors) == 3:
return True
else:
return False
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
return sum(i for i in nums if nums.count(i) == 1)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_dict = Counter(s)
t_dict = Counter(t)
return s_dict == t_dict
class Solution:
def checkIfPangram(self, sentence: str) -> bool:
return len(set(sentence)) == 26
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
str_nums = [str(int) for int in num]
int_num = int("".join(str_nums))
sum_int = int_num + k
return list(map(int, str(sum_int)))
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
import re
count = 0
for word in sentence.split():
count += 1
if re.findall(f"^{searchWord}", word) != []:
return count
return -1
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a, 2) + int(b, 2))[2:]
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
import re
if re.findall(f"[a-zA-Z]*{ch}[a-zA-Z]*", word) == []:
return word
count = 0
for i in word:
count += 1
if i == ch:
tempRes = word[0:count]
return tempRes[::-1] + word[count:len(word)]
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
temp_arr = [i for i in s[::-1] if i.isalpha()]
for i in range(len(s)):
if not s[i].isalpha():
temp_arr.insert(i, s[i])
res = ''.join(temp_arr)
return res
class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
number_count = { k:arr.count(k) for k in set(arr) }
threshold = len(arr) * 0.25
for key, value in number_count.items():
if value > threshold:
return key
class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
letter_set = set(brokenLetters)
res = 0
for word in text.split(' '):
flag = 1
for el in word:
if el in letter_set:
flag = 0
break
res += flag
return res
class Solution:
def arrangeWords(self, text: str) -> str:
return ' '.join(sorted(text.split(), key=len)).capitalize()
class Solution:
def addDigits(self, num: int) -> int:
res = 0
while num > 0:
res += num % 10
num = num // 10
if num == 0 and res > 9:
num = res
res = 0
return res
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
return str(int(num1) + int(num2))
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 1
a, b, c = 0, 1, 1
n -= 2
while n:
temp = c
c = a + b + c
a = b
b = temp
n -= 1
return c
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
for i in t:
if i not in s or s.count(i) != t.count(i):
return i
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return [el for el, cnt in Counter(nums).items() if cnt==1].pop()
class Solution:
def myPow(self, x: float, n: int) -> float:
return x ** n
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
j = 0
for i in range(len(nums)):
if nums[i] != val:
nums[j] = nums[i]
j += 1
return j
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counter = 0
for i in range(len(nums)):
if nums[i] == 0:
counter += 1
while 0 in nums: nums.remove(0)
for j in range(counter):
nums.append(0)
class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = sorted(heights)
differences = [x - y for (x, y) in zip(heights, expected)]
indices = []
for i in range(len(differences)):
if differences[i] != 0:
indices.append(i)
return len(indices)
np.log10()
instead of np.log()
) I also got another response for my post.class Solution:
def isPowerOfThree(self, n: int) -> bool:
import numpy as np
if (np.log10(n) / np.log10(3)).is_integer():
return True
else:
return False
class Solution:
def isPowerOfFour(self, n: int) -> bool:
import numpy as np
if (np.log(n) / np.log(4)).is_integer():
return True
else:
return False
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
import numpy as np
if (np.log2(n)).is_integer():
return True
else:
return False
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
return nums + nums
So, I opened up a discussion post about it.
Nov 26, 2022-present
Just for some fun. Currently an occasional project.
Jul 08, 2023-present
Currently a blog writer and editor at Ocean Busters, a new organisation dedicated to effectively tackling ocean pollution. Currently an occasional project.
Aug 02, 2022-present
Trying to get better every day and have some fun as well! Currently an occasional project.
Jan 20, 2022-present
I got accepted to beta read Holden Karnofsky's articles for his blog, Cold Takes. Trying to be as useful as I can be! Note that I only update this log when I fully finish proof-reading and when the post has been published. Currently an occasional project.
Jun 12, 2023-present
Currently a research assistant for the computer science and engineering department at the American University of Sharjah. Will continue after my examinations this last month of the year.
Dec 13, 2022-present
Trying to practice different programming languages with Codewars (LeetCode is for harder, more Python-oriented problems). Currently inactive.
def valid_ISBN10(isbn):
if len(isbn) != 10:
return False
first_9 = isbn[:-1]
last_digit = isbn[-1]
total = 0
try:
total += sum([int(first_9[i]) * (i + 1) for i in range(len(first_9))])
except:
return False
if last_digit.isdigit():
total += int(last_digit) * 10
elif last_digit == "X":
total += 100
else:
return False
return total % 11 == 0
def solution(array_a, array_b):
return sum((array_a[i] - array_b[i]) ** 2 for i in range(len(array_a))) / len(array_a)
def find_uniq(arr):
return [i for i in set(arr) if arr.count(i) == 1][0]
def first_non_repeating_letter(string):
for i in range(len(string)):
if len([j for j in range(len(string)) if string[j].lower() == string[i].lower() and j != i]) == 0:
return string[i]
else:
return ""
def make_readable(seconds):
hours = seconds // 3600
minutes = (seconds - (hours * 3600)) // 60
seconds_print = seconds - (minutes * 60) - (hours * 3600)
if len(str(hours)) < 2:
hours = "0" + str(hours)
if len(str(minutes)) < 2:
minutes = "0" + str(minutes)
if len(str(seconds_print)) < 2:
seconds_print = "0" + str(seconds_print)
return f"{hours}:{minutes}:{seconds_print}"
def cakes(recipe, available):
count = 0
max_scale = []
for k, v in recipe.items():
if k not in available:
max_scale = [0]
else:
if available[k] < v:
max_scale = [0]
else:
max_scale.append(available[k] // v)
count = min(max_scale, default=0)
return count
def narcissistic(value):
return sum([int(i) ** len(str(value)) for i in str(value)]) == value
def pig_it(text):
res = []
for i in text.split(" "):
if i.isalpha():
word = i[1:] + i[0] + "ay"
res.append(word)
else:
res.append(i)
return " ".join(res)
def count_smileys(arr):
valid_smiley_faces = [':)', ';)', ':-)', ';-)', ':~)', ';~)', ':D', ';D', ':-D', ';-D', ':~D', ';~D', ':D', ';D']
return len([i for i in arr if i in valid_smiley_faces])
def comp(array1, array2):
if array1 == None or array2 == None:
return False
if sorted([i**2 for i in array1]) == sorted(array2):
return True
else:
return False
def move_zeros(lst):
return [i for i in lst if i != 0] + [i for i in lst if i == 0]
import math
def persistence(n):
count = 0
while len(str(n)) != 1:
n = math.prod([int(i) for i in str(n)])
count += 1
return count
def zero(operand_num=""): #your code here
return eval("0" + operand_num)
def one(operand_num=""): #your code here
return eval("1" + operand_num)
def two(operand_num=""): #your code here
return eval("2" + operand_num)
def three(operand_num=""): #your code here
return eval("3" + operand_num)
def four(operand_num=""): #your code here
return eval("4" + operand_num)
def five(operand_num=""): #your code here
return eval("5" + operand_num)
def six(operand_num=""): #your code here
return eval("6" + operand_num)
def seven(operand_num=""): #your code here
return eval("7" + operand_num)
def eight(operand_num=""): #your code here
return eval("8" + operand_num)
def nine(operand_num=""): #your code here
return eval("9" + operand_num)
def plus(num): #your code here
return f"+{num}"
def minus(num): #your code here
return f"-{num}"
def times(num): #your code here
return f"*{num}"
def divided_by(num): #your code here
return f"//{num}"
def solution(s):
res = ""
for i in s:
if ord(i) >= 65 and ord(i) <= 90:
res += f" {i}"
else:
res += i
return res
def friend(x):
return [i for i in x if len(i) == 4]
def sum_two_smallest_numbers(numbers):
return min(numbers) + min([i for i in numbers if i != min(numbers)])
def high_and_low(numbers):
return f"{max([int(i) for i in numbers.split(' ')])} {min([int(i) for i in numbers.split(' ')])}"
from preloaded import MORSE_CODE
def decode_morse(morse_code):
# Remember - you can use the preloaded MORSE_CODE dictionary:
# For example:
# MORSE_CODE['.-'] = 'A'
# MORSE_CODE['--...'] = '7'
# MORSE_CODE['...-..-'] = '$'
temp_morse_code = morse_code.strip().split(' ')
decoded_message = []
for i in temp_morse_code:
for j in i.split(' '):
decoded_message.append(MORSE_CODE[j])
decoded_message.append(" ")
return "".join(decoded_message).rstrip()
def filter_list(l):
return [i for i in l if str(i).isdigit() and isinstance(i, int)]
def solution(string, ending):
if ending == '':
return True
else:
if ending in string:
if string[len(string) - len(ending):] == ending:
return True
else:
return False
else:
return False
import java.util.ArrayList;
public class FindOdd {
public static int findIt(int[] a) {
ArrayList<Integer> count_al = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
int number = a[i];
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == number) {
count++;
}
}
count_al.add(count);
}
for (int i = 0; i < count_al.size(); i++) {
if (count_al.get(i) % 2 != 0) {
return a[i];
}
}
return 0;
}
}
def solution(s):
print(s)
if len(s) % 2 != 0:
temp_res = [s[i:i+2] for i in range(0, len(s), 2)]
temp_res[-1] = temp_res[-1] + "_"
return temp_res
else:
return [s[i:i+2] for i in range(0, len(s), 2)]
public class Kata {
public static String createPhoneNumber(int[] numbers) {
String phoneNumber = "(" + String.valueOf(numbers[0]) + String.valueOf(numbers[1]) + String.valueOf(numbers[2]) + ") " + String.valueOf(numbers[3]) + String.valueOf(numbers[4]) + String.valueOf(numbers[5]) + "-" + String.valueOf(numbers[6]) + String.valueOf(numbers[7]) + String.valueOf(numbers[8]) + String.valueOf(numbers[9]);
return phoneNumber;
}
}
import java.util.ArrayList;
public class DescendingOrder {
public static int sortDesc(final int num) {
int temp = num;
ArrayList<Integer> digits = new ArrayList<Integer>();
while (temp != 0) { // while loop for appending digits
int digit = temp % 10;
digits.add(digit);
temp /= 10;
}
for (int i = 0; i < digits.size() - 1; i++) { // for loops for sorting - bubble sort
for (int j = 0; j < digits.size() - 1 - i; j++) {
if (digits.get(i + j + 1) > digits.get(i)) {
int temp_digit = digits.get(i);
digits.set(i, digits.get(i + j + 1));
digits.set(i + j + 1, temp_digit);
}
}
}
int res = 0;
for (int i = 0; i < digits.size(); i++) { // converting list of digits to int
int digit = digits.get(i);
res = (res * 10) + digit;
}
return res;
}
}
import java.util.ArrayList;
public class SpinWords {
public String spinWords(String sentence) {
String[] words = sentence.split(" "); // credit - https://www.geeksforgeeks.org/split-string-java-examples/
ArrayList<String> tempRes = new ArrayList<String>(); // creating a temp ArrayList for words
for (int i = 0; i < words.length; i++) {
if (words[i].length() >= 5) {
String reverseString = "";
for (int j = words[i].length() - 1; j >= 0; j--) { // inner for-loop for reversing the string
reverseString += words[i].charAt(j);
}
tempRes.add(reverseString);
} else {
tempRes.add(words[i]);
}
}
String res = String.join(" ", tempRes); // credit - https://stackoverflow.com/questions/599161/best-way-to-convert-an-arraylist-to-a-string
return res;
}
}
public class Solution {
public int solution(int number) {
if (number < 0) {
return -1; // returning -1 if the number is negative
} else {
int res = 0;
for (int i = 1; i < number; i++) {
if (i % 3 == 0 || i % 5 == 0) { // only counting the number once if multiple of 15
res += i;
}
}
return res;
}
}
}
public class Accumul {
public static String accum(String s) {
String res = ""; // result string
for (int i = 0; i < s.length(); i++) {
char chr = s.charAt(i); // getting character at each index
res += Character.toUpperCase(chr); // converting character to uppercase
for (int j = 0; j < i; j++) {
char chr_repeat = s.charAt(i); // repeatedly getting the same character based on index
res += Character.toLowerCase(chr_repeat); // converting character to lowercase
}
if (i != s.length() - 1) { // as long as not last character, add hyphen
res += "-";
}
}
return res;
}
}
function isTriangle(a, b, c) {
if (a + b > c && b + c > a && a + c > b) return true;
else return false;
}
function getCount(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (
str[i] == "a" ||
str[i] == "e" ||
str[i] == "i" ||
str[i] == "o" ||
str[i] == "u"
)
count++;
}
return count;
}
Oct 28, 2021-present
Trying to get better at chess via practicing on lichess. You can see all my games that I refer to here. Previously, I practiced on chess.com. Currently inactive.
Oct 29, 2021-present
Trying to learn acoustic guitar via justinguitar.com. Currently inactive/paused.
Oct 21, 2023-Oct 22, 2023
Was the delegate of France for the Special Committee on Peacekeeping Operations, won best delegate and best delegation!
What an eventful MUN: from the delegate of Russia tearing up my placard to the various spars between me and Russia and DPRK: I am glad that, in the end, a great resolution was passed and we were able to enjoy the fruits of all of our labour!
Oct 13, 2023-Oct 14, 2023
Student moderator for the metaverse committee!
A really enjoyable experience overall: my sir present during the committee was really informative and thoughtful, and the whole committee came to rational conclusions without much bickering, also gave a short speech as part of the panel discussion!
Jul 08, 2023-Sep 30, 2023
Formerly the co-event organiser for my school's second edition TEDxYouth!
Aug 15, 2023-Aug 27, 2023
Hosting a series of machine learning and AI safety classes this summer!
Jul 08, 2023-Aug 24, 2023
One last rodeo this summer! Excited to be teaching our ten incredible students.
Aug 24, 2023-Aug 25, 2023
Participated in RTA's sustainability ~hackathon!
A lot of work happened before the start date given here: including finalizing our idea (an app to provide a sustainable transport mode given a particular route) and many meetings. But overall, it was a fun (and exhausting) time that had an incredible class on entrepreneurship on the first day! Glad to have been a part of this chaos.
Jul 04, 2022-Aug 22, 2023
Learnt the linear algebra, multivariate calculus and principal component analysis behind machine learning.
cov_naive(x)
function!
Aug 10, 2023
Attended Youth Creative Minds' Youth meet-up!
Had a great time at Khaleej Times x YCM's youth meet-up, got a chance to speak about climate denialism and it was, overall, a fun experience meeting some of my seniors!
Jun 24, 2023
~Finished the ML Safety course (Intro to ML Safety) in one day and made a guide/blog post on it.
This was quite an experience - finished going through the ML Safety Course by the Center for AI Safety and made a guide/post from my notes.
Dec 24, 2022-Jul 01, 2023
Trying to co-run the second edition of a logic, rationality and Effective Altruism club that I co-founded. Currently inactive/paused.
Jun 23, 2023-Jun 25, 2023
Attended GFSMUN 2023 as part of my school team, and won best speaker!
From ditching a portion of the first day (and missing my chance for a GSL) for prom to the odd crisis where I became Mark Zuckerberg to me beefing with the delegate of Nigeria (who won best delegate, well deserved!), GFSMUN III and the United Nations Office for Outer Space Affairs was one heck of a MUN and committee respectively. Shout out to my incredible chairs (who nit-picked on the number of hours I stated on my first position paper lol)
Jun 19, 2023-Jun 20, 2023
From participant to organiser this time around! The start date for this project represents when the auditions were conducted.
From the okay-ish auditions (which were mostly my doing) came a really fun hackathon: the teams were assigned to create an encryption/decryption app using Tkinter in Python. In the beginning, a fun plot line involving the FBI/CIA and spying emerged. Was quite fun!
May 12, 2023-May 14, 2023
I was a resource head for the Earth and Climate Change Council and a member of the IT team. Won best counci.l
This whole project should be prefaced by the sheer amount of work that had gone into it: from my main work as a resource head for the Earth and Climate Change council: working on the agenda document, the background guide and the video with my co-resource head and directors - as well as helping out with the website as part of the IT team.
With that being said, what an incredible event, so glad to have been (somewhat) randomly selected for ECC - I'd like to think I was a pretty darn good resource head, and won best council with my incredible directors, co-resource head, IT and press members.
Oct 28, 2021-Mar 18, 2023
Trying to finish freeCodeCamp.org's curriculum by the end of 2023.
<span>
element within the Express res
?) and with Responsive Web Design.
/api/check
test cases) and with Responsive Web Design.
POST
comment test case works without the tests, it refuses to pass after all the tests pass. This is probably the second or third most frustrating project I worked on (the most frustrating was probably the JavaScript calculator)
POST
test case to pass, on to the GET
test case. Also continued with beta Responsive Web Design.
DELETE
is done and continued with beta Responsive Web Design.
PUT
and DELETE
functionality to program + the tests! Also continued with beta Responsive Web Design.
GET
request) and continued with beta Responsive Web Design.