惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Cloudflare Blog
T
Tenable Blog
V
Vulnerabilities – Threatpost
T
Troy Hunt's Blog
SecWiki News
SecWiki News
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Secure Thoughts
Cyberwarzone
Cyberwarzone
A
Arctic Wolf
H
Heimdal Security Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
The Hacker News
The Hacker News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cisco Talos Blog
Cisco Talos Blog
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
Forbes - Security
Forbes - Security
Security Archives - TechRepublic
Security Archives - TechRepublic
Project Zero
Project Zero
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Azure Blog
Microsoft Azure Blog
T
Tor Project blog
WordPress大学
WordPress大学
AWS News Blog
AWS News Blog
Jina AI
Jina AI
阮一峰的网络日志
阮一峰的网络日志
Cloudbric
Cloudbric
O
OpenAI News
U
Unit 42
Google DeepMind News
Google DeepMind News
Simon Willison's Weblog
Simon Willison's Weblog
Recorded Future
Recorded Future
N
News | PayPal Newsroom
S
Schneier on Security
F
Full Disclosure
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
P
Privacy International News Feed
L
LINUX DO - 最新话题
F
Fortinet All Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
CERT Recently Published Vulnerability Notes
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Recent Announcements
Recent Announcements

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Leetcode 150 | Day 4: Majority Element - Naive vs. Optimized
Angela F. · 2026-06-18 · via DEV Community

Leetcode 169 asks us to identify the majority element in a given array. The majority element is defined as the element that appears more than n / 2 times. We are told that we can assume such an element always exists.

For both approaches we will use the following value:

  • nums = [2, 4, 2, 2, 4, 4, 4]

Approach 1: Naive (Frequency Map)

This approach uses a Map to count the frequency of each element in the array.

function majorityElement(nums) {
  const counts = new Map();

  for (const num of nums) {
    counts.set(num, (counts.get(num) ?? 0) + 1);
  }

  for (const [num, count] of counts) {
    if (count > nums.length / 2) return num;
  }
}

Our first step is to create the Map which will serve as our frequency map.

const counts = new Map();

The next step will require the use of a for loop. We will loop through the input array nums and count the number of occurrences of each value, writing that as a key/value pair to our frequency map, counts. The key will be the element from nums, and the value will be the frequency of times it appears.

for (const num of nums) {
  counts.set(num, (counts.get(num) ?? 0) + 1);
}

This for loop works by looking at each element in nums and calling .set() to store a value. The value that ends up being set depends on what .get() returns. Here's how .get() works:

  • We attempt to get the current count for this number from counts. There are only two possible outcomes - either we have seen this number before, or we haven't:
    • If we have seen it before, .get() returns its current count and we increment by 1.
    • If we haven't seen it before, .get() returns undefined. The ?? operator (nullish coalescing) catches that and defaults it to 0, then we increment by 1 to initialize the count.

The next step involves another for loop. Because this loop is separate from the first rather than nested inside it, we are still O(n) overall - two sequential O(n) loops add up to O(n), not O(n²).

for (const [num, count] of counts) {
  if (count > nums.length / 2) return num;
}

In this for loop we iterate over our frequency map's key/value pairs one by one and compare each frequency to nums.length / 2.

Using our example array:

nums = [2, 4, 2, 2, 4, 4, 4]

counts would look like this:

counts = [[2, 3], [4, 4]]

We compare the value in the first key/value pair, which is 3, to nums.length / 2:

3 > (7 / 2) ->
3 > 3.5
= FALSE

We then perform the same operation on the next key/value pair:

4 > 7 / 2 ->
4 > 3.5
= TRUE

Once we find a value that returns true we know this is our majority element, and we return num.

Time complexity: O(n)

Two sequential loops, each O(n). Two separate O(n) loops add up to O(n), not O(n²).

Space complexity: O(n)

The Map grows proportionally to the number of unique elements in the array.


Approach 2: Optimized (Boyer-Moore Majority Vote Algorithm)

The Boyer-Moore Majority Vote Algorithm, developed by Robert S. Boyer and J Strother Moore in 1981, finds the majority element in a sequence using linear time and constant memory - making it a natural fit for this problem.

function majorityElement(nums) {
  let candidate = null;
  let count = 0;

  for (const num of nums) {
    if (count === 0) candidate = num;
    count += num === candidate ? 1 : -1;
  }

  return candidate;
}

Step 1

We begin by initializing a variable candidate - this is our current best guess for the majority element, and we initialize it to null.

let candidate = null;

We initialize a second variable count. This variable acts as a confidence meter for our current candidate.

let count = 0;

Step 2

We initialize a for loop to iterate through each element of the nums array.

for (const num of nums) {
}

Step 3

The logic that goes inside the for loop:

if (count === 0) candidate = num;
count += num === candidate ? 1 : -1;

If count equals 0, we reassign candidate to the current value of num. This is because a count of 0 means we have zero confidence in our current candidate, so we replace it with the number we're looking at right now.

Then we update our confidence meter. If the current number matches our candidate, count goes up by 1. If it doesn't match, count drops by 1. Every time we see our candidate again we grow more confident. Every time we see something different, that confidence takes a hit.

This took a moment for me to understand. Here is a quick explanation and a table that should help make the concept more concrete.

Using our example array from earlier:

nums = [2, 4, 2, 2, 4, 4, 4]

The easiest way to explain how we always end up with the correct answer is to think of the elements - 2 and 4 - as opposing teams. For every element 2, there is an element 4 to cancel it out. Since 4 is our majority element, there are not enough 2s to cancel out all of the 4s.

2 4
2 4
2 4
MAJORITY ELEMENT 4

Since each pair of elements cancels each other out, and we are guaranteed that a majority element exists, it will always be the value that has no pair that will be our majority element.

Here is a step by step breakdown:

num count === 0? candidate count
2 yes 2 1
4 no 2 0
2 yes 2 1
2 no 2 2
4 no 2 1
4 no 2 0
4 yes 4 1

Return 4. Correct.

Time complexity: O(n)

One pass through the array.

Space complexity: O(1)

Just two variables regardless of input size. No additional data structures needed.


Conclusion

Both approaches work fine, are pretty straightforward, and have a time complexity of O(n). However, the second approach has a space complexity of O(1). The reason for this is that this approach doesn't need a Map to determine the majority element - it can do everything using just two variables. So while Approach 1 will work fine in most cases, Approach 2 will scale significantly better.

...Day 5 coming soon