Skip to main content

Posts

union-find

  Union-Find (or Disjoint Set Union, DSU) is a data structure that tracks elements partitioned into disjoint subsets, supporting rapid merging () and representative finding () operations. Optimized with path compression and union by rank/size, it achieves near-constant amortized time complexity, $O(\alpha(n))$ , making it efficient for Kruskal’s algorithm and dynamic connectivity. [ 1 , 2 , 3 , 4 ] Key Concepts and Operations Find(x): Determines the representative (root) of the set containing element . Union(x, y): Merges the sets containing elements and . MakeSet(x): Initializes a new set containing only element . Structure: Typically implemented as a forest of trees, where each node points to its parent. The root of a tree is its own parent and acts as the representative. [ 4 , 5 , 6 , 7 , 8 ] Optimizations Path Compression: During a operation, makes every node on the path point directly to the root, flattening the tree. Union by Rank/Size: Always attaches the smaller tr...

Balancing brackets

  Balancing brackets  = checking whether every opening bracket has a matching closing bracket in the correct order. Types usually considered: () [] {} Core idea (stack method) Use a  stack : Read characters left → right. If opening bracket → push onto stack. If closing bracket → stack empty → invalid top doesn’t match → invalid else pop. End → stack must be empty. Time:  O(n) Space:  O(n) Example Input: {[()]} Process: { push [ push ( push ) pop ] pop } pop Stack empty → balanced. Python (clean version) def is_balanced(s): stack = [] pairs = {')': '(', ']': '[', '}': '{'} for ch in s: if ch in "([{": stack.append(ch) elif ch in ")]}": if not stack or stack[-1] != pairs[ch]: return False stack.pop() return len(stack) == 0 Edge cases people miss "(]"  → order mismatch "((("  → leftover opens "))...

3+ prompt for Every Developer

optimization check for optimizations.optimization can be reduction of code.It can be like converting code more organised by rearranging thing so code is mainatable and revent peaces of code is at one place itself. you can use oops style too. implement changes without introducing or inventing new bugs Development plan the pieces in the code.keep them together.test every piece with robust test before integrating them together .here pieces can be functions.

use of /r to clear your terminal

Self-Destructing Terminal Messages in Python Published on December 18, 2025 by AI Developer Ever wanted to create a dramatic "self-destructing" message in your terminal, like something straight out of a spy movie? This clever Python trick uses terminal cursor control and timing to make text appear to vanish before your eyes! How It Works The magic happens through ANSI escape sequences and timing control: Cursor positioning: \r returns the cursor to the start of the line Overwriting: 50 spaces completely cover the original message Timing: time.sleep(3) creates the suspenseful pause Flush output: Ensures immediate display without buffering Try This Code Yourself import time import sys print("This message will self-destruct in 3 seconds...", end="", flush=True) time.sleep(3) # \r moves cursor to start # " " * 50 writes 50 spaces to overwrite the t...

PreSigned Url vs Token based

Presigned URLs vs. Token‑based Access Architecting a system where only your platform owns the data. A deep dive into Cloudflare R2 security patterns. 1. Presigned URLs The standard industry approach. The backend generates a specific URL with a cryptographic signature and an expiration time. GET https://bucket.r2.dev/image.png?X-Amz-Signature=a1b2...&Expires=171000 ✅ The Pros Zero Runtime Cost: Traffic goes directly from R2 to the client; no compute needed. Simple Implementation: Standard S3 SDK feature. Hard Expiry: Access is mathematically impossible after the timestamp. ❌ The Cons Weak Caching: Every signature is unique. `image.png?sig=A` != `image.png?sig=B` Leaky: If a user shares the URL, anyone can view it until expiry. No Revocation: You cannot block a speci...

Ai Agents features

Building AI Agents: Complete Guide to Challenges, Processes, Problems & Solutions Core Challenges in AI Agent Development Hallucination: Agents generate confident but false information, worsening in reasoning chains where errors compound across steps [web:1][web:3]. Context Management: Long-term memory fails in multi-turn interactions, causing inconsistent decisions [web:2]. Tool Integration: Reliable API calls and error handling break under edge cases or rate limits. Scalability: Local LLMs like TinyLlama struggle with complex workflows on consumer hardware. Evaluation: Measuring agent success requires custom benchmarks beyond simple accuracy [web:5]. Standard Process to Build AI Agents Define Goals: Specify tasks (e.g., medical diagnosis workflow) and success metrics like 95% task completion. Select Architecture: Choose LLM backbone (GPT-4o-mini, L...

Pyside 6

Exploring PySide 6 PySide 6 is the official set of Python bindings for the Qt 6 framework. It allows developers to build cross-platform desktop applications with modern UIs using Python. With PySide 6, you can access Qt’s powerful widgets, layouts, and graphics capabilities while writing concise, Pythonic code. Some highlights of PySide 6 include: Support for Qt 6’s latest features and modules Cross-platform compatibility (Windows, macOS, Linux) Integration with QML for declarative UI design Strong community and official backing from The Qt Company If the preview doesn’t load, you can open the document directly in Google Drive: Click here to view .

Firebase in rust

// Minimal Firestore integration smoke test. // This test compiles and runs under `cargo test`. It will attempt a small // credentials check when `GOOGLE_APPLICATION_CREDENTIALS` is set, otherwise // it will print a message and return immediately (so CI without credentials // doesn't fail). #[cfg(test)] mod tests { use std::env; // Use the tokio test runtime which is already a dependency in the project. // Minimal Firestore integration tests. // Tests will skip when `GOOGLE_APPLICATION_CREDENTIALS` is not set. #[tokio::test] async fn firestore_smoke_credentials_check() { if let Ok(path) = env::var("GOOGLE_APPLICATION_CREDENTIALS") { // If the credentials env var is set, ensure the file is readable. match tokio::fs::metadata(&path).await { Ok(meta) => { assert!(meta.is_file(), "GOOGLE_APPLICATION_CREDENTIALS is not a file"); } ...

Roman Number to Integer

This website describe common assumption and failure during gfg coding. python Failed class Solution: def romanToDecimal(self, s): # code here val={ '':1, 'X':10, 'L':50, 'M':1000, 'C':100, 'V':5 } sum=0 s=s[::-1] count=0 for i in s: if count==1: count=0 sum-=val[i] else: sum+=val[i] count+=1 return sum Reason Your current implementation of `romanToDecimal()` has the right spirit, but the logic for subtractive notation (like `IV`, `IX`, `XL`, etc.) is off. You're using a `count` flag, which doesn't reliably detect when subtraction should occur. --- ⚠️ Issues: 1. Incorrect subtraction logic : Roman numerals subtract only when a smaller value precedes a larger...

Balancing brackets

we are going to make the logic for isbalanced function correct.This article is part of my efforts where i have made many mistakes while thinking about problem solution which iam just recording over here.Finally i will also have the correct anwser in the same language.As it is self explanatory no Explantion. Test Case 1 Python Failure class Solution: def isequal(self,f,s): ok=[['(',')'], ['[',']'], ['{','}'], ] for i in ok: s=s.replace(i[1],i[0]) if f==s: return True else : return False def isBalanced(self, s): # code here s=s.strip() s.replace(" ","") n=len(s) #should be even if n%2!=0: return False m=n//2 f=s[:m] t=s[m:] t=t[::-1] return self.isequal(f,t) My above program got fa...

Longest unique substring

  Test Case 1 In the brute-force approach to generating substrings using nested loops, maintaining a hashmap that counts each character's occurrence as 1 (e.g., setting counts to 1 regardless of actual frequency) is invalid. Proper substring generation and validation require accurately tracking character counts in the hashmap rather than assuming all characters occur only once. geekforgeeks eekforgeeks ekforgeeks kforgeeks forgeeks orgeeks rgeeks geeks eeks eks ks s Test Case 2 From the following output, what we actually need is a contiguous substring of characters that satisfies our problem constraints. For example, in the second case, the longest substring without repeating characters is 'ksforg' or 'stoare'—these substrings are contiguous and contain no repeating characters. geekforgeeks eekforgeek ekforgee kforge forg or o Test Case 3 We can use a fixed-size sliding window to find substrings. Starting with a window of fixed size, we keep decreasing the w...

Day 1 WEB3

Day 1: Exploring Web3 Today I started exploring Web3. I learned that it's possible to build a trading bot and host it on cloud platforms like Azure and Google Cloud. Since I'm a college student, I also applied for the GitHub Student Developer Pack—and I got it! I heard about trying out EigenLayer. I installed the MetaMask wallet, but I’m not sure how to connect it to EigenLayer or what steps to follow next. Since I’m in India, I looked into platforms like CoinDCX and Binance as potential options. But why did I choose them? That's something I’ll explore more tomorrow. Right now, I don't have any funds in my MetaMask wallet, so I’ll need to sort that out before doing any real transactions. let's look Day 2. Ihave updated the way the Conclusion Today i have took the look the front line correction error . What's Next I will make a azure python script function to run my tradingbot and this will be a important step how much iam delay i d...

Free database for beginners for prototype online

For free online databases suitable for beginners in India, here are some reliable options that support SQL and work well for prototyping: Firebase Realtime Database / Firestore Firebase offers a limited free tier and is easy to set up for quick prototypes. It provides both SQL-like Firestore and NoSQL Realtime Database options. The free plan includes 1GB storage and basic analytics. Firebase Console Supabase Supabase is an open-source alternative to Firebase with a PostgreSQL backend, making it a solid choice for SQL beginners. The free tier provides up to 500MB of database space, unlimited API requests, and real-time capabilities. Supabase PlanetScale Based on MySQL, PlanetScale is great for beginners and offers a free plan with 5GB storage and a user-friendly interface. It’s especially suitable for scalable prototypes and integrates well with modern frameworks. PlanetScale ElephantSQL ElephantSQL offers a free tier for PostgreSQL databases with 20MB storage. It’s easy to use and prov...

Move zeros to End

 Index Problem is we need to move all the zeros to the right and non-zeros to the left. Move Zeros to End Approaches we can follow are: 1st Approch :  1. Your approach of swapping each 0 element with the end ( j pointer) could work, but it requires some adjustments to handle the indices correctly. However, it’s less efficient than moving the non-zero elements to the front as it repeatedly swaps each 0 with elements toward the end, making it potentially  O ( n 2 ) O(n^2) O ( n 2 ) in the worst case due to unnecessary swaps. Here's a refined version of your approach to help clarify the issues and make it function correctly: Adjusted Code Using End-Pointer Swapping Initialize j to nums.size() - 1 (the last index). Traverse from the beginning, and for each 0 , swap it with nums[j] , then decrement j . However, keep in mind that this will cause the relative order of non-zero elements to change. class Solution { public:     void moveZeroes(vector<int>&...

how to use .json file in react

 Reading a .json file in a React application is quite straightforward. Here are the steps to do it: Create a JSON file : First, create a JSON file with some data. For example, let’s name it data.json and place it in the src folder of your React project. { "users" : [ { "id" : 1 , "name" : "John Doe" } , { "id" : 2 , "name" : "Jane Smith" } ] } Import the JSON file : In your React component, import the JSON file. import React from 'react' ; import data from './data.json' ; const App = ( ) => { return ( < div > < h1 > User List </ h1 > < ul > {data.users.map(user => ( < li key = {user.id} > {user.name} </ li > ))} </ ul > </ div > ); }; export default App ; Run your React app : Start your React application using npm start or yarn start , and yo...

How to get started with vim in linux

 Vim These contains all the quick questions for a user just starting with vim and respective links of solutions for those questions or satisfactory anwsers from community. this is a best list of websites that I found online.I arranged in an order.If you like then do like to comment. Questions vim Learning steps - Jorengarenar how to use vim editor – Complete Guide quick Vim Script Tutorial Start Learning vim By Quiz  -By Morzel vim-adventure a Game how to use vim editor – Complete Guide free book to learn vim  -By Steve Losh Book Name  :  Learn Vimscript the Hard Way How to execute file I'm editing in Vi(m) How can I constantly see the current filename in vim? customize your status bar get line number on status line" howto get copy paste  from system clipboard how can i automatically highlight or fix verb tenses IF any suggestions or opinions comment down quickly

find the sum of 3 numbers to find next term

This Blog post Describe How to your may find this algorithm else where too. In this Problem Algorithm: We are given a three digits of sequence after that,we need to find the next element in the array,for Example :- [0,2,4] By suming the previous Three Elements,means [0+2+4]=next_term Hence the next term in the array is 6.Now the array is [0,2,4,6]. Intution: Here are the few conditions return mod value of the following sequence. Every time return the sum of last three numbers. def find_nth_term (n) : mod = 10 ** 9 + 7 if n<= 3 : return sequence[n- 1 ] for i in range( 4 ,n+ 1 ): next_term=sequence[- 1 ]+sequence[- 2 ]+sequence[- 3 ]%mod sequence.append(next_term) return sequence[- 1 ] n=int(input()) #Ouput the nth term modulo (10**9+7) result=find_nth_term(n) print(result)