AI 资讯
LeetCode 78. Subsets
Link https://leetcode.com/problems/subsets/description/ Problem Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example Example 1: Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: Input: nums = [0] Output: [[],[0]] Solution First, create a variable subsets, initialized to [[]], as the return value. Loop through nums, and for each element, create new subsets by appending that element to each existing subset. Then, append these new subsets to subsets. Sample code class Solution : def subsets ( self , nums : List [ int ]) -> List [ List [ int ]]: """ 0: [[]] 1: [[]]+[1] -> [[], [1]] 2: [[],[1]] + [2],[1,2] -> [[], [1], [2], [1, 2]] 3: [[], [1], [2], [1, 2]] + [3], [1, 3], [2, 3], [1,2,3] -> [[], [1], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] """ subsets = [[]] for num in nums : new_subsets = [ subset + [ num ] for subset in subsets ] subsets += new_subsets return subsets
开发者
Two Sum and the use of Dictionary (Easy) | LeetCode Practice #1
Two Sum Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target . (You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.) Python ####Double FOR Loops (Runtime: 2100ms, Memory: 13.3MB) #DECLARE nums: ARRAY of INTEGER #DECLARE target: INTEGER class Solution : def twoSum ( self , nums , target ): Length = len ( nums ) for i in range ( Length - 1 ): for j in range (( i + 1 ), Length ): if nums [ i ] + nums [ j ] == target : return i , j return None ####Hashing Algorithm (Runtime: 0ms, Memory: 12.9MB) #DECLARE nums: ARRAY of INTEGER #DECLARE target: INTEGER class Solution : def twoSum ( self , nums , target ): Seen = {} for i , Value in enumerate ( nums ): if ( target - Value ) in Seen : return Seen [ target - Value ], i Seen [ Value ] = i return None
AI 资讯
Binary Tree PreOrder Traversal
leetcode.com Problem Statement Given the root of a binary tree, return its preorder traversal. Preorder Traversal follows: Root ↓ Left ↓ Right Brute Force Intuition In an interview, you can explain it like this: Visit the current node first, then recursively traverse the left subtree followed by the right subtree. Recursion naturally follows the preorder sequence. Complexity Time Complexity: O(N) Space Complexity: O(H) Where: N = Number of Nodes H = Height of Tree Recursive Code class Solution { public List < Integer > preorderTraversal ( TreeNode root ) { List < Integer > ans = new ArrayList <>(); preorder ( root , ans ); return ans ; } private void preorder ( TreeNode root , List < Integer > ans ) { if ( root == null ) return ; ans . add ( root . val ); preorder ( root . left , ans ); preorder ( root . right , ans ); } } Moving Towards the Optimal Iterative Approach Instead of recursion, we can use a stack. Since preorder visits: Root ↓ Left ↓ Right we should process the root immediately. To ensure the left subtree is processed first, push the right child before the left child . Pattern Recognition Whenever you see: Preorder Traversal Simulate Recursion Think: Stack Key Observation Stack follows: LIFO To visit: Left First push: Right First ↓ Left Second so that left is popped first. Optimal Java Solution class Solution { public List < Integer > preorderTraversal ( TreeNode root ) { List < Integer > ans = new ArrayList <>(); if ( root == null ) return ans ; Stack < TreeNode > st = new Stack <>(); st . push ( root ); while (! st . isEmpty ()) { TreeNode node = st . pop (); ans . add ( node . val ); if ( node . right != null ) st . push ( node . right ); if ( node . left != null ) st . push ( node . left ); } return ans ; } } Dry Run 1 / \ 2 3 / \ 4 5 Stack: 1 Visit: 1 Push: 3 2 Visit: 2 Push: 5 4 Traversal: 1 ↓ 2 ↓ 4 ↓ 5 ↓ 3 Answer: [1,2,4,5,3] Why Stack Works? A stack processes the most recently added node first. By pushing: Right Child ↓ Left Child the left child
AI 资讯
I Built the Tool I Wish I Had When Learning DSA
After failing 3 coding interviews, I realized the problem wasn't practice it was how I was practicing. I spent 6 months grinding LeetCode before my first FAANG interview. 400+ problems solved. Every "Blind 75" problem is memorized. I felt ready. Then the interviewer asked a sliding window variation I hadn't seen before. I froze. Drew a blank. Bombed the interview. The problem wasn't that I hadn't practiced enough. The problem was that I had practiced incorrectly. I memorized solutions instead of understanding patterns. I can recite code, but I struggle to adapt when problems change slightly. So I built something different. Introducing AlgoPatterns A pattern-first DSA learning platform with visualizations that actually show you how algorithms work. algopatterns.in What Makes It Different 1. Pattern-First, Not Problem-First Most platforms throw 2000+ problems at you and say, "Good Luck." AlgoPatterns organizes everything around 17 core patterns: Two Pointers Sliding Window Binary Search BFS/DFS Dynamic Programming Backtracking And 11 more... Master the patterns, and you can solve any variation. 2. Visualizations That Actually Help We have 50+ interactive visualizers that show algorithms step-by-step: Watch two pointers converge in real-time See the DP table fill cell by cell Trace BFS spreading level by level Visualize the call stack during recursion Reading code is one thing. Seeing it executed is completely different. 3. Curated, Not Overwhelming 315 hand-picked problems organized by pattern. Each problem includes: Company tags (Google, Amazon, Meta, etc.) Frequency indicators Pattern classification Difficulty rating No more random grinding. Practice the right problems in the right order. 4. Real Code Templates Every pattern comes with: Java templates (copy-paste ready) "When to use" indicators Common mistakes to avoid Key insights from each pattern Who It's For Interview preppers who want to learn patterns, not memorize solutions CS students who find textbook expla
AI 资讯
I Got Bored of LeetCode, so I Built a Coding RPG
https://dsa-life-simulator-frontend.vercel.app"I made a free tool to make DSA practice feel like an RPG — would like feedback from this community"Been grinding DSA for months and it never felt fun. So I built something. What it does: 🏟️ Real-time 1v1 Arena battles against other devs 🧪 Lab to create and publish your own challenges 🏘️ Community Hub to attempt others' challenges 📖 AI writes your weekly coding journey as a life story 🎮 XP, credits, levels, leaderboards Stack: React + Tailwind + Firebase + Node.js + Socket.IO + Groq AI Still early — would genuinely love feedback from people who've felt the pain of traditional DSA prep.
AI 资讯
Delete Node in a Linked List
Problem Link - https://leetcode.com/problems/delete-node-in-a-linked-list/ This is one of those interview questions that looks impossible at first. Normally, to delete a node from a Linked List, we need access to the previous node. But in this problem, we're only given the node that needs to be deleted. No head. No previous pointer. So how do we remove it? Let's understand the trick. Problem Statement Write a function to delete a node in a singly linked list. You are not given the head of the list. Instead, you are given only the node that needs to be deleted. Example Input: 4 -> 5 -> 1 -> 9 node = 5 Output: 4 -> 1 -> 9 Initial Thought Normally we delete a node like this: prev.next = node.next But here: We don't have prev We don't have head So the usual deletion approach is impossible. Key Observation Although we cannot delete the current node directly, we can make it look like it never existed. Consider: 4 -> 5 -> 1 -> 9 We need to delete: 5 Instead of removing node 5 , copy the value of the next node into it. 4 -> 1 -> 1 -> 9 Now remove the next node. 4 -> 1 -> 9 The original value 5 has disappeared. Mission accomplished. Intuition Copy the next node's value into the current node. Skip the next node. The current node now behaves as if it was deleted. Since the problem guarantees that the given node is not the tail node, a next node will always exist. Dry Run Input 4 -> 5 -> 1 -> 9 node = 5 Current node: 5 Next node: 1 Step 1 Copy next node value. node.val = node.next.val List becomes: 4 -> 1 -> 1 -> 9 Step 2 Skip next node. node.next = node.next.next List becomes: 4 -> 1 -> 9 Done. Optimal Java Solution class Solution { public void deleteNode ( ListNode node ) { ListNode cur = node . next ; node . val = cur . val ; node . next = cur . next ; } } Even Shorter Version class Solution { public void deleteNode ( ListNode node ) { node . val = node . next . val ; node . next = node . next . next ; } } Complexity Analysis Metric Complexity Time Complexity O(1) Space Comp
AI 资讯
Learn Leetcode daily with Claude code mentor
This is a submission for the GitHub Finish-Up-A-Thon Challenge What I Built After being abandoned for several months, I have come back to build and complete Claude with LeetCode, which is a DSA learning system that automates daily algorithm education with Claude code directly inside GitHub repo. Every time I submit an accepted solution on Leetcode, the Github workflow fetches my Leetcode account data and commit the problem with the solution to the repo. Claude will then run on a fixed schedule and automatically generates a full structured lecture, covering the DSA topic, brute force through optimal solutions in Python, complexity analysis, and a YouTube video packaged in a GitHub Issue. This project means a lot to me because it merges two things I care about daily: now not only can I solve Leetcode problem, my solution is automatically analyzed by a powerful AI agent mentor. Demo Link to my project: https://github.com/Stewie-pixel/claude-with-leetcode.git Link to my application walkthrough: https://youtu.be/ClWdW3v9JJ0 The Comeback Story At first this was only a project to store the Leetcode questions I have solved. The process required manual pushing the problem to the repo and nothing special. Later I have added the automation workflow to fetch data from my Leetcode account, Claude will be prompted like an experienced dsa mentor from Claude and skill.md file to give a thorough analysis on that problem. And at the end of the day, Github Copilot workflow will give a daily summary report to cover my daily progress. My Experience with GitHub Copilot I built a DSA Mentor skill that gives Copilot the full context of what a lecture should contain: topic identification, the brute force to optimal approach structure, complexity analysis requirements, and the YouTube search step. Without Copilot, writing the dsaMentor.js orchestration logic and getting the agent to consistently produce structured markdown output would have taken significantly longer. I then use Copilot cli
AI 资讯
Leetcode 150 | Day 2: Remove Element - Naive vs. Optimized
Leetcode 27: Remove Element Leetcode 27 asks us to remove a specific value from an array. The value to be removed is passed in as a parameter to the function along with the array. Just as we did in Day 1, we will cover a naive approach and an optimized approach and discuss the trade-offs between them. I think in the end there's a pretty clear winner. Let's get started. For both approaches we will use the following values: nums = [1, 3, 3, 2, 4] val = 3 Approach 1: Naive (For Loop + Splice) This approach uses a for loop and leverages .splice() for removals. Solution: var removeElement = function ( nums , val ) { let k = 0 ; for ( let i = 0 ; i < nums . length ; i ++ ) { if ( nums [ i ] === val ) { nums . splice ( i , 1 ); i -- ; } else { k ++ ; } } return k ; }; We begin by initializing a variable k to 0. We then enter the for loop. The condition is standard: create a variable i initialized to 0, continue looping while i is less than nums.length to avoid going past the end of the array, and increment by 1 each time through. Each iteration checks one condition: whether nums[i] is equal to val . If true, we call .splice() on the array. The arguments we pass to splice are i and 1 . i is the index at which we want to start removing, and 1 tells splice to remove only that one element. We then decrement i . The reason for this took me some time to wrap my brain around, so I have included a visual below to make it concrete. The core issue is this: when splice removes an element, every element to the right shifts one index to the left. Without i-- , the loop would increment i on the next iteration and skip right over the element that just shifted in. i-- counteracts that by stepping i back, so after the loop increments it, i lands exactly where the shifted element now sits. If nums[i] !== val , we skip the splice and increment k instead. At the end we return k , which holds the count of elements remaining after all occurrences of val have been removed. Time complexity: O(n²)
AI 资讯
Leetcode 150 | Day 1: Merge Sorted Array - Naive vs. Optimized
There's been no shortage of debate lately about whether grinding Leetcode still makes sense in the age of AI. I think it does. AI is a powerful tool, but it was built by humans; which means it inherited our strengths, our blind spots, and our biases. Leaning on it entirely without understanding what's happening under the hood is a risk. A mentor once told me: those who refuse to use AI are not hireable. But neither are those who rely on it entirely. Learning deeply is how you stay on the right side of that line. This is my journey into just that - learning deeply. Day 1 Leetcode 88: Merge Sorted Array This is an interesting problem. You begin with 4 pieces of data — 2 arrays and 2 integers: nums1 : a sorted array whose length equals nums1.length + nums2.length . The first m elements are valid numbers; the remaining indexes hold 0 s as placeholders. nums2 : a sorted array containing only valid numbers, with a length of n . m : the count of valid numbers in nums1. n : the count of valid numbers in nums2. The objective is to merge both arrays into sorted order in place . Since nums1 is already sized to hold every valid element from both arrays, it's where the final sorted result will live. Approach 1: Naive (Splice + Sort) This solution is 2 lines of code. That's it. It's a testament to how much ES6 advanced JavaScript. nums1 . splice ( m , n , ... nums2 ); nums1 . sort (( a , b ) => a - b ); Here's how it works. We start by calling .splice() on nums1. While .splice() has many use cases, here's what each argument is doing in this context: m : the index where we start deleting elements. Since m is the count of valid numbers in nums1, starting at index m puts us right at the first placeholder 0 — exactly where we want to be. n : the number of elements to delete. Since n equals the length of nums2, we're deleting exactly as many placeholders as we have values to insert. ...nums2 : the values we want to insert in place of the deleted elements. The ... is the spread operato
AI 资讯
2487. Remove Nodes From Linked List
In this post i'm gone explain liked list an famous leetcode problem that is " Remove Nodes from linked list ". Problem Statement: You are given the head of a linked list. Remove every node which has a node with a greater value anywhere to the right side of it. Return the head of the modified linked list. Example 1: Input: head = [5,2,13,3,8] Output: [13,8] Explanation: The nodes that should be removed are 5, 2 and 3. Node 13 is to the right of node 5. Node 13 is to the right of node 2. Node 8 is to the right of node 3. Explanation: In this problem statement state that remove the nodes which have the right side (any place) element greater than. let's understand with given example. Node 13 is the right side of the 5,2 nodes thats why 2,5 should be remove. Node 8 is the right side of 3 node thats why 3 should be remove. final result would be [13,8] Solution of the problem: `/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ const reverList = function(head){ let prev = null; let curr = head; let next = null; while(curr!=null){ next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } var removeNodes = function(head) { // reverse list let reversList = reverList(head); let maxNode = reversList; let prevNode = reversList; let currNode = reversList.next; // removed list while(currNode != null){ if(maxNode.val > currNode.val){ currNode = currNode.next; }else{ maxNode = currNode; prevNode.next = currNode; prevNode = prevNode.next; currNode = currNode.next; } } prevNode.next = null; // reverse list return reverList(reversList); };` If you have any query or suggestions leave your expression👨🏿💻🙌.