Posts

Showing posts from December, 2026

Majority Element in Java(LeetCode 169): Arrays

Image
If you ask someone how to find the most common number in an array, they will almost always say "count everything with a HashMap." That is a fine answer, and it works. But LeetCode 169 (Majority Element) gives you a special guarantee that lets you do much better: the answer appears more than half the time . Because of that one detail, you can solve it with just two variables and a single loop, using no extra memory at all. In this post I'll explain the idea behind it (it's called the Boyer-Moore voting algorithm), trace it by hand on a small array, and then show the Java code I used in my video. There is also a small step-by-step simulator below, so you can type in your own array and watch the candidate and the counter change. Video Walkthrough If you'd rather watch than read, the full explanation is here: 1. What the Problem Asks You get an integer array nums of size n . Return the majority element , which is the value t...

Valid Anagram in Java (LeetCode 242): Arrays

Image
The first instinct most people have for LeetCode 242 (Valid Anagram) is to sort both strings and compare them. That works, but sorting costs you O(n log n) when the problem can actually be solved in a single straight pass through each string. Since both words only use lowercase English letters, a 26-slot counting array does the job in linear time, with no sorting step at all. This post walks through why counting beats sorting here, dry-runs the logic on a couple of examples (including a sneaky one where the lengths differ), and then shares a clean Java implementation. There's also an interactive counter below so you can watch the 26 slots go up and down as each string is scanned. Video Walkthrough Prefer to watch it instead? Here's the full walkthrough, from reading the problem to submitting the solution: 1. What the Problem Asks You're given two strings, s and t . The task is to check whether t is an anagram of s — meaning it uses e...