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
        const sumOfValues = firstValue + secondValue + carry
        const remainder = sumOfValues % 10
        carry = (sumOfValues - remainder) / 10

        currentNode.next = new ListNode(remainder)
        currentNode = currentNode.next
        firstNode = firstNode?.next
        secondNode = secondNode?.next

    return head.next

Solution 2. Based on this solution

var addTwoNumbers = function(l1, l2) {

    const getNextNode = (firstNode, secondNode, carry) => {
        const firstValue = firstNode?.val || 0
        const secondValue = secondNode?.val || 0
        const sumOfValues = firstValue + secondValue + carry
        const remainder = sumOfValues % 10
        const newCarry = (sumOfValues - remainder) / 10

        if(firstNode?.next || secondNode?.next || newCarry) {
            const nextNode = getNextNode(firstNode?.next, secondNode?.next, newCarry)
            return new ListNode(remainder, nextNode)

        return new ListNode(remainder)

    return getNextNode(l1, l2, 0)

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) {

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.


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.


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


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]];

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





Isn't this much clearer?

The Code

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

programmingjavascriptmongoosebuilding in publicmongodb
1 comment

How I built a chat app using Streams API, Next.JS, Redis and Vercel

Last week I added a chat feature to Sanity. In this article, I'll guide through how I built it using Streams API, Next.js, Redis and Vercel.

Sanity chat

Before we start, a quick disclaimer: there are much better ways to build a chat application, for example by using WebSockets. Vercel unfortunately doesn't support WebSockets and I didn't want to spin a dedicated server, which is why I used Streams API. Using Streams API the way I use it here is most likely not the best use of resources but it works and is a good enough solution for my small scale use. If you're on the same boat, keep reading.

If the chat takes off, I'll have to move it to a dedicated Socket.io server, a serverless WebSocket on AWS, or something similar to reduce costs.

Storing messages in Redis

I use the KV (Redis) database from Vercel to store the last 100 messages. Here is the code used to send and read messages.

import { MAX_CHAT_MESSAGE_LENGTH } from "@/utils";

const MAX_MESSAGES = 100;

export const addChatMessage = async ({
programmingvercelstreams apibackendnext.jsreactredisjavascript

How I fixed @aws-crypto build error

I've been getting the following error when building my Next.js app:

Failed to compile.

./node_modules/.pnpm/@aws-crypto+sha256-js@5.2.0/node_modules/@aws-crypto/sha256-js/build/module/index.js + 12 modules Cannot get final name for export 'fromUtf8' of ./node_modules/.pnpm/@smithy+util-utf8@2.0.2/node_modules/@smithy/util-utf8/dist-es/index.js

I narrowed the source down to the following piece of code:

import { createServerRunner } from "@aws-amplify/adapter-nextjs";
import { AWS_AMPLIFY_CONFIG } from "./utils";
import { cookies } from "next/headers";
import { getCurrentUser } from "aws-amplify/auth/server";

export const { runWithAmplifyServerContext } = createServerRunner({

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

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

Introduction to Beginner Mandarin: 写 (Xiě), 再见 (Zàijiàn), and 下车 (Xiàchē)

写 (xiě)

The character 写 (xiě) means "to write." It consists of two parts: the top part, called the radical, is called 冖 (miànzhào), which was originally associated with a cover or shelter. The bottom part is the character 与 (yǔ), which means "to give." Combined, they create the concept of writing or describing something, as if giving form to thoughts under the shelter of the mind.

Example Sentences:

  1. 我要写信。(Wǒ yào xiě xìn.)
    • I want to write a letter.
  2. 他在写作业。(Tā zài xiě zuòyè.)
    • He is doing his homework.
  3. 请写下你的名字。(Qǐng xiě xià nǐ de míngzì.)
    • Please write down your name.

再见 (zàijiàn)

再见 (zàijiàn), translating to "goodbye" or "see you again," is made up of two characters. 再 (zài) means "again," and 见 (jiàn) means "to see." Essentially, you're expressing a wish to see the person again in the future when you part ways.

mandarinbeginner mandarinhsk 1foreign languageslanguage learninglearn mandarinchinese characters