Arjun Yadav

Table of Contents

Active (7)

Occasional (4)

Inactive (3)

Done (44)

Retroactive (5)

Abandoned (3)

Navigation Tips

  • Press Ctrl/Cmd + ↑ to return back to the table of contents/navigation bar.
  • Use Ctrl/Cmd + F to search for any keyword/date.

Confused? See the note down below.

Active


Advent of Code 2023

Dec 01, 2023-present
Trying to solve all the coding problems for this year's Advent of Code!


Log

  • Third problem done!

  • Second problem done!

  • First problem done!


Offline Streaming Systems

Nov 11, 2023-present
Part of the O.S.S. team.


Log

  • Got organised and got started with debugging.

  • First meeting!

  • Excited to see where this goes!


AI Safety Studying/Research

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!


Student Council - 12th + Head of Events

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)


Log

  • What a month. Summary forthcoming!

  • College fair!

College Fair

  • (another EcoGen flash mob!)

EcoGen - Flash Mob - 2

  • Brown is quite a nice colour.

  • Don't be a donkey.

  • (also, EcoGen flash mob!)

EcoGen - Flash Mob

  • College. TEDx. Entrance.

  • All colours are beautiful.

  • Grading.

  • Everything. In. Between.

  • Everything in between!

  • Oh, it was.

F1

  • 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.

Investiture Ceremony

  • 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.


OptX

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.


Log

  • 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!

OptX Astronomy

  • 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!

OptX Iftar Distribution Event

  • 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.

OptX - Bridges of Giving

  • 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.

OptX - The Symposium 1.0


EA UAE

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.


Log

  • 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!

EA UAE - 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!

EA UAE x EA NYUAD

  • 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!

EA UAE

  • 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)!


LeetCode

Nov 13, 2021-present
Trying to do a problem every day. All of the general problems are done in Python.


Log

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;
  • Finished [Number of Valid Words in a Sentence](https://leetcode.com/problems number-of-valid-words-in-a-sentence/):
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);
  • Finished Top Travellers (with a little bit of help, at least I learnt about LEFT JOIN):
# 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
  • Finished Prime In Diagonal (the square root tricked made it not time out):
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
  • Finished (not really) with Valid Mountain Array:
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)
  • Finished [Count Distinct Numbers on Board]https://leetcode.com/problems/count-distinct-numbers-on-board/):
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)
  • Couldn't solve a problem today, but that's okay.

  • Finished Alternating Digit Sum:

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)])
  • Finished Vowels of All Substrings (not sure if this is my solution or another's, since this code was written before):
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])
  • Could not solve a problem in time today, but that's alright.

  • Finished Longest Nice Substring:

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
  • Finished Base 7 but this does not really count as a valid solution?
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
  • Finished First Unique Character in a String (note: I already completed this problem earlier, but they seemed to have lower the time limit when they made it a daily challenge so I decided to re-do and count it):
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 ""
  • Finished My Calendar I but I had to look at the solution:
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]
  • I tried copying my solution for Find the Middle Index in Array for Find Pivot Index (since it's the same quesiton) but the constraints are 100x larger, so it timed out and I had to look at the solution:
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
  • Sigh (had to look at the solution):
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
  • Trying to solve more medium problems, so here we are:
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("*")
  • Finished Patients With a Condition, but I had to look at the solution (forgot about 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%'

  • I got tunnel visioned in Can Place Flowers, focused so much on list comprehension that I forgot about normal for loops (which was presented in the solution):
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]
  • Finished Tenth Line in Bash, though I basically looked at the solution:
# 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
  • Finished Teemo Attacking, but I had to look at the solution (mine was too slow):
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))
  • Sigh, my binary search solution for First Bad Version timed out so I had to look at the solution:
# 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
  • Reverse Vowels of a String is an interesting problem. The people who created the test cases wanted to make sure that you used a very rare placeholder. I used the non-breaking space (" "):
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 " "
  • MAN I could have solved Perfect Number without looking at the solution if I had remembered to use the 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)
  • Man, I was kind of close with Count and Say, but I had to look at the solution:
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)])
  • Finished Palindrome Linked List (also I'm pretty sure yesterday's solution violated the problem's constraints):
# 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
  • I tried solving a Divide and Conquer problem but I don't think I'm ready. I'll be trying linked lists soon (since they have pretty easy problems).

  • Finished Remove Digit From Number to Maximize Result:

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]]))
  • I belly laughed after the simplest one-liner I could think of actually got through all the test cases for Check if All A's Appears Before All B's:
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)))
  • I overcomplicated my solution for Backspace String Compare which led me to looking at the solution (which is so darn simple!):
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)]
  • Finished Count Integers with Even Digit Sum with a bad for loop. I'll be trying to learn some data structures in the next few months so hopefully this should go:
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))
  • Finished Reverse Bits but I had to look at the solution:
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)]))
  • Finished Goat Latin with a decently fast solution:
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])
  • So this is why it's a nightmare to work with date/time while programming, finished with Day of the Year:
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
  • Finished the worst problem on LeetCode Binary Prefix Divisible By 5 but I had to look at the solution since my answer was a couple of milliseconds too slow:
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))
  • Finished Duplicate Emails, I technically looked at the solution as I didn't know about the existence of "HAVING":
# Write your MySQL query statement below
SELECT email FROM Person GROUP BY email HAVING COUNT(id) >1;
  • Day of the Week took SO LONG but I'm really proud of my solution, with no imports!
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]
  • Finished Baseball Game with a non-one liner (gasp). A really fun problem!
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:]
  • Usually the daily challenges are really tough, but today's Counting Bits was really easy:
class Solution:
    def countBits(self, n: int) -> List[int]:
        return [bin(i)[2:].count('1') for i in range(n + 1)]
  • Finished with Single Number III, same solution as yesterday's problem but it's returning a list:
class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
        return [i for i in nums if nums.count(i) == 1]
  • Finished with Single Number II with my first submission taking 6251 ms lol:
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]]
  • Couldn't solve anything, very frustrating.

  • Took so long to find a problem that I could actually do. Finished with Set Mismatch (but I had to look at the solution):

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))]
  • Finished with Capitalize the Title:
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()
  • Finished with Majority Element II with a sad one-liner (had to escape an absurdly long test case):
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]
  • Finished Find Peak Element with another funny solution (this time, a one-liner):
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)
  • Finished Subsets, though I sort of looked at the solution:
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
  • Tried to find two problems to do, but I only did one: Truncate Sentence:
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])
  • Finished Factorial Trailing Zeroes but I had to look at the solution, tomorrow I will have completed 75 problems!
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
  • After sitting for what feels like hours trying to find a LeetCode problem I could do, I found this, which I thought was silly, just sort the list!

    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)
  • Finished Add Binary (which I've already done, I re-submitted as it was a daily challenge on LeetCode) and Multiply Strings:
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

  • This took so long, but I finally solved Search Insert Position with a crappy solution (but at least it worked):
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
  • So close, finished Sorting the Sentence though I had to make an exception for one test case. I want to transition to medium problems in 2022.
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)
  • Finished my first hard problem, Number of Digit One though I had to look at the solution:
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)
  • Finished Valid Anagram, though I had to look at the solution:
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:]
  • Finished Reverse Prefix of Word, pretty proud of my solution, even though it involves an import:
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
  • Man, I was so close to having my solution accepted, but some long test case tripped me up. Anyways, finished Maximum Number of Words You Can Type but had to look at the solution:
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()
  • Finished Add Digits, though I had to look at the solution (this problem should be medium anyways):
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()
  • Finished my first medium problem, Pow(x, n):
class Solution:
    def myPow(self, x: float, n: int) -> float:
        return x ** n
  • Finished Remove Element, though I had to look at the solution:
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
  • Started with Remove Element. I expect to make many more stupid mistakes in December when it comes to Python.

  • Completed Move Zeros, this took a lot longer than expected:

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)
  • Completed Power of Three, thus ending the power saga (though I had to look at the solution as I didn't know I needed to use 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
  • Completed Power of Four with numpy. (I also got a response on my post from yesterday):
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
  • Completed Power of Two, though I had to use numpy so I don't think my solution really counts, but here's the solution anyways:
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        import numpy as np

        if (np.log2(n)).is_integer():
            return True
        else:
            return False
  • Finished Concatenation of Array, my solution was literally just one line of code (excluding the boilerplate):
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        return nums + nums

      So, I opened up a discussion post about it.


Occasional


Ukulele

Nov 26, 2022-present
Just for some fun. Currently an occasional project.


Ukulele's start date is the date I started logging, not the date when the project started.

Log

  • I think I've gotten "Going to California" by Led Zeppelin fully down now.

Ocean Busters

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.


Log

  • Finished editing for this month!

  • Finished editing for this month!

  • Admin for this month.

  • Done for this month!

  • Always expect the unexpected.

  • Submitted the blog post in record time.

  • Working with my new blog writer for this month!

  • August's theme has been announced!

  • Finished the blog post with my blog writer!

  • Reviewed the second draft. Nearly done (I think)!

  • Reviewed the draft and added comments.

  • Got the draft!

  • Did some organisational work.

  • Had a productive meeting.

  • Meeting soon!

  • Got in touch with my blog writer for this month (who's writing I'll be editing and proof-reading)

  • Got accepted! Interesting to see where this project goes (especially considering my Cold Takes project has been inactive for about half a year).


Drums

Aug 02, 2022-present
Trying to get better every day and have some fun as well! Currently an occasional project.


Drums' start date is the date I started logging, not the date when the project started.

Log

  • Recorded and uploading Clocks by Coldplay.

  • It's up!

  • Recorded a song that a couple of my schoolmates and I are covering!

  • Recorded Zero by The Smashing Pumpkins!

  • Recorded Suck My Kiss by Red Hot Chili Peppers - really loved how this one came out!

  • Do air drums count?

  • Recorded Rope by Foo Fighters! (finally)

  • Recorded Rock and Roll by Led Zeppelin!

  • Played the acoustic drum kit in school!

  • Almost recorded Rope by Foo Fighters.

  • Recorded Heartbreaker by Led Zeppelin.

  • I think I made my teacher proud!

  • Played Summer of 69' by Bryan Adams for tomorrow.

  • I am Iron Man. Also, Heartbreaker! Will finish learning it by Friday.

  • Finished an audition.

  • Messed around with some blink-182 and Van Halen.

  • Finished Grade 3 for the most part (one song is left I believe) and blink-182!

  • Recorded Smells Like Teen Spirit by Nirvana.

  • Recorded Come Together by The Beatles.

  • Continuing to learn Sweet Child O' Mine by Guns N' Roses.

  • Learnt Weird Fishes/ Arpeggi by Radiohead.

  • Los.

  • 'Breed' by Nirvana is quite a fun song to play.

  • Played the intro to Toxicity and shared it.

  • Learnt Boulevard of Broken Dreams and I Believe I'll Dust My Broom

  • "I've given.... UUUUUPPPP!"

  • Back to playing random songs, 'Los' is quite fun to play! Turns out that I broke my snare pad, so swapped with a tom pad. Works.

  • Played 'Chop Suey!' by System of a Down and shared it to the interwebs.

  • So much fun just playing random songs (mostly by a certain NDH band). Going to record a little something tomorrow.

  • Played some Radiohead songs. This is a lot more fun than I remember!

  • Sort of messed around for a bit.

  • Played Fever by The Black Keys.

  • Played I Want to Break Free by Queen.

  • Finished learning Back in Black by AC/DC. The snare-kick-hi-hat pattern was the only thing I had to get down.

  • Played Back in Black by AC/DC.

  • Played Yellow by Coldplay.


Cold Takes Beta Reading

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.


Log

  • Finished my eighth proof-reading. The link to the post will be here once done.

  • Finished my seventh proof-reading (possibly my last for this year - so grateful to have been a part of this). The link to the post will be here once done.

  • Finished my sixth proof-reading (although I unfortunately missed the deadline by a bit). The link to the post will be here once done.

  • Finished my fifth proof-reading. The link to the post will be here once done.

  • Along with other beta-readers, I got appreciated in the latest Cold Takes post!

  • Been a while, but finished my fourth proof-reading. The link to the post will be here once done.

  • Finished my third proof-reading. The link to the blog post will be here once done.

  • Finished my second proof-reading. The link to the blog post will be here once done.

  • Got accepted (!) and finished proof-reading. The link to the blog post will be here when it's done (for privacy reasons).


Inactive


AUS CSE Research Assistant

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.


Log

  • Got the training results up on the AI lab machine!

  • Finally, some good progress.

  • Met my co-RA in-person!

  • Solid plan for the next four to five days, excited!

  • Back to normal training results.

  • Sent out the report.

  • Met my professor onsite! Really reassured now, going to continue on with a really sweet end-goal in mind!

AUS - Part Two

  • Spoke with my professor and co-RA.

  • Jeez, the results are quite poor. Going to need to get back to Paperspace soon.

  • Experimented with VAEs and GANs - going to move on now to expanding the dataset and re-training.

  • Some lukewarm results again, better than run-through at least!

  • Hm, running into a snafu with my code. Will check what's up tomorrow.

  • Heard back from my co-RA!

  • Man, my data processing work sort of meant nothing today. Oh well, we move.

  • You can only increase the batch size so much.

  • Some great results for the first day with the data!

  • Spoke with my co-RA!

  • Took a cursory look at the data.

  • The end of this month lined up perfectly with the end of the first part of this project, excited for the next step!

  • Going to move on to analysing why the model had performed poorly on FashionMNIST, but quite well on CIFAR-10.

  • In the meanwhile, tried my hand at FashionMNIST. Did not go so well.

  • CIFAR-10 training done, going to try out Tiny ImageNet next to end of training before the CameraTrap part of my research (hopefully!)

  • CIFAR-10 training should be done tomorrow morning!

  • Switched to Gradient.

  • CIFAR-10 is showing great results!

  • We back to training.

  • Why is Google so stingy?

  • Day 4b) happened! Got the 240 x 240 data set, and I think the model is better?

  • Pre-lude to Day 4b) tomorrow.

  • Day 4a) I guess.

  • Heard back from my professor.

  • Training, will see its results by tonight (hopefully, else it might time out)

  • Need to train it on the larger dataset tomorrow, had some troubles with it today.

  • I did it! Finally got some results on ImageNette (a smaller version of ImageNet) and while they're not very good, at least I'm somewhere tangible now!

  • So close.

  • Closer.

  • More time needed.

  • Finished my notes on the repository and, in my efforts of trying to get the results on CIFAR-10, ran into a bug that I could not squash in time. Will continue tomorrow.

  • Thoroughly went through a repository - really interesting stuff! Only one roadblock is the difference between two models, but I'm sure I'll figure that out tomorrow.

  • Read two academic papers.

  • Read three academic papers.

  • First day! Learnt a lot about transformers.

AUS.jpg


Codewars

Dec 13, 2022-present
Trying to practice different programming languages with Codewars (LeetCode is for harder, more Python-oriented problems). Currently inactive.


Log

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;
  }
}
  • Finished Split Strings in Python (accidentally left the print statement in my final solution - oh well):
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;
    }
  }
}
  • Finished Mumbling in Java:
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;
}
  • Finished a couple of different problems (?) and got to 8 kyu.

Chess

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.


Chess's start date is the date I started logging, not the date when the project started.

Log


Guitar

Oct 29, 2021-present
Trying to learn acoustic guitar via justinguitar.com. Currently inactive/paused.


Guitar's start date is the date I started logging, not the date when the project started.

Log

  • Learnt some open 7th chords.

  • (Tried) to learn Hey You by Pink Floyd.

  • Freestyled to ease back in.

  • Continued with Module 4 practice.

  • "Learnt" the intro to Chop Suey! Drop C tuning is awesome.

  • Practiced a sliding power chord song that was recommended to us (why do almost all of them have iffy names?)

  • Got started with Module 4 practice.

  • Finished learning an easier version of Enter Sandman.

  • "Finished" with the Module 5 videos (sort of just skipped a few) and will get started with the practice tomorrow.

  • Played an electric guitar for the first time!

  • Finished a short video in the module. I guess I've been less motivated to continue with this module since it's so electric guitar focused (though maybe I'm wrong and my skill is to blame here, not the acoustic)

  • Sort of continued with the riff.

  • Learnt the first part of the first part of the Enter Sandman riff.

  • Finished with Palm Muting and Understanding Distortion. This module is irritating if you're using an acoustic. Why do you have to be so cool, electric?.

  • Finished with The Am Pentatonic Scale.

  • Finished with Power Chords (and sort of learnt Smells Like Teen Spirit?)

  • Got started with Power Chords.

  • Six days... Finished with the second iteration of Module 4 practice.

  • Continued with the second iteration of Module 4 practice. I finally understood why my guitar improv is so bad: I keep trying to play odd patterns.

  • Continued with the second iteration of Module 4 practice.

  • Got started with the second iteration of Module 4 practice.

  • Finished with the first iteration of Module 4 practice.

  • Continued with the first iteration of Module 4 practice.

  • Got my guitar repaired!

  • Continued with the first iteration of Module 4 practice, will be done with it tomorrow (welp, a guitar string broke again, so I'll try my best to get back to the practice ASAP).

  • Finished with the Module 4 videos and got started with the first iteration of Module 4 practice. I think I'm going to increase the number of iterations to three.

  • Finished dice songwriting. Really fun lesson! (even though I didn't do too much lol)

  • Finished learning about the songs for this module (excited for the fingerstyle songs for the first iteration).

  • Finished some ear training, felt pretty disheartened after getting the last exercise wrong.

  • Had fun with this lesson.

  • It took roughly a week but I can finally play Happy Birthday on my own!

  • Hopefully I should be able to play it tomorrow...

  • So close to playing Happy Birthday on my own!

  • Continued with learning Happy Birthday, about two-thirds of the way there.

  • Continued with learning Happy Birthday.

  • Got started with learning Happy Birthday and had some fun with learning All Falls Down (I guess I've learnt it? It sounds pretty bad though).

  • Learnt more about fingerstyle playing.

  • Had fun playing How Much A Dollar Cost with these chords (simplified) (only the F#, F and Dm sounded okay lol)

  • Finished with shifting the F chord. The way Justin played the F chord reminded me How Much a Dollar Cost by Kendrick Lamar. I'm going to try to play that tomorrow.

  • Got started with Module 11 with some sus chords, I really like the transition from A sus2 to A sus4.

  • Finished with the second iteration of Module 10 practice!

  • Continued with the second iteration of Module 10 practice. Nearly done!

  • Continued with the second iteration of Module 10 practice.

  • Continued with the second iteration of Module 10 practice, I thought I forgot the C Major scale but nope, my guitar was just slightly out of tune lol.

  • Got started with the second iteration of Module 10 practice.

  • Finished with the first iteration of Module 10 practice! Also, small correction: I don't use the songbook tab on JustinGuitar.com (since it forces the song into three categories, which I don't like) and instead I just like the play-through video (which acts as a songbook).

  • Continued with Module 10 practice and added two songs to my songbook!

  • Continued with Module 10 practice, F (with bar) chord is shaping up to be pretty decent now (similar sounding to a Fmaj7) but the change from F to C is slow for me lol.

  • Continued with Module 10 practice and did some really bad C Major improvisation (why did I choose the thinnest string?)

  • Continued (?) with Module 10 practice.

  • Finished with the Module 10 videos and got started with the first iteration of Module 10 practice (sort of, I need to start over with the C major scale alternate picking).

  • Learnt some common chord progressions.

  • Finished with La Bamba Riff (learnt the double note variation).

  • Finished with Beginner Hammer-ons which are super tricky and learnt the single note variation of the La Bamba riff, which is super awesome.

  • Finished with The Rhythm Push and also discovered that the 11th fret of the thinnest string sounds almost exactly like the "siren" sample in Use This Gospel.

  • Finished with Alternate Picking C Major and Major Scale Improvisation (really excited to start guitar improv in this module's practice!)

  • Finished with F chord changes and feeling the frets.

  • Learnt about the weak finger G (which I dislike, for now...) and the A mini barre (which I kinda dig)

  • Finished the second iteration of Module 9 practice! Will start Module 10 tomorrow.

  • Continued with the second iteration of Module 9 practice.

  • Continued with the second iteration of Module 9 practice.

  • Got started with the second iteration of Module 9 practice.

  • Finished the first iteration of Module 9 practice, will start the second iteration tomorrow.

  • I did it! I learnt the C Major Scale! I leveraged the previous pattern I learnt for the note circle.

  • Continued with the first iteration of Module 9 practice and played One by U2.

  • Continued with the first iteration of Module 9 practice. Something barely impressive: I can play the C-G-D-A-Em chord transition without looking at the guitar (kind of).

  • Continued with the first iteration of Module 9 practice, the guitar chords Notion page is extremely handy!

  • Revised the Em Pentatonic Scale.

  • Continued with the first iteration of Module 9 practice.

  • Got started with the first iteration of Module 9 practice.

  • Finished with the Module 9 lessons, will be on the practice for some time (due to the C Major scale lol)

  • Finished with the Red Hot Chili Peppers riff (minus the chords, might do that for fun).

  • Got my guitar strings replaced, I've never heard a guitar so out of tune before lol.

  • It wouldn't be a JustinGuitar module without an odd finger training exercise. I was planning on finishing up the Red Hot Chili Peppers riff today (since it's pretty easy) but my D string broke :(

  • Finished with more advanced 16th note strumming.

  • Got done with compiling all the chords in a Notion page.

  • Changed my mind, the C Major scale got to me lol. I'll start the chord book work tomorrow.

  • Finished with All Stop Mute and creating a chord book (which I will do from tomorrow instead of the videos.)

  • Finished with learning the F chord and its variations. It honestly isn't impossible but it certainly is tricky. Maybe I'm just lucky.

  • Finished with the second iteration of Module 8 practice! Will start Module 9 and the dreaded F chord soon.

  • Continued with the second iteration of Module 8 practice, nearly done.

  • Continued with the second iteration of Module 8 practice.

  • Started with the second iteration of Module 8 practice, why does my E min7 chord sound so bad?

  • Finished with the first iteration of Module 8 practice! I'll start it all over again tomorrow.

  • Continued with Module 8 practice.

  • I think I'm done learning the riff! I'll check back tomorrow to see if I still remember it.

  • Continued with the Wish You Were Here riff.

  • I've been listening to Wish You Were Here by Pink Floyd in preparation for finishing the riff. I guess it helped a bit? Anyways, almost finished learning the riff and just a few more items are left for the first iteration of Module 1 practice!

  • Continued with Module 8 practice.

  • Continued with Module 8 practice. I stink at Big G to D chord transitions.

  • Memorized all the Stuck 3&4 chords!

  • 3 days... Anyways, I've finished with all the content and I'll start with the practice tomorrow (for real this time!), it'll probably last ~2 weeks since I'll repeat it.

  • Finished with the Wish You Were Here riff video, sort of got the introduction down. Will start the practice soon!

  • Finished with Notes in Open Position and got started with the Wish You Were Here riff, the riff is super hard!

  • Finished with Pick Manipulation.

  • Finished with All Down 8th Note Strumming, really had a lot fun today in this lesson! Strumming can sometimes be fun.

  • Finished with Muting Strings Deliberately.

  • I have no excuses for not playing guitar for 4 days. Anyways, learnt about a new exercise routine and the Open Em Pentatonic scale.

  • Learnt a ton of chord variations. Going to be slightly hard to remember and practice all of them :(

  • Finished Module 7 practice. Going to start Grade 2 (in guitar!) on the weekend.

  • It's been a while and I finished memorizing two more songs (mainly Mad World) and I only have two more before I finish all my pre-requisites! The memorizing and practising also continued my Module 7 practice.

  • Continued with Module 7's practice.

  • Finished all the content of the last module for Grade 1 and got started with the practice, this (and the last pre-requisite) should be done in about 2 weeks time.

  • Finished all the pre-requisites for Grade 2 except for memorizing the songs, still have 4-ish left.

  • We did it! We'll soon be in Grade 2 after I complete the pre-requisites and the practice for this module.

  • Learnt about the extra modules that JustinGuitar provides (outside of the grades).

  • Learnt more about Dynamics.

  • Learnt about open strings between chord changes and feel good strumming.

  • Learnt about the best chord changes to practice and air changes.

  • Started the last module with a revision on the 8 basic chords.

  • Finished with the second iteration of practice (!) and practised Mad World. Will start the last module of Grade 1 tomorrow.

  • Continued with the second iteration of practice and Hey Joe. Nearly done.

  • Continued with the second iteration of practice and Hey Joe.

  • Started the second iteration of practice and added Hey Joe and Mad World to my songbook!

  • Finished Module 6 practice and played quite alright for this module's song, Hey Joe.

  • Continued with Module 6 practice, I only have the song practice left!

  • Continued with Module 6 practice.

  • Started with Module 6 practice. After this and the second iteration, I will have moved on to the last module of Grade 1!

  • Finished Module 6! Will start the practice soon.

  • Learnt a strumming pattern in 6:8 timing and string names.

  • Learnt about 6:8 timing.

  • Learnt about alternate picking and a variation of the G chord.

  • Finished the second iteration of practice and added Black to my songbook!

  • Only song practice is left for the second iteration of practice! Also, I am very bad at transitioning from C chord to E chord.

  • Continued the second iteration of practice.

  • Sorry, I forgot what tomorrow meant, anyways, I started with the second iteration with the odd finger stretching exercise and the riff practice, will continue with the iteration tomorrow...

  • Completed the first iteration! Will start the Module 5 practice once again tomorrow.

  • Continued with Module 5 practice. Only song practice is left for iteration 1.

  • Continued with Module 5 practice.

  • Started with Module 5 practice.

  • Finished Module 5, will take the next week solely for practice. Also going to build a songbook next week.

  • Watched the Songs For Module 5 video and tried my hands at Daft Punk, let's just say that I'll be practising Daft Punk for a while...

  • Learnt about music theory and notes in guitar.

  • Learnt more about strumming.

  • Learnt the Come As You Are riff.

  • Finished with Justin's strumming tips.

  • Got a little more than half-way through with Justin's strumming tips.

  • Learnt the C Chord.

  • Finished the second iteration of Module 4 practice and played 505 and Chocolate Jesus! I'll start Module 5 tomorrow.

  • Continued with Module 4 practice, nearly done!

  • Started with the second iteration of Module 4 practice.

  • Finished the first iteration of Module 4 practice, had fun playing 505 and Chocolate Jesus.

  • Continued with Module 4 Practice, I'll probably finish with this practice after I do the whole thing twice.

  • Website is back up and continued with Module 4 practice.

  • Continued with 505 as the website is still broken.

  • Sort of freestyled a bit since the website seems to be broken.

  • Continued with 505, the strumming pattern is hard to master!

  • Continued with 505.

  • Started learning 505 by Arctic Monkeys as part of my guitar practice, really nice song.

  • Learnt the riff to Sunshine Of Your Love by Cream, hoping to learn much more in December.

  • Learnt about the most common strumming patter in guitar.

  • Learnt about the metronome in guitar.

  • Learnt the D Minor chord, really cool chord! Sounds much moodier than the other minor chords I've learnt.

  • Continued with JustinGuitar and learnt about this odd finger stretching exercise.

  • Went back to Three Little Birds.

  • Freestyled for a bit.

  • Easing back into guitar.

  • Finishing the whole practice was way too ambitious. I could only get done with the Seven Nation Army riff practice.

  • Finished with Three Little Birds, hope to finish Module 3 practice tomorrow.

  • Continued with Three Little Birds, the A to E to D transition is really hard.

  • Continued with Three Little Birds.

  • Practiced Three Little Birds by Bob Marley. Beautiful song!

  • Been some time, and learnt the Seven Nation Army riff.

  • Learnt about strumming with up strums, and using it after the 2nd beat.

  • Learnt about up strums.


Done


NMSMUN 2023

Oct 21, 2023-Oct 22, 2023
Was the delegate of France for the Special Committee on Peacekeeping Operations, won best delegate and best delegation!


Summary

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!

NMSMUN


Project: Unboxed

Oct 13, 2023-Oct 14, 2023
Student moderator for the metaverse committee!


Summary

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!

Project - Unboxed


TEDxYouth@DPSS 2023

Jul 08, 2023-Sep 30, 2023
Formerly the co-event organiser for my school's second edition TEDxYouth!


Log

  • Success!

TEDxYouth

  • Last week.

  • Salute to all PAs. Heroes don't often wear capes.

  • Stellar progress!

  • Social media! Everything is mostly coming together.

  • We're close in some regards, really close.

  • Two really, really productive days!

  • Outreach meeting.

  • Check-ins.

  • Filming day complete! Hugely successful and really fun!

TEDx - Filming

  • Meeting!

  • Major progress and got up to speed.

  • A lot happened today: started out a bit disheartening but ended on a positive note!

  • Finished a new draft of the script.

  • Outreach, a small crisis in media and finalising the trailer.

  • Press!

  • Outreach.

  • Photography!

  • Recording, recording.

  • Recording, recording.

  • Lots of press (and some media) work!

  • Gotta test out a camera soon.

  • Got (and shared) some great sponsorship advice.

  • Media's turn!

  • Checked-in with outreach - some good progress

  • Cameras have been sorted!

  • Did some media & outreach check-ins.

  • An interesting day.

  • Completely opposite to yesterday, so much progress!

  • Things have gone, noticably quiet...

  • I have a lot of respect for our editorial board.

  • Files!

  • Messages.

  • A lot of progress on the smaller things, really happy to see!

  • From a rocky start (with me sending out a pretty poorly worded message out) to getting settled in to the role to forming our incredible two teams leaves us at this moment right now: with about two months left for the event, things are going to start picking up a lot of momentum now!


Arjun's AI Escapades Class

Aug 15, 2023-Aug 27, 2023
Hosting a series of machine learning and AI safety classes this summer!


  • Third (and final, for now) class done! Extremely grateful to have been able to teach 25+ seniors something that I'm truly passionate about.

  • Time sheet!

  • Announced the second edition.

  • Second class done! Was also a huge success (one my students coincidentally thought of the first thing I teach in second half of the class lol):

AAE - Second

  • Got the presentation done in the nick of time, and a successful first class!

AAE - First


RTA Hackathon

SOLARIS (Third Edition)

Jul 08, 2023-Aug 24, 2023
One last rodeo this summer! Excited to be teaching our ten incredible students.


  • Certificates, and nudged for one of the projects to be published!

  • One of them is really, really incredible.

  • Last capstone project received!

  • Second and third capstone project received! One more...

  • First capstone project received!

  • All capstone project ideas should be finalised now!

  • Answered a doubt(s).

  • And that's a wrap! Capstone project time.

SOLARIS - 3

  • Did some organisational work.

  • Fourth day done!

  • Did some organisational work.

  • Third day done!

  • Did some organisational work.

  • Second day done!

  • Welp, got postponed to tomorrow.

  • First day done!

  • With all the prep work out of the way, just a couple days left before the first class!


Aug 24, 2023-Aug 25, 2023
Participated in RTA's sustainability ~hackathon!


Summary

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.

RTA Hackathon


Mathematics for Machine Learning

Jul 04, 2022-Aug 22, 2023
Learnt the linear algebra, multivariate calculus and principal component analysis behind machine learning.


Log

  • Finished the penultimate week, and finished the course, thus marking the end of this project!

  • Admin work, will finish this project for good by Tuesday.

  • Better late than never.

  • Continued with Week 3.

  • Continued with Week 3.

  • "Continued" with Week 3.

  • Continued with Week 3.

  • "Continued" with the course.

  • "Continued" with the course.

  • Finally finished week 1 after finishing week 2.

  • Figured out the cov_naive(x) function!

  • Trying to finish week 1.

  • Finished with week 2, for the most part.

  • Finished my programming assignment for week 2!

  • Continued with the course.

  • Continued with the course. My programming assignment for week 2 needs a lot more work (and I haven't even finished my week 1 programming assignment...).

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • Made good progress on the programming assignment for Week 1.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • "Continued" with the course.

  • Continued with the course.

  • Continued with the course.

  • Continued with the course.

  • "Continued" with the course.

  • Continued with the course.

  • "Continued" with the course.

  • "Continued" with the course.

  • "Continued" with the course.

  • "Continued" with the course.

  • Continued with Week 1 and got 100% on the practice quiz!

  • Continued with Week 1.

  • Got started with Week 1 of Principal Component Analysis.

  • Finished with Week 6 and hence finished with the multivariate calculus course! Will (hopefully) start Principal Component Analysis on Jan 2023.

  • Nearly finished with Week 6.

  • Finished with Week 5.

  • Continued with Week 5, nearly done after passing a really hard assignment.

  • Continued with Week 5.

  • "Continued" with "Week 5".

  • "Continued" with "Week 5".

  • "Continued" with "Week 5".

  • Continued with Week 5.

  • "Continued" with "Week 5".

  • Continued with Week 5.

  • Continued with Week 5.

  • Continued with Week 5.

  • Continued with Week 5.

  • Continued with Week 5.

  • Got started with Week 5.

  • Finished with Week 4.

  • Continued with Week 4.

  • Continued with Week 4.

  • Continued with Week 4 and got 95% on my practice quiz on the first attempt!

  • Continued with Week 4.

  • Continued with Week 4.

  • Continued with Week 4.

  • Continued with Week 4.

  • Continued with Week 4.

  • Continued with Week 4.

  • Continued with Week 4.

  • Got started with Week 4.

  • Got started with Week 4.

  • Finished with Week 3! Here's my backpropagation submission: Backpropagation

  • Continued with Week 3.

  • Continued with Week 3.

  • Continued with Week 3.

  • Continued with Week 3.

  • "Continued" with Week 3.

  • Continued with Week 3 and got 100% on the practice quiz!

  • Continued (?) with Week 3.

  • Continued (?) with Week 3.

  • Continued with Week 3.

  • Got started with Week 3.

  • Finished with Week 2 and got 100% on the practice quiz!

  • Continued with Week 2. Nearly done.

  • Continued with Week 2 and got 100% on the practice quiz!

  • Continued with Week 2 and learnt about the Hessian.

  • Continued with Week 2.

  • Continued with Week 2.

  • Continued with Week 2.

  • Continued with Week 2.

  • Continued with Week 2.

  • Continued with Week 2 and got 100% on the practice quiz!

  • Continued with Week 2 and learnt about the Jacobian.

  • Got started with Week 2.

  • Finished with Week 1 and got 100% on the final quiz!

  • Continued with Week 1. Nearly (nearly) done.

  • Continued with Week 1. Nearly done.

  • Continued with Week 1.

  • Continued with Week 1.

  • Continued with Week 1.

  • Finished and earned my certificate for the Linear Algebra course!

  • Got started with the final assessment for linear algebra.

  • Finished the last programming assignment for Week 5 and continued with Week 1 (Calculus), going to finish the linear algebra course tomorrow!

  • Continued with Week 5 and Week 1 (Calculus).

  • Continued with Week 5 and learnt about PageRank. Lots to finish up tomorrow (and review simultaneously) so I can focus on multivariate calculus.

  • Continued with Week 5 and learnt about eigenbasis.

  • Continued with Week 5 after passing the second eigenvector quiz.

  • Continued with Week 5.

  • Continued with Week 5 (LA) and got started with the multivariate calculus (MC) course!

  • Continued with Week 5 and finally learnt what eigenvalues are!

  • Continued with Week 5. I finally know, at least on a surface level, what eigenvectors are. But what about eigenvalues?

  • Got started with Week 5.

  • Finished with Week 4.

  • Nearly finished with Week 4.

  • Continued with Week 4 and learnt about transforming a matrix in another plane (in an easier way). I'm going to miss David Dye, he was a phenomenal lecturer in this course.

  • Continued with Week 4 and got a perfect score on my Gram-Schmidt assignement on first submit.

  • Continued with Week 4 and learnt about the Gram-Schmidt process.

  • Continued with Week 4 and learnt about transposing a matrix and orthonormal matrices.

  • Continued with Week 4.

  • Just passed the hard practice test for this week on first attempt.

  • Got started with Week 4 and learnt about Einstein's summation convention and symmetry with the dot product.

  • Finished with Week 3.

  • Nearly finished with Week 3.

  • Learnt about matrix inverses and Gaussian Elimination.

  • Finished with the matrix transformation quiz.

  • Learnt about matrix transformations.

  • Got started with week 3 with matrices.

  • Finished with week 2!

  • Learnt about changing basis and got another 100%!

  • Finished with week 1 (the reply thing wasn't optional lol), learnt about the dot product with the cosine rule, projects and got 100% on the quiz!

  • Learnt about operations, modulus and dot product.

  • Got started with the course!


YCM Youth Meet-up

Aug 10, 2023
Attended Youth Creative Minds' Youth meet-up!


Summary

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!

Khaleej Times


Machine Learning Safety Course

Jun 24, 2023
~Finished the ML Safety course (Intro to ML Safety) in one day and made a guide/blog post on it.


Summary

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.


SOLARIS (Second Edition)

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.


Log

  • Sent out the certificates. See y'all for the last SOLARIS that I'll be facilitating!

  • Did some organisational work.

  • Did some organisational work.

  • Sent out my three capstone project reviews.

  • Had the last meeting for a while, thus marking the end of this project (for now!)

  • Scheduled the last meeting for a while.

  • Finished reviewing two more capstone projects.

  • Reviewed the first capstone project.

  • Received capstone projects. Closing ceremony will be delayed but for now, will host an online meeting to discuss the projects.

  • In discussion regarding the closing ceremony.

  • In discussion regarding the closing ceremony.

  • Did some more organisational work, held the last (technically fourth) day and sent out the capstone project submission form!

  • Did some organisational work.

  • Did some organisational work.

  • Did some organisational work.

  • Did some organisational work.

  • Did some more organisational work. Here's to this project becoming even more ambitious in 2023!

  • Did some organisational work in the morning, but I couldn't teach today's class due to internet issues. We'll be combining this session and the last day (which I feel is something we should do regardless).

  • An okay third day, but this part of the syllabus really needs to be re-vamped.

  • Second day went better than the first: espicially since we had really good debate responses and rebuttals.

  • First day! Along with my co-facilitator, we gave a good overview about rationality.


GFSMUN 2023

Jun 23, 2023-Jun 25, 2023
Attended GFSMUN 2023 as part of my school team, and won best speaker!


Summary

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)

GFSMUN III


Local Hackathon 2023

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.


Summary

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!

Local Hackathon - 2023


YGSS 2023

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


Summary

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.

ECC


freeCodeCamp

Oct 28, 2021-Mar 18, 2023
Trying to finish freeCodeCamp.org's curriculum by the end of 2023.


freeCodeCamp.org's start date is the date I started logging, not the date when the project started.

Log

  • Happy to call an end to this project - really proud of all the certificates that I've earned and the mini-projects I made for them. As I mentioned in one of my blog posts for 2022, I won't (and have not yet) hesitate to recommend freeCodeCamp to anyone who wishes to learn how to code.

  • Continued with the Data Analysis with Python course.

  • "Continued" with the Medical Data Visualizer project.

  • "Continued" with the Medical Data Visualizer project.

  • "Continued" with the Medical Data Visualizer project.

  • Continued with the Medical Data Visualizer project.

  • Continued with the Medical Data Visualizer project.

  • "Continued" with the Medical Data Visualizer project.

  • Continued with the Medical Data Visualizer project.

  • "Continued" with the Medical Data Visualizer project.

  • "Got started" with the Medical Data Visualizer project.

  • Finished the Demographic Data Analyzer Project (here it is).

  • Continued with the Demographic Data Analyzer project. Figured out the roadblock. I hope to finish the last three remaining certificates by the first half of 2023.

  • Continued with the Demographic Data Analyzer project. Sort of hit a roadblock, but I'll figure it out (hopefully).

  • Continued with the Demographic Data Analyzer project.

  • Got started with the Demographic Data Analyzer project.

  • Finished with the Mean-Variance-Standard Deviation Calculator project (here it is).

  • Continued with Data Analysis with Python.

  • Continued with Data Analysis with Python.

  • Continued with Data Analysis with Python.

  • Continued with Data Analysis with Python.

  • Continued with Data Analysis with Python.

  • Continued with Data Analysis with Python.

  • Got started with Data Analysis with Python.

  • Finished with the Probability Calculator Project project (here it is) and earned my certification for Scientific Computing with Python (yes, I know the budget app project isn't fully finished, but I wanted to move on). Only three more certifications left!

  • Finished with the Polygon Area Calculator Project project (here it is).

  • Been a while. Continued with the Budget App Project and I plan to just finish my Python certification before the end of the year (and early next year, try to finish databases).

  • "Continued" with the Budget App Project.

  • Continued with the Budget App Project.

  • "Continued" with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project. Should finish up this upcoming week.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Continued with the Budget App Project.

  • Got started with the Budget App Project.

  • 1 year since this project started! Finished with the Time Calculator Project, here it is.

  • Continued with the Time Calculator Project. Writing down my logic really helped, really close now (just need to fix the AM/PM and -12 logic for 24-hour format).

  • "Continued" with the Time Calculator Project.

  • Continued with the Time Calculator Project. Need to map out my logic on paper tomorrow to see where I'm going wrong.

  • Continued with the Time Calculator Project. Getting somewhat close.

  • Continued with the Time Calculator Project.

  • Continued with the Time Calculator Project.

  • Continued with the Time Calculator Project.

  • Continued with the Time Calculator Project.

  • Continued with the Time Calculator Project.

  • Continued with the Time Calculator Project.

  • Never mind, I won't finish the project today, but I made some great progress! I think I just need to fix the AM/PM and calculate next days.

  • Continued with the Time Calculator Project. I'll try to finish this project by Oct 17.

  • Got started with the Time Calculator Project.

  • Finished with the Arithmetic Formatter project! Here it is.

  • Continued with the Arithmetic Formatter project. Still can't get the test cases to pass but I think I'm getting close.

  • Continued with the Arithmetic Formatter project. I can't get my solution to pass the test cases (even though the output looks to be correct) for some reason, will keep trying tomorrow.

  • Continued with the Arithmetic Formatter project and fixed the alignment of the numbers! Will finish the project tomorrow.

  • Continued with the Arithmetic Formatter project.

  • Continued with the Arithmetic Formatter project. I'm sort of close to fixing the arrangement.

  • Continued with the Arithmetic Formatter project.

  • Continued with the Arithmetic Formatter project.

  • Continued with the Arithmetic Formatter project.

  • "Continued" with the Arithmetic Formatter project.

  • Continued with the Arithmetic Formatter project.

  • Continued with the Arithmetic Formatter project.

  • Got started with Relational Database.

  • Continued with Responsive Web Design.

  • Continued (?) with the Arithmetic Formatter project and continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Progress! I finally got the problems to print horizontally for the Arithmetic Formatter project. Also continued with Responsive Web Design.

  • "Continued" with the Arithmetic Formatter project and continued with Responsive Web Design.

  • Continued with the Arithmetic Formatter project and continued with Responsive Web Design.

  • Continued with the Arithmetic Formatter project and continued with Responsive Web Design.

  • Continued with the Arithmetic Formatter project and continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with the Arithmetic Formatter project and continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Finished with error handling (?) for the Arithmetic Formatter project and continued with Responsive Web Design.

  • Finished with the Scientific Computing with Python lectures. On to the projects!

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python.

  • Contunued with Scientific Computing with Python. Nearly done with the videos.

  • Contunued with Scientific Computing with Python. Never repeat string data more than once.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python. JSON all the way.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python. RFC is a nice easter egg.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python. I think the website went down?

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Scientific Computing with Python.

  • Continued with Scientific Computing with Python.

  • Continued with Responsive Web Design.

  • Got started with Scientific Computing with Python.

  • Finally, finished with the American/British English Translator project (here it is) and finished with Quality Assurance. Oh, and also continued with Responsive Web Design.

  • Continued with the translator project (two more test cases left, though I'll be honest and say that I sort of skipped the other two test cases) and with Responsive Web Design.

  • Continued with the translator project (four more test cases to go) and with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • "Continued" with the translator project and with Responsive Web Design.

  • Continued with the translator project (though progress has been sort of slow) and with Responsive Web Design.

  • Continued with the translator project (sort of fixed the RegEx and figured out how to make the text green) and with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with the translator project (sort of finished the British to American English part, on to getting the text green lol) and with Responsive Web Design.

  • Continued with the translator project (did some VSCode magic to flip the JS objects for the British to American English part) and with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with the translator project (I need to figure out the highlight functionality, how do I insert a <span> element within the Express res?) and with Responsive Web Design.

  • Continued with the translator project and with Responsive Web Design.

  • Continued with the translator project (the American to British English part is very buggy but it sort of works) and with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with Responsive Web Design.

  • Continued with the translator project (working on the American to British English part) and with Responsive Web Design.

  • Sort of got started with the last project for Quality Assurance, American-British English Translator and continued with Responsive Web Design.

  • Finished with the Sudoku Solver project (here it is) and continued with Responsive Web Design.

  • One more test case left and continued with Responsive Web Design.

  • Three more tests cases left and continued with Responsive Web Design.

  • Four more tests cases left for the Sudoku Solver project! Also continued with Responsive Web Design.

  • Continued with the Sudoku Solver project (about half way done with all the /api/check test cases) and with Responsive Web Design.

  • Continued with the Sudoku Solver project (I've got an annoying glitch for the region placement check) and with Responsive Web Design.

  • Continued with the Sudoku Solver project and with Responsive Web Design.

  • Continued with the Sudoku Solver project and with Responsive Web Design.

  • Continued with the Sudoku Solver project (finished the solve part with this algorithm, which I referred to due to this) and with Responsive Web Design.

  • Continued with the Sudoku Solver project and with Responsive Web Design.

  • Continued with the Sudoku Solver project (finished translating the helper function from (1, 2) for the main backtracking function) and continued with Responsive Web Design.

  • Continued with the Sudoku Solver project (got the regex stuff to work and got started with the solving part) and continued with Responsive Web Design.

  • Continued with the Sudoku Solver project and continued with beta Responsive Web Design.

  • Got started with the Sudoku Solver project and finished with a section for beta Responsive Web Design (which recently graduated to the default Responsive Web Design!)

  • Finished with the Personal Library project by intentionally leaving a test case broken :/ (here it is) Also continued with beta Responsive Web Design.

  • AAAAAAAAAA This is a really complicated situation: I wrote all the functional tests and a) Replit keeps crashing after all the tests pass (unless I do a weird port trick) b) Even though the 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)

  • Got the comment POST test case to pass, on to the GET test case. Also continued with beta Responsive Web Design.

  • The comment array seems to be less broken and continued with beta Responsive Web Design.

  • Got the delete all test case to pass and the comment array is, uh, there? (it's really broken). I also continued with beta responsive web design.

  • Continued with beta Responsive Web Design but didn't make a ton of progress with the Personal Library project (the comment system looks a bit daunting, I don't think I've worked with arrays in MongoDB before)

  • Got started with the Personal Library project and continued with beta Responsive Web Design.

  • Finished the Issue Tracker project (here it is) and continued with beta Responsive Web Design.

  • DELETE is done and continued with beta Responsive Web Design.

  • I now only have the PUT and DELETE functionality to program + the tests! Also continued with beta Responsive Web Design.

  • Got a decent amount of tests cases for the Issue Tracker project (I need to fix a schema glitch for the GET request) and continued with beta Responsive Web Design.

  • Continued with the Issue Tracker project and continued with beta Responsive Web Design.

  • Got started with the Issue Tracker Project and continued with beta Responsive Web Design.

  • I finally got done with the Metric-Imperial Converter Project (here it is) and continued with beta Responsive Web Design.

  • AAAAAAAAAA I finished all the tests but freeCodeCamp keeps failing the 16 units test test, it feels like I've tried everything to fixed it.

  • Finished those last two non-test test cases and continued with beta Responsive Web Design. I don't like how we're (to my knowledge) force to use eval for this project.

  • Excluding the the two test cases for the test (which I'm dreading lol), I only have two more tests! Also continued with beta Responsive Web Design.

  • Continued with the Metric-Imperial Converter project and beta Responsive Web Design.

  • Continued with the Metric-Imperial Converter project and beta Responsive Web Design.

  • Got the "all incoming units..." test to pass and continued with beta Responsive Web Design (which I did for yesterday also, oops).

  • Got the "invalid unit" test to pass, need to get the "invalid number" and "invalid number and unit" tests to pass.

  • Got a decent amount of test cases to pass after adding rounding to 5 decimal places and continued with beta Responsive Web Design.

  • Continued with the Metric-Imperial Converter project and beta Responsive Web Design.

  • Continued with the Metric-Imperial Converter project and beta Responsive Web Design.

  • Continued with the Metric-Imperial Converter project and beta Responsive Web Design.

  • Continued with the Metric-Imperial Converter project (got most of the converter to work) and beta Responsive Web Design (I'm only going to do one challenge from now so I don't run out of them lol).

  • Continued with the Metric-Imperial Converter project and beta Responsive Web Design (also, this is pretty late but the issue I opened on the 4th got resolved).

  • Continued with the Metric-Imperial Converter project and beta Responsive Web Design.

  • Got started with the Metric-Imperial Converter project and continued with beta Responsive Web Design.

  • Finished all the coding challenges for Advanced Node and Express. I didn't like the chat application part, mainly because the test cases were too lenient and you could pass a lot of them with a non-functional project. Anyways, I also continued with beta Responsive Web Design.

  • Continued with Advanced Node and Express and with beta Responsive Web Design (finished a section).

  • Continued with Advanced Node and Express and with beta Responsive Web Design.

  • Continued with Advanced Node and Express and with beta Responsive Web Design. Why did I never discover Passport during the bettermailto project?

  • Continued with Advanced Node and Express and with beta Responsive Web Design.

  • Continued with Advanced Node and Express and with beta Responsive Web Design. Why is CSS grid so complicated?

  • Continued with Advanced Node and Express and with beta Responsive Web Design.

  • Continued with Advanced Node and Express and with beta Responsive Web Design.

  • Continued with Advanced Node and Express and with beta Responsive Web Design.

  • Continued with Advanced Node and Express and with beta Responsive Web Design.

  • Got started with Advanced Node and Express, continued with beta Responsive Web Design and opened an issue on GitHub.

  • Finished Quality Assurance and Testing with Chai and continued with beta Responsive Web Design! I finally understand what all this Chai business does. Going to start with Advanced Node and Express from tomorrow.

  • Just realized that I lost my ~180-day streak (probably because of time zones), though it doesn't really matter. Continued with beta Responsive Web Design and Quality Assurance.

  • Continued with beta Responsive Web Design and Quality Assurance.

  • Continued with beta Responsive Web Design and Quality Assurance.

  • Continued with beta Responsive Web Design and Quality Assurance.

  • Continued with beta Responsive Web Design and got started with Quality Assurance again (as I've forgotten a lot about it and I need that knowledge for my Information Security project)

  • Continued with beta Responsive Web Design.

  • Continued with beta Responsive Web Design.

  • Continued with beta Responsive Web Design.

  • Continued with beta Responsive Web Design.

  • Couldn't get much of anything done for the project, but continued with beta Responsive Web Design.

  • Dang it, I forgot about the tests that I had to write. This project is deceivingly big. Anyways, made a bit of progress on the project and continued with beta Responsive Web Design (also, beta Relational Database looks really cool).

  • Sort of got multiple stocks to work (the query parameter if-else conditions aren't very good though), I think I can technically submit the project now, but it's obviously not complete (need to implement the like and rel_likes features)

  • Fixed an axios glitch where it would take two refreshes to get the stock price. Got started with two stocks and continued with beta Responsive Web Design.

  • Progress on Stock Price Checker has been slow, why is it so hard to make a GET request in node.js?

  • Continued with the Stock Price Checker and Responsive Web Design.

  • Got started with the Stock Price Checker project and finished a project within beta Responsive Web Design!

  • Finally finished with the Python section of Information Security. Definitely my least favourite part of freeCodeCamp so far. Anyways, continued with beta Responsive Web Design and the Information Security projects look fun.

  • Continued with beta Responsive Web Design. Yeah, I know I've been skimping on Information Security. It'll come soon.

  • Continued with beta Responsive Web Design.

  • Continued with beta Responsive Web Design.

  • Continued with beta Responsive Web Design.

  • Finished with the tutorial project and continued with beta Responsive Web Design.

  • Got started with the tutorial project and continued with beta Responsive Web Design.

  • Learnt how to create a TCP client and continued with beta Responsive Web Design.

  • Back to learning, finished with Understanding Sockets and Creating a TCP Server and continued with beta Responsive Web Design.

  • Haha I did it! Earned my fifth certificate (here's the project) and continued with beta Responsive Web Design.

  • This forum post should help with my glitch and continued with beta Responsive Web Design.

  • I think I know why my exercise tracker project's last test case doesn't pass, I can't save multiple exercises! I'll fix that soon and I've continued with beta Responsive Web Design.

  • The last test case was close to ending me so I opened up a forum post about it and continued with beta Responsive Web Design.

  • The last test case is so dang annoying but I think I'm nearly done with it. Continued with beta Responsive Web Design.

  • One more test case left for the project! Also, continued with beta Responsive Web Design.

  • Made decent progress on the project and continued with beta Responsive Web Design.

  • My opinion on Mongoose has changed, it's actually pretty neat. Got a little less than half of the test cases done and continued with beta Responsive Web Design.

  • Got started with the behemoth of a project that is the Exercise Tracker and continued with beta Responsive Web Design.

  • Finished with the URL Shortener Project (here it is) and finished with a section of beta Responsive Web Design.

  • Nearly done with the URL Shortener project and continued with beta Responsive Web Design.

  • Finished with the File Metadata Microservice project (here it is) and continued with beta Responsive Web Design. The last two projects I have might take a bit of time...

  • Finished with the Request Header Parser Microservice project (just had to find the HTTP request headers, here's my project link on replit) and continued with beta Responsive Web Design.

  • Finished with the Timestamp project (here it is) and continued with beta Responsive Web Design.

  • Almost finished with the Timestamp project and my project in beta Responsive Web Design (which I continued with) got reset when the FCC team changed the layout!

  • Got started with the Timestamp Microservice project and finished with a section in beta Responsive Web Design.

  • Finished with MongoDB and Mongoose and finished with the challenge portion of Back End Development and APIs! Back to working on projects.

  • Continued with MongoDB and Mongoose.

  • Started with MongoDB and Mongoose and finished a project in beta Responsive Web Design.

  • Finished Basic Node and Express, I think I finally got it down now.

  • Got started with Basic Node and Express.

  • Back to learning, got started with Back End Development and APIs and finished with Managing Packages with NPM (you can find all the back-end learning on my replit in the appropriate folder).

  • I did it! Earned my data visualization certificate (here's the last project) and continued with beta Responsive Web Design.

  • Well, I figured it out the treemap project thanks to the D3 creator, Mike. Just need to add the legend and the tooltip. Should be done in ~2 days.

  • Got started with the Treemap project and continue with beta Responsive Web Design.

  • Map done! Couldn't get the tooltip test cases to pass for some reason, but here it is. I'll work on the last project tomorrow. Also continued with beta Responsive Web Design.

  • Only 3 more test cases left to pass! Also finished a project in beta Responsive Web Design.

  • LET'S GO I got the map all coloured in (the colour scheme is a little different, but that's fine), going to try to wrap this up in about 2 days.

  • Okay, colouring will be impossible if I don't use FCC's map data. Figuring out how to replace the pre-existing map data with that. Also continued with beta Responsive Web Design.

  • In the process of figuring out how to color in the map. Also continued with beta Responsive Web Design.

  • Figured out the map! Also continued with beta Responsive Web Design and finished a section within it!

  • Still figuring out the whole map thing, though I think I found my answer. Also continued with beta Responsive Web Design.

  • Got started with the map project, wondering if I can use a package to draw the US map instead of converting the data they gave into an SVG (which is too complicated). Also continued with beta Responsive Web Design.

  • Finished with the heatmap project (here's the link to it)! Will start with the penultimate project tomorrow. Also continued with beta Responsive Web Design.

  • So close to submitting my heatmap project, just need another day to make the y-axis show the month name, not the number and to add text below the legend (also, figured out the legend!) and I also continued with beta Responsive Web Design.

  • Got more than half of the test cases to pass, though I still need to figure out how to make a legend. Also continued with beta Responsive Web Design.

  • Made amazing progress! The heatmap is basically complete, just need to add a legend, fix the tooltip and pass the tests. I also continued with the beta Responsive Web Design.

  • Made good progress with the heatmap project, I got the axes set properly, it's just the squares that need work now. Also finished two projects within beta Responsive Web Design!

  • Sort of fixed the data issue with this less obscure website (I say sort of because the free account only has 10000 requests before it goes down, which is decent, but the tests that I run