successful spells and potions. Leetcode problem: https://leetcode.com/problems/successful-pairs-of-spells-and-potions/description/

--------------------

Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7 Output: [4,0,3] Explanation:

  • 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
  • 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
  • 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful. Thus, [4,0,3] is returned.

Intuition

My initial intuition (and I assume for many others out there), when seeing the problem, is to multiply each spell by each potion in the potions array, return the number of successful pairs and continue in this way. Unfortunately, this leads to a time complexity of O(n * m) which will not work for bigger inputs. In order to change the time complexity from O(n*m) to O(n * log(m)) we have to use a binary search to minimize the number of searches through the potions array we have to do.

Approach

We initiate a helper function called spellAndPotions which accepts a single spell, an array of potions and success/target number. It returns a number "successfulPairs" which is a counter for the number of successfulPairs of a single spell * potion in the potion array. The spellAndPotions function uses binary search in order to minimize the number of potions it has to analyze, therefore it expects the potions array to be sorted for the input.

successfulPairs function is initiated and accepts a spells array, potions array, and a success target number. In the function we first sort the potions array as this is what the helper function expects in order to be able to perform a binary search on the potions array. We then return an array by using map on each spell, so for each spell we call the spellAndPotions function on it, and for each spell we return the number of successful pairs for this spell vs all the potions in the potions array.

Binary search: The binary search algorithm in the function spellAndPotions initiates a left at the beginning of the array and right point at the end of the array, successfulPairs at 0 which is the counter. While left endpoint is less than or equal to right endpoint we have elements to search. In each iteration the algorithm calculates the middle point of the search. If this middle potion * spell is equal to or more than the success/target number, we add to the counter the number of elements from the middle element to the end of the array (right-mid are all the elements to the right + 1, the element we just checked). We also move the right counter to mid - 1, since everything to the right of mid is already assumed to be successful. Otherwise, we move the left counter to be mid + 1 because every potion on the left will be a smaller number and therefore will not product a successful match (there is simply no need to check them).

Complexity

  • Time complexity: O(n * log m)

  • Space complexity: O(1)

Code

function spellAndPotions(spell, potions, success) {
  let left = 0;
  let right = potions.length - 1;
  let successfulPairs = 0;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (potions[mid] * spell >= success) {
      successfulPairs += right - mid + 1;
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }

  return successfulPairs;
}

function successfulPairs(spells, potions, success) {
  potions.sort((a, b) => a - b);
  return spells.map((spell) => spellAndPotions(spell, potions, success));
}

reply

Other posts you might like

Leetcode - Capacity To Ship Packages Within D Days - Two Solutions

Here are my two solutions to today's Leetcode problem:

Both solutions use binary search, they are inspired by this solution, with slight performance improvements. Both of them rely on a greedy algorithm and binary search.

Solution 1:

This solution beats 98.92% of solutions in terms of runtime speed but only 21.8% in terms of memory usage.

const isPossible = (weights, days, maxShipSize) => {
  let currentDay = 1;
  let sumOfWeights = 0;

  for (let i = 0; i < weights.length; i++) {
    const weight = weights[i];
    const newSum = sumOfWeights + weight;

    if (newSum > maxShipSize) {
leetcodeprogramming
reply

Leetcode - Add Two Numbers - Two Solutions

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

Full problem here.

Solution 1. Based on this solution

var addTwoNumbers = function(l1, l2) {
    const head = new ListNode(0)

    let firstNode = l1
    let secondNode = l2
    let currentNode = head
    let carry = 0

    while (firstNode || secondNode || carry) {
        const firstValue = firstNode?.val || 0
        const secondValue = secondNode?.val || 0
leetcodeprogrammingjavascriptrecursionlinked listsdata structures
reply

When someone says AI will steal everybody's jobs

const symbols = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
};

const romanToInt = function(s) {
let value = 0;
for (let i = 0; i < s.length - 1; i++) {
console.log("s", s[i])
console.log("s+1", s[i+1])
symbols[s[i]] < symbols[s[i+1]] ? value -= symbols[s[i]]: value += symbols[s[i]];
reply

How to find a wealthy Husband

I had this little joke with my friend that you can spot a wealthy man for yourself by finding guys who play magic the gathering (the cards are super expensive and I wish I could afford the cards to play) or warhammer which is just, also stupidly, stupidly expensive. I would love to buy the little figurines and paint them and play with them but your girl broke as shit.

reply

A Grimm Tale about obedience, by me and chatGPT

Once upon a time in a small, humble village on the edge of a vast forest, there lived a poor miller and his three sons. The miller worked tirelessly to provide for his family, but despite his efforts, they lived a life of scarcity. The three brothers, though strong and capable, were known for their differing personalities: the eldest for his pride and boastfulness, the second for his disobedience, and the youngest for his humility and kindness.

In a distant kingdom, a beautiful and wise princess was captured by a wicked witch with a heart as dark as coal. This malicious sorceress locked the princess away in a tower hidden deep within an enchanted forest, guarded by a fearsome dragon and surrounded by a maze of thorns. The desperate king, who loved his daughter dearly, announced that whoever could rescue his precious child would receive her hand in marriage and half the kingdom's wealth.

Hearing of this great opportunity, the three brothers decided to embark on the adventure, each hoping to change their family's fortune and prove their worth. They prepared for their journey, bidding farewell to their father and the villagers who cheered them on with hope and excitement.

The eldest brother, driven by his pride, ventured into the forest first. He encountered the witch who guarded the path to the princess. She looked deep into his eyes, her voice a raspy whisper, and said, "If you wish to rescue the princess, you must follow m...

reply

How I struggled to fix votes on Sanity

Ever since I implemented upvotes a few months ago, I had been struggling with user upvotes/downvotes request occasionly timing out. The bug persisted for a few months and the few times I tried to debug it, I had no success. Is it the database schema? Nope, I use similar schemas for other collections and they work fine. An inefficient MongoDB query? Same thing. No indexing? I indexed the DB even though there are barely any votes in the collection. An issue with Vercel cold start? Also not it, everything within the norm.

Last Friday the rest of the app was finally ready and I wanted to start inviting some users, so I gave up and decided to pay $20/month for Vercel Pro to increase the timeout from 10 to 60 seconds and worry about the bug another day. And then I checked the logs on Vercel Pro...

Unhandled error: MongooseError: Operation `userVotes.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/var/task/sanity_client/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:175:23)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

Because Mongoose timeout is 10000ms and Vercel's timeout is also 10000ms but this includes the cold start time, this error never popped up on my free plan....

sanityprogrammingvercelmongodbbuilding in public
reply

How I implemented slugs on Sanity - a TypeScript code sample

The lack of human-readable slugs on Sanity had bothered me for a while and I finally got around to fixing them last Sunday. The old, slugless URL structure probably wasn't doing me any favors in terms of SEO and user experience. I'm hoping the new format can give Sanity a much needed SEO boost. Plus, I can finally tell which post is which in Google Search Console and Vercel Analytics.

The Result

Before

https://www.sanity.media/p/64c375049f5d6b05859f10c6

After

https://www.sanity.media/p/64c375049f5d6b05859f10c6-delicious-post-workout-milkshake-recipe

Isn't this much clearer?

The Code

When writing the code I had the following goals in mind:

programmingjavascriptmongoosebuilding in publicmongodb
1 comment

Mandarin Vocabulary for Beginners: 找到, 一半, 朋友

In this article, we will explore three Mandarin words that are useful for everyday conversation: 找到 (zhǎo dào), 一半 (yí bàn), and 朋友 (péng yǒu). Let's break down these words into their individual characters.

找到 (zhǎo dào)

找 (zhǎo) means "to look for" or "to seek". 到 (dào) means "to arrive" or "to reach". Combined, 找到 means "to find" or "have found", which indicates the successful result of a search.

Example Sentences for 找到:

  1. 我找到我的钥匙了。 (Wǒ zhǎodào wǒ de yàoshi le.)
    • I have found my keys.
  2. 他终于找到工作了。 (Tā zhōngyú zhǎodào gōngzuò le.)
    • He finally found a job.
  3. 请帮我找到这本书。 (Qǐng bāng wǒ zhǎodào zhè běn shū.)
    • Please help me find this book.

一半 (yí bàn)

一 (yí) means "one". 半 (bàn) means "half".

mandarinbeginner mandarinhsk 1foreign languageslanguage learninglearn mandarinchinese characters
reply

My last Karaoke Group

The group I went out with last time was a strange mix for sure. There were two types of people. Techbros (our brothers who predictably, work in tech, all part of the 'bald, white, bearded developers' coalition, their words not mine) and the other group, girls who don't speak English (we are all from the local medical university).

How did we get here

The techbros had all lived in the same building as me. I was doing a medical internship at the local medical uni at the time, but seeing as we shared coworking spaces, gym and bar I did eventually somehow manage to make friends there.

As for the girls, we all knew each other from medical Uni, this is in Poland so speaking English at the hospital isn't really a requirement. I ended up inviting my friends to come to Karaoke night with us, as there were some Polish songs we could sing. We ended up singing a mix of Polish and English songs.

All in all, I'd say a pretty successful Karaoke session. Some would consider this a strange group but honestly, I couldn't imagine a better one. The techbros were happy to hang around girls, and the girls wouldn't be there if they understood them.

reply

How I manage to take 10,000 steps a day

Taking 10,000 steps a day is not just a number—it's a commitment to longevity. Regular walking strengthens the heart, aids in weight management, and boosts energy levels, while also reducing the risk of chronic diseases. This daily goal encourages consistency, promoting a healthier and potentially longer life. — ChatGPT

You may already have a fairly good idea about the benefits of taking ten thousand steps a day. This article, then, will be more about the how rather than the why. Let's be honest, ten thousand is a lot of steps and if you're just getting started with a more active lifestyle, the number may seem overwhelming. What follows are some tricks and strategies I use to average more than 10,000 steps a day in most weeks. Before we start, I recommend these two articles if you want to know more about why taking ten thousand steps a day is a good idea:

All right, let's get started.

Monitor your steps

This may seem obvious, but it bears stating: you can't control what you can't measure. The first step to getting to t...

fitbitfitnesshealthself improvementten thousand steps
1 comment
feedback