Skip to main content

Posts

Showing posts with the label Algorithm

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

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.

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

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

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)

GCD Function

The greatest common divisor (GCD) is a fundamental concept in number theory, and its computation plays a crucial role in various mathematical and computational applications. In this comprehensive article, we will delve into the GCD function, exploring both recursive and non-recursive approaches, with a focus on Euclid’s division as an efficient method for GCD calculation. Recursive Approach: // A function to calculate the greatest common divisor of two positive integers int gcd ( int a, int b) { // If one of the numbers is zero, the other is the GCD if (a == 0 ) return b; if (b == 0 ) return a; // Use Euclid's algorithm to find the GCD recursively // The GCD of a and b is the same as the GCD of b and the remainder of a/b return gcd(b, a % b); } Non-Recursive Approach: // A non-recursive function to find the gcd of two positive integers int gcd ( int a, int b) { // Assume that a and b are positive // If not, convert them to positive by taking their a...