├── .vscode └── settings.json ├── Contests ├── Amazone │ ├── Median of Two Sorted Arrays.java │ ├── MetaData.java │ ├── Minimum Area of Square.java │ └── Optimal Utilization.java ├── FJP-2 Contest(Stack and Queue) │ ├── Down to Zero II.java │ ├── Equal Stacks.java │ ├── Simple Text Editor.java │ ├── Truck Tour.java │ └── Waiter.java ├── FJP-2 Contest-05 │ ├── CamelCase.java │ ├── FunnyString.cpp │ ├── Game of Thrones - I.cpp │ ├── Gemstones.cpp │ ├── MaximumFrequencyCharacter.java │ ├── Pangrams.java │ └── RemoveConsecutiveDuplicates.java ├── FJP-2 Contest-06 │ ├── DiagonalMoveInMazzePath.java │ ├── HiWithoutHit.java │ ├── NonRepeatablePermutationLaxicographical.java │ └── Recursion_1OddAndEvenNumberPrinting.java ├── FJP2-Content_4 │ ├── Pep_Java_4OneDArray_5IsInverse.java │ ├── Pep_Java_5TwoDArray_5TraceByAddingTwoMatrices.java │ ├── TwoDArray_1WavePrint.java │ ├── TwoDArray_2SpiralPrint.java │ └── zigzag_or_diagonal_traversal_of_matrix.java ├── FJP2-Contest_3 │ ├── Adding2numbers.java │ ├── Pep_Java_2NumberSystemAndFunctions_3Combinatorics.java │ ├── Pep_Java_3DataTypeAndBitManipulation_7TemperatueConversion.java │ └── number_in_any_base_to_any_base.java ├── Hackerrank 1 │ ├── AnyBaseMultiplication.java │ ├── BonusPattern.java │ ├── GreedyTom.java │ ├── HollowRhombusStarPattern.java │ └── NarutoandhisBikes.java ├── Hackerrank 2 │ ├── FindthePeakPoint.java │ ├── MixTheArray.java │ ├── TheReturnOfSpiral.java │ └── ZeroMovement.java ├── Hackerrank_3 │ ├── BreakYourSentence.java │ ├── DistinctOccurrences.java │ ├── FindTheRepeatingNumber.java │ └── RefillYourWater.java ├── Hackerrank_4 │ ├── Check If Two String Arrays are Equivalent.java │ ├── Find Least Index.java │ ├── Good And Bad.java │ ├── Not So Unique Numbers.java │ └── Very Easy Problem!.java ├── Intuit Hiring Challenge │ ├── Allen Town.java │ ├── Aman and garden.java │ ├── ROBBERY.java │ ├── Tokyo Drift.java │ ├── Triangular Farms.java │ └── Water Regions.java ├── JoshTechnology Group All Questions │ ├── 0 1 Knapsack.java │ ├── Add Linked Lists.java │ ├── BST to greater tree.java │ ├── Berth of railway seat number.java │ ├── Best Time to Buy and Sell Stock III.java │ ├── Check If Linked List Is Palindrome.java │ ├── Closest Leaf To Given Node In Binary Tree.java │ ├── Dijkstra's shortest path.java │ ├── Equilibrium indices of a Sequence.java │ ├── Is Height Balanced Binary Tree.java │ ├── Kth ancestor of a node in binary tree.java │ ├── Level Order Traversal.java │ ├── Longest Alternating Subsequence.java │ ├── Maximum sum of non-adjacent elements.java │ ├── Minimum Jumps.java │ ├── Multiply Linked Lists.java │ ├── N Queens.java │ ├── Nuts and Bolt Problem.java │ ├── Remove BST keys outside the given range.java │ ├── Reverse Linked List.java │ ├── Rotate Matrix K times.java │ ├── Segregate Odd-Even.java │ ├── Spiral Matrix.java │ └── Sum root to leaf.java └── fjp-2 Contest-07 │ └── SpecificStringBetweenParanthesis.java ├── Leetcode ├── Easy │ ├── Add Digits.java │ ├── Array │ │ ├── First Unique Character in a String.java │ │ ├── RemoveDuplicatesfromSortedArray.java │ │ └── TwoSum.java │ ├── Check If N and Its Double Exist.java │ ├── Check if Every Row and Column Contains All Numbers.java │ ├── Find the Difference.java │ ├── Formulas │ │ ├── Implement strStr().java │ │ ├── Pow(x, n).java │ │ └── PowerOfThree.java │ ├── LinkedList │ │ ├── Delete the Middle Node of a Linked List.java │ │ ├── Insert in Middle of Linked List .java │ │ ├── Remove Linked List Elements.java │ │ └── Reverse a Linked List in groups of given size.java │ ├── Majority Element.java │ ├── Recursion │ │ ├── FibonacciNumber.java │ │ └── ReverseString.java │ ├── String │ │ ├── PrintfirstcharacterOfEveryWord.java │ │ ├── ReverseIndividualWordsInGivenString.java │ │ ├── ReverseString.java │ │ └── TrimingString.java │ ├── Tower Of Hanoi.java │ └── Valid Palindrome.java └── Mediam │ ├── ContainerWithMostWater.java │ ├── Contiguous Array.java │ ├── K-diff Pairs in an Array.java │ ├── Minimum Number of Swaps to Make the String Balanced.java │ ├── Remove Duplicates from Sorted Array II.java │ ├── Remove Zero Sum Consecutive Nodes from Linked List.java │ ├── Smallest Value of the Rearranged Number.java │ ├── Sort Even and Odd Indices Independently.java │ ├── Subarray Sum Equals K.java │ ├── Swap Nodes in Pairs.java │ └── Validate Stack Sequences.java ├── Level 1 ├── 2D Array │ ├── ExitPointOfAMatrix.java │ ├── MatrixMultiplication.java │ ├── RingRotate.java │ ├── RotateBy90Degree.java │ ├── Saddle_Price.java │ ├── Spiral_Display.java │ ├── TWOdArraysDemo.java │ ├── TheStateOfWakanda_1.java │ └── TheStateOfWakanda_2.java ├── DP │ ├── Climb Stairs With Minimum Moves.java │ ├── Climb Stairs With Variable Jumps.java │ ├── Climb Stairs.java │ ├── Fibonacci-dp.java │ ├── Jump Game II.java │ ├── Jump Game.java │ ├── Min Cost Climbing Stairs.java │ ├── Min Cost In Maze Traversal.java │ ├── Minimum Number of Taps to Open to Water a Garden.java │ └── Minimum steps to minimize n as per given condition.java ├── Getting Started │ ├── Basic Program │ │ ├── BenjaminBulbs.java │ │ ├── GCD_LCM.java │ │ ├── GradingSystem.java │ │ ├── PrimeFactorisation.java │ │ ├── PrintFibonacciNumbers.java │ │ ├── PrintPrimeNumber.java │ │ ├── ReverseOFaNumber.java │ │ ├── prime.java │ │ ├── printZ.java │ │ └── pythagorean_triplet.java │ ├── Functions and array │ │ ├── AnyBaseAddition.java │ │ ├── AnyBaseSubtraction.java │ │ ├── AnyBaseToAnyBase.java │ │ ├── AnyBaseToDecimal.java │ │ ├── Any_Base_Multiplication.java │ │ ├── BarChart.java │ │ ├── DecimalToAnyBase.java │ │ ├── DigitFrequency.java │ │ ├── InverseOfAnArray.java │ │ ├── RotateAnArray.java │ │ ├── SubarrayProblem.java │ │ ├── SubsetsOfArray.java │ │ └── SumOfTwoArrays.java │ └── Patterns │ │ ├── Pattern1.java │ │ ├── Pattern2.java │ │ ├── pattern10.java │ │ ├── pattern3.java │ │ ├── pattern4.java │ │ ├── pattern5.java │ │ ├── pattern6.java │ │ ├── pattern7.java │ │ └── pattern8.java ├── Graph │ ├── All Paths From Source to Target.java │ ├── Breadth First Traversal.java │ ├── Get Connected Components Of A Graph.java │ ├── Graph.java │ ├── Hamiltonian Path And Cycle.java │ ├── Has Path.java │ ├── Is Graph Bipartite.java │ ├── Is Graph Connected.java │ ├── Is Graph Cyclic.java │ ├── Iterative Depth First Traversal.java │ ├── Minimum Wire Required To Connect All Pcs.java │ ├── Multisolver - Smallest, Longest, Ceil, Floor, Kthlargest Path.java │ ├── Number Of Islands.java │ ├── Order Of Compilation.java │ ├── Perfect Friends.java │ ├── Print All Paths.java │ ├── Shortest Path In Weights.java │ ├── Spread Of Infection-Using DFS.java │ └── Spread Of Infection.java ├── HashMap and Heap │ ├── Find Median from Data Stream.java │ ├── HashMap and Heap.java │ ├── Intersection of Two Arrays II.java │ ├── Intersection of Two Arrays.java │ ├── K Closest Points to Origin.java │ ├── K largest elements.java │ ├── Longest Consecutive Sequence.java │ ├── Marks of PCM.java │ ├── Nearly Sorted Algorithm.java │ ├── Reorganize String.java │ ├── Sort Characters By Frequency.java │ └── array-of-doubled-pairs.java ├── Linked Lists │ ├── 707. Design Linked List.java │ ├── Add At Index In Linked List.java │ ├── Add First In Linked List.java │ ├── Add Last In Linked List.java │ ├── Big Integer │ │ ├── Add Two Numbers II.java │ │ ├── Add Two Numbers.java │ │ └── Subtraction in Linked List.java │ ├── Display A Linkedlist.java │ ├── Display Reverse (recursive) - Linked List.java │ ├── Get Value In Linked List.java │ ├── K Reverse In Linked List.java │ ├── Merge k Sorted Lists.java │ ├── Merge two sorted linked lists.java │ ├── Middle of the Linked List.java │ ├── Nth node from end of linked list.java │ ├── Odd Even Linked List.java │ ├── Palindrome Linked List.java │ ├── Remove At Index In Linked List.java │ ├── Remove Duplicates from Sorted List II.java │ ├── Remove Duplicates from Sorted List.java │ ├── Remove First In Linkedlist.java │ ├── Remove Last In Linked List.java │ ├── Reorder List.java │ ├── Reverse A Linked List (data Iterative).java │ ├── Reverse Linked List (pointer - Recursive).java │ ├── Reverse Linked List (pointer Iterative).java │ ├── Segregate even and odd nodes in a Link List.java │ ├── Sort List.java │ └── Unfold Of Linkedlist.java ├── Recursion and Backtracking │ ├── Backtracking │ │ ├── Flood Fill.java │ │ ├── Knights Tour.java │ │ └── N Queens.java │ ├── Introduction to Recursion │ │ ├── Factorial.java │ │ ├── Powerlinear.java │ │ ├── Powerlogarithmic.java │ │ ├── PrintDecreasing.java │ │ ├── PrintIncreasing.java │ │ ├── PrintIncreasingDecreasing.java │ │ └── PrintZigzag.java │ ├── Recursion Array │ │ ├── All Indices Of Array.java │ │ ├── Display Array In Reverse.java │ │ ├── DisplayArray.java │ │ ├── First Index.java │ │ ├── Last Index.java │ │ ├── Max Of An Array.java │ │ └── TowerOfHanoi.java │ ├── Recursion On The WayUp │ │ ├── Print Encodings.java │ │ ├── Print Kpc.java │ │ ├── Print Maze Paths With Jumps.java │ │ ├── Print Maze Paths.java │ │ ├── Print Permutations.java │ │ ├── Print Stair Paths.java │ │ ├── Print Subsequence.java │ │ └── Target Sum Subsets.java │ └── Recursion with ArrayList │ │ ├── Get Kpc.java │ │ ├── Get Maze Path With Jumps.java │ │ ├── Get Maze Paths.java │ │ ├── Get Stair Paths.java │ │ └── Get Subsequence.java ├── Searching & Sorting │ ├── Binary Search.java │ ├── Bubble Sort.java │ ├── Count Sort.java │ ├── Insertion Sort.java │ ├── Merge Sort.java │ ├── Merge Two Sorted Arrays.java │ ├── Partition An Array.java │ ├── Quick Select.java │ ├── Quick Sort.java │ ├── Radix Sort.java │ ├── Selection Sort.java │ ├── Sort 01.java │ ├── Sort 012.java │ └── Target Sum Pair 1.java ├── Stack and Queue │ ├── Balanced Brackets.java │ ├── BasicOperation.java │ ├── Celebrity Problem.java │ ├── Duplicate Brackets.java │ ├── Dynamic Queue.java │ ├── Dynamic Stack.java │ ├── Expression Evalution │ │ ├── Infix Conversions.java │ │ ├── Infix Evaluation.java │ │ └── Postfix Evaluation And Conversions.java │ ├── Implement two stacks in an array.java │ ├── Largest Area Histogram.java │ ├── Linked List To Queue Adapter.java │ ├── Linked List To Stack Adapter.java │ ├── Minimum Stack - Constant Space.java │ ├── Minimum Stack - I.java │ ├── Next Greater Element To The Right.java │ ├── Normal Queue.java │ ├── Normal Stack.java │ ├── Queue To Stack Adapter - Pop Efficient.java │ ├── Queue To Stack Adapter - Push Efficient.java │ ├── Sliding Window Maximum.java │ ├── Stack To Queue Adapter - Add Efficient.java │ ├── Stack To Queue Adapter - Remove Efficient.java │ ├── Stock Span.java │ └── Two Stacks In An Array.java ├── String, StringBuilder and arraylist │ ├── Print_All_Palindromic_Substrings.java │ ├── Print_All_Permutations_Of_A_String_Iteratively.java │ ├── RemovePrimes.java │ ├── StringCompression.java │ ├── StringInterning.java │ └── Toggle_Case.java ├── Templates └── Tree │ ├── Binary Search Tree │ ├── Add Node To Bst.java │ ├── Convert Sorted Array to Binary.java │ ├── Delete Node in a BST.java │ ├── Diameter Of A Binary Tree.java │ ├── Is A Binary Search Tree.java │ ├── Is Balanced Tree.java │ ├── Lca Of Bst.java │ ├── Replace With Sum Of Larger.java │ ├── Size, Sum, Max, Min, Find In Bst.java │ └── Target Sum Pair In Bst.java │ ├── Binary Tree │ ├── Average of Levels in Binary Tree.java │ ├── Binary Tree Inorder Traversal.java │ ├── Binary Tree Level Order Traversal II.java │ ├── Binary Tree Level Order Traversal.java │ ├── Binary Tree Right Side View.java │ ├── Binary Tree Zigzag Level Order Traversal.java │ ├── Boundary Traversal of binary tree.java │ ├── Construct Binary Tree from Preorder and Inorder Traversal.java │ ├── Cousins in Binary Tree.java │ ├── Delete Leaves With a Given Value.java │ ├── Find And Nodetorootpath In Binary Tree.java │ ├── Image Multiplication.java │ ├── Left View of Binary Tree.java │ ├── Lowest Common Ancestor of a Binary Tree.java │ ├── Minimum Depth of Binary Tree.java │ ├── Path To Leaf From Root In Range.java │ ├── Print K Levels Down.java │ ├── Print Nodes K Distance Away.java │ ├── Print Single Child Nodes.java │ ├── Remove Leaves In Binary Tree.java │ ├── Same Tree.java │ ├── Symmetric Tree.java │ ├── Tilt Of Binary Tree.java │ ├── Transform To Left-cloned Tree.java │ ├── Transform To Normal From Left-cloned Tree.java │ ├── Unique Binary Search Trees.java │ └── main.java │ └── Generic Tree │ ├── Are Trees Mirror In Shape.java │ ├── Are Trees Similar In Shape.java │ ├── Ceil And Floor In Generic Tree.java │ ├── Diameter Of Generic Tree.java │ ├── Diameter of Tree.java │ ├── Distance Between Two Nodes In A Generic Tree.java │ ├── Find In Generic Tree.java │ ├── Generic Tree - Traversals (pre-order, Post-order).java │ ├── Height Of A Generic Tree.java │ ├── Is Generic Tree Symmetric.java │ ├── Iterative Preorder And Postorder Of Generic Tree.java │ ├── Kth Largest Element In Tree.java │ ├── Level-order Of Generic Tree.java │ ├── Levelorder Linewise (generic Tree).java │ ├── Linearize A Generic Tree.java │ ├── Lowest Common Ancestor (Generic Tree).java │ ├── Maximum Depth of N-ary Tree.java │ ├── Maximum In A Generic Tree.java │ ├── Mirror A Generic Tree.java │ ├── Multisolver.java │ ├── N-ary Tree Level Order Traversal.java │ ├── Node To Root Path In Generic Tree.java │ ├── Node With Maximum Subtree Sum.java │ ├── Predecessor And Successor Of An Element.java │ ├── Remove Leaves In Generic Tree.java │ ├── Size Of Generic Tree.java │ ├── generic Tree.java │ └── levelOrderLinewiseZZ.java ├── Level 2 ├── Array & String │ ├── Balance Array.java │ ├── Best Meeting Point.java │ ├── Boats to Save People.java │ ├── Car Fleet.java │ ├── Car Pooling.java │ ├── Chaining Technique │ │ ├── Max Chunks To Make Sorted II.java │ │ ├── Max Chunks To Make Sorted.java │ │ ├── Min Jumps With +i -i Moves.java │ │ ├── Partition Array into Disjoint Intervals.java │ │ ├── Partition Labels.java │ │ └── Product of Array Except Self.java │ ├── Chocolate Distribution Problem.java │ ├── Consecutive Numbers Sum.java │ ├── Container With Most Water.java │ ├── Digit multiplier.java │ ├── Extra Space │ │ ├── Contains Duplicate II.java │ │ └── Contains Duplicate.java │ ├── Find Minimum in Rotated Sorted Array.java │ ├── Find Pair Given Difference.java │ ├── Find the Smallest Divisor Given a Threshold.java │ ├── First Missing Positive.java │ ├── First negative integer in every window of size k.java │ ├── Indexing Based Sorting │ │ ├── Find All Duplicates in an Array.java │ │ ├── Find All Numbers Disappeared in an Array.java │ │ ├── Find the Duplicate Number.java │ │ ├── First Missing Positive.java │ │ ├── Maximum repeating number.java │ │ ├── Missing Number.java │ │ └── Set Mismatch.java │ ├── Largest Number At Least Twice of Others.java │ ├── Long Pressed Name.java │ ├── Majority Element General.java │ ├── Majority Element II.java │ ├── Majority Element.java │ ├── Majority Elements │ │ ├── Majority Element II.java │ │ ├── Majority Element.java │ │ └── Set Matrix Zeroes.java │ ├── Max Consecutive Ones III.java │ ├── Max sum in sub-arrays.java │ ├── Maximize Distance to Closest Person.java │ ├── Maximum Product Subarray.java │ ├── Maximum Swap.java │ ├── Minimum Moves to Equal Array Elements II.java │ ├── Minimum Moves to Equal Array Elements.java │ ├── Minimum Platforms.java │ ├── Next Greater Element III.java │ ├── Number of Subarrays with Bounded Maximum.java │ ├── Pairs of Songs With Total Durations Divisible by 60.java │ ├── Push Dominoes.java │ ├── Range_Addition.java │ ├── Reach a Number.java │ ├── Reverse Vowels of a String.java │ ├── Shortest Unsorted Continuous Subarray.java │ ├── Sieve of Eratosthenes │ │ ├── Count Primes.java │ │ └── Sieve of Eratosthenes.java │ ├── Smallest Range Covering Elements from K Lists.java │ ├── Sort Array By Parity.java │ ├── Sort the Matrix Diagonally.java │ ├── Split Array Largest Sum.java │ ├── Squares of a Sorted Array.java │ ├── String Matching Problems │ │ ├── Check if two strings are k-anagrams or not.java │ │ ├── Find All Anagrams in a String.java │ │ ├── Find largest word in dictionary.java │ │ ├── Group Anagrams.java │ │ ├── Is Subsequence.java │ │ └── Valid Anagram.java │ └── Wiggle Sort II.java ├── Binary Search │ ├── Binaery Search On Answer │ │ ├── 1552. Magnetic Force Between Two Balls.java │ │ ├── AGGRCOW - Aggressive cows.java │ │ ├── Allocate minimum number of pages.java │ │ ├── Capacity To Ship Packages Within D Days.java │ │ ├── Cooking Ninjas.java │ │ ├── Koko Eating Bananas.java │ │ ├── MissingelementofAP.java │ │ ├── Split Array Largest Sum.java │ │ └── WoodCutting Made Easy!.java │ ├── Binary Search On Matrix │ │ ├── (Only Row Sorted ) Row with max 1s.java │ │ ├── Count zeros in a sorted matrix.java │ │ ├── Row , Col Sorted and Condition.java │ │ └── Row , Col Sorted.java │ ├── Binary Search in Sorted Array │ │ ├── Median of Two Sorted Arrays.java │ │ ├── Search In Nearly Sorted Array.java │ │ ├── Searching in an array where adjacent differ by at most k.java │ │ ├── Staircase Search.java │ │ └── Unbounded Binary Search.java │ ├── Bitonic Array │ │ ├── 540. Single Element in a Sorted Array.java │ │ ├── Find Peak Element.java │ │ ├── Peak Index in a Mountain Array.java │ │ └── Search in Bitonic Array!.cpp │ ├── Broken Economy.java │ ├── Find First and Last Position of Element in Sorted Array.java │ ├── Find K Closest Elements.java │ ├── Find Minimum in Rotated Sorted Array.java │ ├── Find Nth root of M.java │ ├── Find Transition Point.java │ ├── First Bad Version.java │ ├── Guess Number Higher or Lower.java │ ├── Heaters.java │ ├── Lower And Upper Bound.java │ ├── Lower Bound and Upper Bound │ │ ├── (Lower Bound and Upper Bound)Search Insert Position.java │ │ ├── FIrst&LastOccurence.java │ │ └── FloorAndCeil.java │ ├── Median of 2 Arrays │ │ ├── K-th element of two sorted Arrays.java │ │ └── Median of Two Sorted Arrays.java │ ├── Number of occurrence.java │ ├── Preimage Size of Factorial Zeroes Function.java │ ├── Search Insert Position.java │ ├── Sqrt(x).java │ ├── StepArraySearch.java │ └── Valid Perfect Square.java ├── DP │ ├── 2D DP │ │ ├── DP on Grid │ │ │ ├── Minimum Falling Path Sum II.java │ │ │ ├── Minimum Falling Path Sum.java │ │ │ ├── Minimum Path Sum.java │ │ │ ├── Triangle.java │ │ │ ├── Unique Paths II.java │ │ │ └── Unique Paths.java │ │ └── Ninja’s Training.java │ ├── 3D DP │ │ └── DP on Grid │ │ │ ├── Cherry Pickup II.java │ │ │ └── Cherry Pickup.java │ ├── DP ON STRINGS │ │ ├── Longest Common Subsequence.java │ │ ├── Longest Common Substring.java │ │ ├── Longest Palindromic Subsequence.java │ │ ├── Minimum Insertion Steps to Make a String Palindrome.java │ │ ├── Minimum Number of Deletions and Insertions.java │ │ ├── Print all LCS sequences.java │ │ ├── Shortest Common Supersequence.java │ │ └── String Matching │ │ │ ├── Distinct Subsequences.java │ │ │ ├── Edit Distance.java │ │ │ └── Wildcard Matching.java │ ├── DP On Subsequences & Subsets & target │ │ ├── 0 1 Knapsack │ │ │ └── 0 1 Knapsack.java │ │ ├── Infinite Supplies Pattern │ │ │ ├── Coin Change II.java │ │ │ ├── Coin Change.java │ │ │ └── Unbounded Knapsack.java │ │ ├── Number Of Subsets.java │ │ ├── Partition Equal Subset Sum.java │ │ ├── Partitions With Given Difference.java │ │ ├── Subset Sum Equal To K.java │ │ └── Target Sum.java │ ├── DP on Rectangles │ │ ├── Count Square Submatrices with All Ones.java │ │ └── Maximal Rectangle.java │ ├── DP on Stocks │ │ ├── Best Time to Buy and Sell Stock II.java │ │ ├── Best Time to Buy and Sell Stock III.java │ │ ├── Best Time to Buy and Sell Stock IV.java │ │ ├── Best Time to Buy and Sell Stock with Cooldown.java │ │ ├── Best Time to Buy and Sell Stock with Transaction Fee.java │ │ └── Best Time to Buy and Sell Stock.java │ ├── Fibonacci │ │ ├── Decode Ways.java │ │ ├── Distinct Subsequences II.java │ │ ├── Domino and Tromino Tiling.java │ │ ├── Fibonacci Number.java │ │ ├── Frog Jump.java │ │ ├── N-th Tribonacci Number.java │ │ ├── Tiling with M x 1.java │ │ └── Ways To Tile A Floor.java │ ├── LIS │ │ ├── Building Bridges.java │ │ ├── Highway Billboard Problem.java │ │ ├── Largest Divisible Subset.java │ │ ├── Longest Bitonic subsequence.java │ │ ├── Longest Increasing Subsequence.java │ │ ├── Longest String Chain.java │ │ ├── Maximum Profit in Job Scheduling.java │ │ ├── Minimum number of increasing subsequences.java │ │ ├── Number of Longest Increasing Subsequence.java │ │ ├── Print LIS.java │ │ ├── Russian Doll Envelopes.java │ │ ├── Weighted Job Scheduling.java │ │ ├── min max │ │ │ ├── Paint House - Many Colors.java │ │ │ └── Paint House.java │ │ └── total find │ │ │ ├── Arrange Buildings.java │ │ │ ├── Consecutive 1's not allowed.java │ │ │ ├── Count Number of Ways to Place Houses.java │ │ │ └── Paint Fence.java │ ├── Partition DP │ │ ├── Burst Balloons.java │ │ ├── Matrix Chain Multiplication.java │ │ ├── Minimum Cost to Cut a Stick.java │ │ ├── Palindrome Partitioning II.java │ │ └── Partition Array for Maximum Sum.java │ ├── Pascals-triangle │ │ ├── Pascal's Triangle II.java │ │ ├── Pascal's Triangle.java │ │ ├── Water Overflow.java │ │ └── nCr.java │ └── Pic and NotPic Problem │ │ ├── House Robber II.java │ │ └── House Robber.java ├── Graph │ ├── 0-1 Matrix │ │ ├── 01 Matrix.java │ │ └── Reverse Edges.java │ ├── All Paths From Source to Target.java │ ├── Articulation Point And Bridges │ │ ├── Articulation Point - I.java │ │ ├── Articulation Point - II.java │ │ ├── Bridge edge in a graph.java │ │ └── Critical Connections in a Network.java │ ├── As Far from Land as Possible.java │ ├── Bellmon ford Algorithm │ │ ├── Distance from the Source (Bellman-Ford Algorithm).java │ │ └── Negative weight cycle.java │ ├── Bus Routes.java │ ├── Clone Graph.java │ ├── Coloring A Border.java │ ├── Connected Components │ │ ├── Hamiltonian Path And Cycle.java │ │ ├── Number Of Distinct Island.java │ │ ├── Number of Islands.java │ │ ├── Number of Provinces.java │ │ └── number-of-enclaves.java │ ├── Count Unreachable Pairs of Nodes in an Undirected Graph.java │ ├── Cycle Detection │ │ ├── Detect cycle in a directed graph.java │ │ ├── Detect cycle in an undirected graph.java │ │ └── PrintCycle.java │ ├── DSU │ │ ├── Checking Existence of Edge Length Limited Paths.java │ │ ├── DSU Sinepet.java │ │ ├── Detect cycle in an undirected graph.java │ │ ├── Evaluate Division.java │ │ ├── Graph Connectivity With Threshold.java │ │ ├── Kruskal (MST) Algo │ │ │ ├── Kruskal.java │ │ │ └── Minimum Spanning Tree.java │ │ ├── Lexicographically smallest equivalent string.java │ │ ├── Minimize Malware Spread.java │ │ ├── Number Of Island 2.java │ │ ├── Number of Islands II.java │ │ ├── Redundant Connection II.java │ │ ├── Redundant Connection.java │ │ ├── Regions Cut By Slashes.java │ │ ├── Satisfiability of Equality Equations.java │ │ ├── Sentence Similarity.java │ │ ├── Smallest String With Swaps.java │ │ └── similar-string-groups.java │ ├── Dijkstra's Algorithm │ │ ├── Bus Routes.java │ │ ├── Network Delay Time.java │ │ ├── Path With Minimum Effort.java │ │ └── Path with Maximum Probability.java │ ├── Euler Circuit and Path │ │ ├── CODE │ │ │ ├── (Undirected Graph) Euler circuit and Path.java │ │ │ └── Is Directed graph Eulerian.java │ │ └── Reconstruct Itinerary.java │ ├── Find if Path Exists in Graph.java │ ├── Flood Fill.java │ ├── Floyd's Warshall Algorithm │ │ └── Floyd Warshall.java │ ├── Graph Coloring │ │ ├── M-Coloring Problem.java │ │ └── Two cliques.java │ ├── Is Graph Bipartite.java │ ├── Kahn's Algo │ │ ├── Course Schedule II.java │ │ ├── Course Schedule.java │ │ ├── Parallel Courses.java │ │ └── Topological sort.java │ ├── Kosaraju's Algo │ │ ├── Mother Vertex.java │ │ └── Strongly Connected Components.java │ ├── Minimum Spanning Tree │ │ ├── Min Cost to Connect All Points.java │ │ ├── Minimum Spanning Tree.java │ │ └── Water Supply In A Village.java │ ├── Rotting Oranges.java │ ├── Shortest Path In Unweighted Graph │ │ ├── Rotting Oranges.java │ │ ├── Shortest path in an unweighted graph.java │ │ ├── Snakes and Ladders.java │ │ ├── Spread Of Infection.java │ │ ├── Steps by Knight.java │ │ └── Word Ladder.java │ ├── Swim in Rising Water.java │ ├── Time Needed to Inform All Employees.java │ ├── Topological Sort │ │ └── Alien Dictionary.java │ └── shortest-bridge.java ├── Greedy │ ├── Assign Mice to Holes.java │ ├── BAISED.java │ ├── Candy.java │ ├── Car Fleet.java │ ├── Car Pooling.java │ ├── Chocolate Distribution Problem.java │ ├── DEFKIN.java │ ├── Gas Station.java │ ├── Insert Interval.java │ ├── Interval List Intersections.java │ ├── Job Sequencing Problem.java │ ├── Maximum Length of Pair Chain.java │ ├── Meeting Rooms I.java │ ├── Meeting Rooms II.java │ ├── Merge Intervals.java │ ├── Minimum Number of Arrows to Burst Balloons.java │ ├── N meetings in one room.java │ ├── Non-overlapping Intervals.java │ └── Two City Scheduling.java ├── Linked Lists │ ├── 0's and 1's.java │ ├── 0s, 1s and 2s.java │ ├── Copy List with Random Pointer.java │ ├── Find length of Loop .java │ ├── Intersection of Two Linked Lists.java │ ├── LRU Cache.java │ ├── Linked List Cycle II.java │ ├── Linked List Cycle.java │ ├── Partition List.java │ ├── Quick Sort .java │ └── Quick Sort on Linked List.java ├── Number Theory │ ├── Cutting Rectangles.java │ ├── Find Greatest Common Divisor of Array.java │ ├── GCD of Array.java │ ├── Greatest Common Divisor of Strings.java │ ├── LCM And GCD.java │ ├── Largest Coprime Divisor.java │ ├── Prime │ │ ├── Common Divisors.java │ │ ├── Count Primes.java │ │ ├── Four Divisors.java │ │ ├── Prime Number.java │ │ ├── The kth Factor of n.java │ │ └── Three Divisors.java │ └── Required Rooms.java ├── Recursion&Backtracking │ ├── All Palindromic Permutations.java │ ├── Combinations.java │ ├── M-Coloring Problem.java │ ├── Modular Fast Exponentiation.java │ ├── N-Queens(Space Optimised).java │ ├── N-Queens.java │ ├── Palindrome Partitioning.java │ ├── Permutation Sequence.java │ ├── Permutations - 2.java │ ├── Permutations II.java │ ├── Permutations.java │ ├── Pow(x, n).java │ ├── Rat in a Maze Problem - I(Sort Code).java │ ├── Rat in a Maze Problem - I.java │ ├── Subsets.java │ └── Sudoku Solver.java ├── Sorting │ ├── Count Inversions.java │ ├── DNF_Sort.java │ ├── Find Pivot Index.java │ ├── Google │ │ └── Count Winning Streaks.java │ ├── Merge Sorted Array.java │ ├── Quick_Sort.java │ ├── Reverse Pairs.java │ ├── Search a 2D Matrix II.java │ ├── Search a 2D Matrix.java │ ├── Sort Array by Increasing Frequency.java │ ├── Sort Characters By Frequency.java │ ├── Sort an Array.java │ ├── StringSort.java │ ├── Top K Frequent Elements.java │ └── Top K Frequent Words.java ├── Stack and Queue │ ├── Asteroid Collision.java │ ├── Basic Calculator.java │ ├── Build Binary Expression Tree From Infix Expression.java │ ├── Decode String.java │ ├── Design Circular Deque.java │ ├── Design Circular Queue.java │ ├── Design Front Middle Back Queue.java │ ├── Design a Stack With Increment Operation.java │ ├── Evaluate Expression Tree.java │ ├── Find the Most Competitive Subsequence.java │ ├── Flattening a Linked List.java │ ├── Longest Valid Parentheses.java │ ├── Max Stack.k.java │ ├── Maximum Frequency Stack.java │ ├── Minimum Add to Make Parentheses Valid.java │ ├── Minimum Insertions to Balance a Parentheses String.java │ ├── Minimum Remove to Make Valid Parentheses.java │ ├── N Stacks In An Array.java │ ├── Remove Duplicate Letters.java │ ├── Remove K Digits.java │ ├── Remove Outermost Parentheses.java │ ├── Reverse Stack Using Recursion.java │ ├── Reverse Substrings Between Each Pair of Parentheses.java │ ├── Reversing Queue.java │ ├── Score of Parentheses.java │ ├── Sort a Stack.java │ ├── Sum of Subarray Minimums.java │ ├── Trapping Rain Water(Extra Space & WithOut Extra Space).java │ ├── Valid Parentheses.java │ ├── Valid Parenthesis String.java │ └── Validate Stack Sequences.java ├── Tree │ ├── (Morris )Binary Tree Inorder Traversal.java │ ├── (Morris) Binary Tree Preorder Traversal.java │ ├── AVL │ │ ├── AVL ADD.java │ │ ├── AVL Deleat.java │ │ └── AVL_Contract.java │ ├── Ancestors in Binary Tree.java │ ├── Balanced Binary Tree.java │ ├── Binary Tree Cameras.java │ ├── Binary Tree Coloring Game.java │ ├── Binary Tree Maximum Path Sum.java │ ├── Binary Tree Paths.java │ ├── Binary Tree Tilt.java │ ├── Binary Tree to CDLL.java │ ├── Bottom View of Binary Tree.java │ ├── Boundary Traversal of binary tree.java │ ├── Brothers From Different Roots.java │ ├── Clone a Binary Tree.java │ ├── Construct Binary Search Tree from Preorder Traversal.java │ ├── Construct Binary Tree from Inorder and Postorder Traversal.java │ ├── Construct Binary Tree from Preorder and Postorder Traversal.java │ ├── Construct tree from Inorder and LevelOrder.java │ ├── Convert BST to Greater Tree.java │ ├── Count Complete Tree Nodes.java │ ├── DP on TREE │ │ ├── Binary Tree Cameras.java │ │ ├── Distribute Coins in Binary Tree.java │ │ ├── House Robber III.java │ │ ├── Largest Distance between nodes of a Tree.java │ │ ├── Largest Independent Set Problem.java │ │ └── Longest ZigZag Path in a Binary Tree.java │ ├── Delete Node in a BST.java │ ├── Diagonal Traversal of Binary Tree .java │ ├── Diameter of Binary Tree.java │ ├── Distribute Coins in Binary Tree.java │ ├── Find the Closest Element in BST .java │ ├── Flatten Binary Tree to Linked List.java │ ├── Image Multiplication.java │ ├── Inorder Successor in BST.java │ ├── Largest Distance between nodes of a Tree.java │ ├── Left View of Binary Tree.java │ ├── Linked List in Binary Tree.java │ ├── Longest Even Sum Path.java │ ├── Longest Univalue Path.java │ ├── Lowest Common Ancestor in a Binary Tree.java │ ├── Lowest Common Ancestor of a Binary Search Tree.java │ ├── Maximum Depth of Binary Tree.java │ ├── Maximum Path Sum between 2 Leaf Nodes.java │ ├── Maximum sum leaf to root path.java │ ├── Median of BST.java │ ├── Merge two BST 's.java │ ├── Minimum Depth of Binary Tree.java │ ├── Node Paths.java │ ├── Number of Turns in Binary Tree.java │ ├── Path Sum II.java │ ├── Path Sum III.java │ ├── Path Sum.java │ ├── Populating Next Right Pointers in Each Node II.java │ ├── Populating Next Right Pointers in Each Node.java │ ├── Recover Binary Search Tree.java │ ├── Reverse Level Order Traversal .java │ ├── Segment Tree │ │ └── Range Sum Query - Mutable.java │ ├── Serialize and Deserialize Binary Tree.java │ ├── Step-By-Step Directions From a Binary Tree Node to Another.java │ ├── Subarray Sum Equals K.java │ ├── Sum Root to Leaf Numbers.java │ ├── Sum of Distances in Tree.java │ ├── Top View of Binary Tree.java │ ├── Unique Binary Search Trees II.java │ ├── Vertical Order Traversal of a Binary Tree.java │ ├── k-th smallest element in BST.java │ ├── maximum-width-of-binary-tree.java │ └── recover-a-tree-from-preorder-traversal.java ├── Tries │ ├── Design Add and Search Words Data Structure.java │ ├── Implement Trie (Prefix Tree).java │ ├── Implement Trie llI.java │ ├── Longest Word in Dictionary.java │ ├── Map Sum Pairs.java │ └── Replace Words.java ├── Two Pointer Technique │ ├── 2Sum │ │ ├── Count pairs with given sum.java │ │ ├── Max Number of K-Sum Pairs.java │ │ ├── Pairs With Given Sum In Two Sorted Matrices.java │ │ ├── Two Sum - Closest to target.java │ │ ├── Two Sum - Greater than target.java │ │ ├── Two Sum - Less than or equal to target.java │ │ ├── Two Sum - Unique pairs.java │ │ ├── Two Sum Absolute.java │ │ ├── Two Sum II.java │ │ ├── Two Sum III - Data structure design.java │ │ └── Two Sum.java │ ├── 3Sum │ │ ├── 3Sum Closest.java │ │ ├── 3Sum Smaller.java │ │ ├── 3Sum.java │ │ ├── Array 3 Pointers.java │ │ ├── Count the triplets.java │ │ └── Valid Triangle Number.java │ ├── 4Sum │ │ ├── 4Sum II.java │ │ ├── 4Sum.java │ │ └── Tuple with Same Product.java │ ├── Difference Pair │ │ ├── Count Number of Pairs With Absolute Difference K.java │ │ ├── K-diff Pairs in an Array.java │ │ ├── Maximum Distance Between a Pair of Values.java │ │ ├── Maximum Width Ramp.java │ │ └── Two Sum - Difference equals to target.java │ └── Static Window Sliding │ │ └── Max Sum Subarray of size K.java └── java.txt ├── README.md └── images └── giphy.gif /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": [ 3 | "Level 1/Getting Started/Functions and array", 4 | "Level 1/2D Array", 5 | "Contests/Hackerrank 1", 6 | "Contests/FJP2-Content_4", 7 | "Level 1/String, StringBuilder and arraylist" 8 | ] 9 | } -------------------------------------------------------------------------------- /Contests/FJP-2 Contest(Stack and Queue)/Simple Text Editor.java: -------------------------------------------------------------------------------- 1 | //simple-text-editor 2 | //https://www.hackerrank.com/contests/fjp-stack-and-queue/challenges/simple-text-editor/problem 3 | 4 | -------------------------------------------------------------------------------- /Contests/FJP-2 Contest(Stack and Queue)/Truck Tour.java: -------------------------------------------------------------------------------- 1 | //Truck Tour 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | public static void main(String [] args) { 11 | Scanner in = new Scanner(System.in); 12 | int n = in.nextInt(); 13 | List list = new ArrayList(); 14 | int tank = 0; 15 | int result = -1; 16 | for(int loop=0; loop 0) { 19 | if(result==-1) { 20 | result = loop; 21 | } 22 | list.add(net); 23 | tank += net; 24 | } else { 25 | list.clear(); 26 | tank = 0; 27 | result = -1; 28 | } 29 | } 30 | System.out.println(result); 31 | in.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Contests/FJP-2 Contest(Stack and Queue)/Waiter.java: -------------------------------------------------------------------------------- 1 | //Waiter 2 | //https://www.hackerrank.com/contests/fjp-stack-and-queue/challenges/waiter 3 | -------------------------------------------------------------------------------- /Contests/FJP-2 Contest-05/Game of Thrones - I.cpp: -------------------------------------------------------------------------------- 1 | //Game of Thrones - I 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int cnt[26]; 8 | 9 | int main() 10 | { 11 | string str; 12 | cin >> str; 13 | for (int i = 0; i < (int)str.size(); i++) 14 | cnt[str[i] - 'a']++; 15 | int even = 0, odd = 0; 16 | for (int i = 0; i < 26; i++) 17 | { 18 | if (cnt[i] % 2 == 0) even++; 19 | else odd++; 20 | } 21 | 22 | if (odd <= 1) 23 | cout << "YES" << endl; 24 | else 25 | cout << "NO" << endl; 26 | 27 | return 0; 28 | } 29 | 30 | 31 | /* 32 | Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom. 33 | 34 | door 35 | 36 | But, to lock the door he needs a key that is an anagram of a palindrome. He starts to go through his box of strings, checking to see if they can be rearranged into a palindrome. Given a string, determine if it can be rearranged into a palindrome. Return the string YES or NO. 37 | 38 | Example 39 | */ -------------------------------------------------------------------------------- /Contests/FJP-2 Contest-05/Gemstones.cpp: -------------------------------------------------------------------------------- 1 | //Gemstones 2 | 3 | #include 4 | 5 | 6 | using namespace std; 7 | string s[101]; 8 | int main() 9 | { 10 | ios::sync_with_stdio(0); 11 | int n; 12 | cin >> n; 13 | for(int i = 0 ; i < n ; ++i) 14 | cin >> s[i]; 15 | 16 | int ans = 0; 17 | for(char ch = 'a' ; ch <= 'z' ; ++ch) 18 | { 19 | bool fl = 1; 20 | for(int i = 0 ; fl && i < n ; ++i) 21 | { 22 | fl = 0; 23 | for(int j = 0 ; j < s[i].size() ; ++j) 24 | if(s[i][j] == ch) 25 | fl = 1; 26 | } 27 | if(fl) 28 | ++ans; 29 | } 30 | cout << ans << "\n"; 31 | return 0; 32 | } 33 | 34 | 35 | /* 36 | There is a collection of rocks where each rock has various minerals embeded in it. Each type of mineral is designated by a lowercase letter in the range . There may be multiple occurrences of a mineral in a rock. A mineral is called a gemstone if it occurs at least once in each of the rocks in the collection. 37 | 38 | Given a list of minerals embedded in each of the rocks, display the number of types of gemstones in the collection. 39 | */ -------------------------------------------------------------------------------- /Contests/FJP-2 Contest-06/NonRepeatablePermutationLaxicographical.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //NonRepeatablePermutationLaxicographical 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | /*Take as input str, a string. We are concerned with all possible permutations of 17 | characters in str. E.g. “abc” can produce following words “abc”, “acb”, “bac”, 18 | “bca”, “cab”, “cba” 19 | 20 | a. Write a recursive function which returns the count of different permutations 21 | for a given string(repetition not allowed). Print the value returned. 22 | 23 | b. Write a recursive function which prints all possible permutations for a 24 | given string in Laxicographical Order 25 | (repetition not allowed and void is the return type for function). 26 | 27 | Example(To be used only for expected output): 28 | Input: 29 | 213 30 | 31 | output 32 | 6 33 | 123 34 | 132 35 | 213 36 | 231 37 | 312 38 | 321 39 | Input Format 40 | 41 | String will be Input 42 | 43 | Constraints 44 | 45 | String may be large. 46 | 47 | Output Format 48 | 49 | print the output. 50 | 51 | Sample Input 0 52 | 53 | 213 54 | Sample Output 0 55 | 56 | 6 57 | 123 58 | 132 59 | 213 60 | 231 61 | 312 62 | 321*/ -------------------------------------------------------------------------------- /Contests/Intuit Hiring Challenge/Water Regions.java: -------------------------------------------------------------------------------- 1 | // Water Regions 2 | 3 | /* 4 | Easy 5 | 6 | 1. Given n non-negative integers a1, a2, ..., an. 7 | 2. Each represents a point at coordinate (i, ai). 8 | 3. "n" vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). 9 | 4. Find two lines, which, together with the x-axis forms a region, such that the region contains the most water. 10 | Note : that you may not slant the container. 11 | 12 | Constraints 13 | 14 | 1. n == height.length 15 | 2. 2 <= n <= 105 16 | 3. 0 <= height[i] <= 104 17 | 18 | Format 19 | 20 | Input 21 | 22 | 1. Take 'n', size of Array 23 | 2. Take 'n' different element for Array 24 | [15:08, 1/12/2022] Mukesh Dani: Output 25 | 26 | 1. Max water 27 | 28 | Example 29 | 30 | Sample Input 31 | 32 | 9 33 | 1 34 | 8 35 | 6 36 | 2 37 | 5 38 | 4 39 | 8 40 | 3 41 | 7 42 | 43 | Sample Output 44 | 45 | 49 46 | 47 | */ -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/0 1 Knapsack.java: -------------------------------------------------------------------------------- 1 | //0 1 Knapsack 2 | 3 | // 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Add Linked Lists.java: -------------------------------------------------------------------------------- 1 | //Add Linked Lists 2 | //https://www.codingninjas.com/codestudio/problems/add-linked-lists_920495 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/BST to greater tree.java: -------------------------------------------------------------------------------- 1 | //BST to greater tree 2 | //https://www.codingninjas.com/codestudio/problems/bst-to-greater-tree_800311 3 | 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Best Time to Buy and Sell Stock III.java: -------------------------------------------------------------------------------- 1 | //Best Time to Buy and Sell Stock III 2 | //https://www.codingninjas.com/codestudio/problems/buy-and-sell-stock_1071012 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Check If Linked List Is Palindrome.java: -------------------------------------------------------------------------------- 1 | //Check If Linked List Is Palindrome 2 | //https://www.codingninjas.com/codestudio/problems/check-if-linked-list-is-palindrome_985248 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Closest Leaf To Given Node In Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Closest Leaf To Given Node In Binary Tree 2 | //https://www.codingninjas.com/codestudio/problems/closest-leaf-to-given-node-in-binary-tree_983627 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Dijkstra's shortest path.java: -------------------------------------------------------------------------------- 1 | //Dijkstra's shortest path 2 | 3 | // 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Equilibrium indices of a Sequence.java: -------------------------------------------------------------------------------- 1 | //Equilibrium indices of a Sequence 2 | //https://www.codingninjas.com/codestudio/problems/equilibrium-index-of-an-array_842464 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Is Height Balanced Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Is Height Balanced Binary Tree 2 | 3 | //https://www.codingninjas.com/codestudio/problems/is-height-balanced-binary-tree_975497 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Kth ancestor of a node in binary tree.java: -------------------------------------------------------------------------------- 1 | //Kth ancestor of a node in binary tree 2 | //https://www.codingninjas.com/codestudio/problems/kth-ancestor-of-a-node-in-binary-tree_842561 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Longest Alternating Subsequence.java: -------------------------------------------------------------------------------- 1 | //Longest Alternating Subsequence 2 | //https://www.codingninjas.com/codestudio/problems/longest-alternating-subsequence_1214645 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Maximum sum of non-adjacent elements.java: -------------------------------------------------------------------------------- 1 | //Maximum sum of non-adjacent elements 2 | //https://www.codingninjas.com/codestudio/problems/maximum-sum-of-non-adjacent-elements_843261 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Minimum Jumps.java: -------------------------------------------------------------------------------- 1 | //Minimum Jumps 2 | //https://www.codingninjas.com/codestudio/problems/minimum-jumps_1062693 3 | 4 | 5 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Multiply Linked Lists.java: -------------------------------------------------------------------------------- 1 | //Multiply Linked Lists 2 | 3 | //https://www.codingninjas.com/codestudio/problems/multiply-linked-lists_983603 4 | 5 | 6 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/N Queens.java: -------------------------------------------------------------------------------- 1 | //N Queens 2 | //https://www.codingninjas.com/codestudio/problems/n-queens_759332 3 | 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Nuts and Bolt Problem.java: -------------------------------------------------------------------------------- 1 | //Nuts and Bolt Problem 2 | //https://www.codingninjas.com/codestudio/problems/evaluation-of-postfix_842782 3 | 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Remove BST keys outside the given range.java: -------------------------------------------------------------------------------- 1 | //Remove BST keys outside the given range 2 | //https://www.codingninjas.com/codestudio/problems/remove-bst-keys-outside-the-given-range_920538 3 | 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Reverse Linked List.java: -------------------------------------------------------------------------------- 1 | //Reverse Linked List 2 | //https://www.codingninjas.com/codestudio/problems/reverse-the-singly-linked-list_799897 3 | 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Rotate Matrix K times.java: -------------------------------------------------------------------------------- 1 | //Rotate Matrix K times 2 | //https://www.codingninjas.com/codestudio/problems/rotate-matrix-k-times_626061 3 | 4 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Segregate Odd-Even.java: -------------------------------------------------------------------------------- 1 | //Segregate Odd-Even 2 | //https://www.codingninjas.com/codestudio/problems/segregate-odd-even_920524 3 | -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Spiral Matrix.java: -------------------------------------------------------------------------------- 1 | //Spiral Matrix 2 | // -------------------------------------------------------------------------------- /Contests/JoshTechnology Group All Questions/Sum root to leaf.java: -------------------------------------------------------------------------------- 1 | // /Sum root to leaf 2 | //https://www.codingninjas.com/codestudio/problems/sum-root-to-leaf_1095657 3 | 4 | -------------------------------------------------------------------------------- /Contests/fjp-2 Contest-07/SpecificStringBetweenParanthesis.java: -------------------------------------------------------------------------------- 1 | //SpecificStringBetweenParanthesis 2 | 3 | /*1.Take as input String. 4 | 5 | The string contains pairs of parenthesis “(..)”. 6 | Write a recursive function which returns the contents between the parenthesis. 7 | 8 | Example(To be used only for expected output): 9 | 10 | Input: 11 | xyz(abc)def 12 | 13 | output 14 | (abc) 15 | Input Format 16 | 17 | String representing S. 18 | 19 | Constraints 20 | 21 | Size of String may be large. 22 | 23 | Output Format 24 | 25 | print the output. 26 | 27 | Sample Input 0 28 | 29 | xyz(pepcoding)def 30 | Sample Output 0 31 | 32 | (pepcoding)*/ 33 | -------------------------------------------------------------------------------- /Leetcode/Easy/Add Digits.java: -------------------------------------------------------------------------------- 1 | //Add Digits 2 | //https://leetcode.com/problems/add-digits/ 3 | 4 | 5 | class Solution { 6 | public int addDigits(int num) { 7 | if(num == 0){ 8 | return 0; 9 | } else if(num % 9 == 0) { 10 | return 9; 11 | } 12 | return num%9; 13 | } 14 | } -------------------------------------------------------------------------------- /Leetcode/Easy/Array/First Unique Character in a String.java: -------------------------------------------------------------------------------- 1 | //First Unique Character in a String 2 | 3 | class Solution { 4 | public int firstUniqChar(String s) { 5 | int [] store = new int[26]; 6 | 7 | for (int i = 0; i < s.length(); i++) { 8 | store[s.charAt(i) - 'a']++; 9 | //System.out.println(store[s.charAt(i) - 'a']++); 10 | } 11 | for (int i = 0; i < s.length(); i++) { 12 | if (store[s.charAt(i) - 'a'] == 1) { 13 | return i; 14 | } 15 | } 16 | return -1; 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /Leetcode/Easy/Array/TwoSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | You can return the answer in any order. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [2,7,11,15], target = 9 13 | Output: [0,1] 14 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 15 | Example 2: 16 | 17 | Input: nums = [3,2,4], target = 6 18 | Output: [1,2] 19 | Example 3: 20 | 21 | Input: nums = [3,3], target = 6 22 | Output: [0,1] 23 | 24 | 25 | Constraints: 26 | 27 | 2 <= nums.length <= 104 28 | -109 <= nums[i] <= 109 29 | -109 <= target <= 109 30 | */ 31 | 32 | // Source Code 33 | 34 | class Solution { 35 | public int[] twoSum(int[] nums, int target) { 36 | 37 | 38 | for ( int i = 0; i hm = new HashMap<>(); 8 | 9 | for( int i = 0 ; i0){ 17 | hm.put(ch,hm.get(ch)-1); 18 | }else { 19 | return ch ; 20 | } 21 | } 22 | return ' '; 23 | } 24 | } 25 | 26 | 27 | // Using BitM 28 | class Solution { 29 | public char findTheDifference(String s, String t) { 30 | char bit = 0; 31 | 32 | for (int i = 0; i < s.length(); ++i) { 33 | bit ^= s.charAt(i); 34 | } 35 | 36 | for (int i = 0; i < t.length(); ++i) { 37 | bit ^= t.charAt(i); 38 | } 39 | 40 | return bit; 41 | } 42 | } -------------------------------------------------------------------------------- /Leetcode/Easy/Formulas/PowerOfThree.java: -------------------------------------------------------------------------------- 1 | 2 | //Power of Three 3 | class Solution { 4 | public boolean isPowerOfThree(int n) { 5 | 6 | return (Math.log10(n) / Math.log10(3)) % 1 == 0; 7 | // Formula to check number is generalise as power of 4. 8 | } 9 | } 10 | 11 | 12 | 13 | 14 | 15 | 16 | /*Given an integer n, return true if it is a power of three. Otherwise, return false. 17 | 18 | An integer n is a power of three, if there exists an integer x such that n == 3x. 19 | 20 | 21 | 22 | Example 1: 23 | 24 | Input: n = 27 25 | Output: true 26 | Example 2: 27 | 28 | Input: n = 0 29 | Output: false 30 | */ -------------------------------------------------------------------------------- /Leetcode/Easy/LinkedList/Delete the Middle Node of a Linked List.java: -------------------------------------------------------------------------------- 1 | //Delete the Middle Node of a Linked List 2 | // /https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/ 3 | 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode() {} 11 | * ListNode(int val) { this.val = val; } 12 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 13 | * } 14 | */ 15 | class Solution { 16 | public ListNode deleteMiddle(ListNode head) { 17 | ListNode slow = head , fast = head ,prev = null ; 18 | 19 | if ( head==null||head.next==null){ 20 | return null; 21 | } 22 | while ( fast != null && fast.next != null){ 23 | prev = slow ; 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | 28 | prev.next = slow.next; 29 | 30 | return head ; 31 | } 32 | } -------------------------------------------------------------------------------- /Leetcode/Easy/LinkedList/Remove Linked List Elements.java: -------------------------------------------------------------------------------- 1 | //Remove Linked List Elements 2 | //https://leetcode.com/problems/remove-linked-list-elements/ 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * public class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode() {} 10 | * ListNode(int val) { this.val = val; } 11 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 12 | * } 13 | */ 14 | class Solution { 15 | public ListNode removeElements(ListNode head, int val) { 16 | ListNode dummy = new ListNode(-1); 17 | ListNode tail = dummy ; 18 | 19 | while ( head!= null){ 20 | if (head.val != val ){ 21 | tail.next = head ; 22 | tail = head ; 23 | head = head.next ; 24 | }else { 25 | head = head.next; 26 | } 27 | } 28 | 29 | tail.next = null; 30 | return dummy.next ; 31 | } 32 | } -------------------------------------------------------------------------------- /Leetcode/Easy/Recursion/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | //Fibonacci Number 2 | class Solution { 3 | public int fib(int n) { 4 | if ( n<2 )return n; 5 | 6 | return fib(n-2)+fib(n-1); 7 | } 8 | } 9 | 10 | // without recursion 11 | int a = -1; 12 | int b = 1; 13 | int c = 0; 14 | for(int i = 0; i <= n; i++) { 15 | c = a + b; // sum of previous two 16 | a = b; 17 | b = c; 18 | } 19 | return c; 20 | } 21 | } 22 | 23 | /* 24 | 25 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 26 | 27 | F(0) = 0, F(1) = 1 28 | F(n) = F(n - 1) + F(n - 2), for n > 1. 29 | Given n, calculate F(n). 30 | 31 | 32 | 33 | Example 1: 34 | 35 | Input: n = 2 36 | Output: 1 37 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 38 | Example 2: 39 | 40 | Input: n = 3 41 | Output: 2 42 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 43 | 44 | */ -------------------------------------------------------------------------------- /Leetcode/Easy/Recursion/ReverseString.java: -------------------------------------------------------------------------------- 1 | public class ReverseString { 2 | 3 | } 4 | 5 | //Reverse String 6 | 7 | class Solution { 8 | public void reverse1(char[] s, int left, int right) 9 | { 10 | 11 | if(left >= right) return; 12 | char c = s[left]; 13 | s[left] = s[right]; 14 | s[right] = c; 15 | 16 | reverse1(s, left + 1, right -1); 17 | 18 | 19 | } 20 | 21 | public void reverseString(char[] s) { 22 | int left = 0; 23 | int right = s.length -1; 24 | reverse1(s, left, right); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Leetcode/Easy/String/PrintfirstcharacterOfEveryWord.java: -------------------------------------------------------------------------------- 1 | 2 | // Print first character of every word 3 | 4 | 5 | package string; 6 | 7 | public class PrintFirstCharacterOfWord { 8 | 9 | public static void main(String[] args) { 10 | 11 | String s = "Hello User!! Welcome"; 12 | 13 | char a[] = s.toCharArray(); 14 | 15 | for(int i = 0; i < a.length; i++) { 16 | if(a[i] != ' ' && (i == 0 || a[i - 1] == ' ')) { 17 | System.out.println(a[i]); 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Leetcode/Easy/String/TrimingString.java: -------------------------------------------------------------------------------- 1 | // Triming String 2 | // we knows the inbuild method for triming string --->str.trim() 3 | 4 | 5 | package string; 6 | 7 | public class TrimString { 8 | 9 | public static void main(String[] args) { 10 | String s = " Hello User!! Welcome "; 11 | 12 | char a[] = s.toCharArray(); 13 | int start = 0, end = a.length - 1, count; 14 | 15 | for(int i = 0; i < a.length; i++) { 16 | if(a[i] != ' ') { 17 | start = i; 18 | break; 19 | } 20 | } 21 | 22 | for(int i = a.length - 1; i > start - 1; i--) { 23 | if(a[i] != ' ') { 24 | end = i; 25 | break; 26 | } 27 | } 28 | 29 | count = end - start + 1; 30 | 31 | String result = new String(a, start, count); 32 | System.out.println("Trimmed string: " + result); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Leetcode/Easy/Valid Palindrome.java: -------------------------------------------------------------------------------- 1 | //Valid Palindrome 2 | //https://leetcode.com/problems/valid-palindrome/ 3 | 4 | class Solution { 5 | public boolean isPalindrome(String s) { 6 | int left = 0, right = s.length() - 1; 7 | while (left < right) { 8 | char cl = s.charAt(left); 9 | char cr = s.charAt(right); 10 | if (!Character.isLetterOrDigit(cl)) left++; 11 | else if (!Character.isLetterOrDigit(cr)) right--; 12 | else if (Character.toLowerCase(cl) != Character.toLowerCase(cr)) return false; 13 | else { 14 | left++; 15 | right--; 16 | } 17 | } 18 | return true; 19 | 20 | 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Leetcode/Mediam/Contiguous Array.java: -------------------------------------------------------------------------------- 1 | //Contiguous Array 2 | 3 | class Solution { 4 | public int findMaxLength(int[] nums) { 5 | HashMap map = new HashMap<>(); 6 | int sum = 0 ; 7 | int ans = 0 ; 8 | map.put(0,-1); 9 | 10 | for(int i = 0 ; i< nums.length ; i++){ 11 | if(nums[i]==0){ 12 | sum +=-1; 13 | }else if(nums[i]==1){ 14 | sum+=1; 15 | } 16 | 17 | if(map.containsKey(sum)){ 18 | int idx =map.get(sum); 19 | int len = i - idx ; 20 | if(len > ans ){ 21 | ans = len; 22 | } 23 | }else { 24 | map.put(sum, i); 25 | } 26 | } 27 | return ans ; 28 | } 29 | } -------------------------------------------------------------------------------- /Leetcode/Mediam/Minimum Number of Swaps to Make the String Balanced.java: -------------------------------------------------------------------------------- 1 | ////Minimum Number of Swaps to Make the String Balanced 2 | //https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/ 3 | class Solution { 4 | public int minSwaps(String s) { 5 | Stack stk = new Stack<>(); 6 | int count = 0 ; 7 | for( int i = 0 ; i< s.length() ; i++){ 8 | char ch = s.charAt(i); 9 | 10 | if(ch == '['){ 11 | stk.push(ch); 12 | }else { 13 | if(stk.isEmpty()== false && ch == ']'){ 14 | stk.pop(); 15 | }else { 16 | count++; 17 | } 18 | } 19 | } 20 | return (count+1)/2; 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /Leetcode/Mediam/Remove Duplicates from Sorted Array II.java: -------------------------------------------------------------------------------- 1 | //Remove Duplicates from Sorted Array II 2 | //https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 3 | class Solution { 4 | public int removeDuplicates(int[] nums) { 5 | int n = nums.length ; 6 | if(n<3)return n; 7 | 8 | int slow = 2 , fast = 2; 9 | while(fast=0;i--){ 20 | ansStr += charArray[i]; 21 | } 22 | ans = - Long.parseLong(ansStr); 23 | } 24 | else { 25 | 26 | int i=0; 27 | 28 | for(i = 0;i maxHeap = new PriorityQueue((a,b) ->(b-a)); 7 | PriorityQueue minHeap = new PriorityQueue((a,b) ->(a-b)); 8 | 9 | for(int i=0;i map = new HashMap<>(); 10 | map.put(0,1); 11 | int sum =0; 12 | for(int i = 0 ; i< arr.length ; i++){ 13 | sum +=arr[i]; 14 | if(map.containsKey(sum - k)){ 15 | ans+=map.get(sum-k); 16 | } 17 | map.put(sum , map.getOrDefault(sum , 0)+1); 18 | } 19 | return ans ; 20 | } 21 | } -------------------------------------------------------------------------------- /Leetcode/Mediam/Swap Nodes in Pairs.java: -------------------------------------------------------------------------------- 1 | //Swap Nodes in Pairs 2 | //https://leetcode.com/problems/swap-nodes-in-pairs/ 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode swapPairs(ListNode head) { 15 | ListNode cur = head,next = null,prev = null; 16 | int count = 0; 17 | while(cur!=null && count<2){ 18 | next = cur.next; 19 | cur.next = prev; 20 | prev = cur; 21 | cur = next; 22 | count++; 23 | }if(next!=null){ 24 | head.next = swapPairs(next); 25 | } 26 | return prev; 27 | 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Leetcode/Mediam/Validate Stack Sequences.java: -------------------------------------------------------------------------------- 1 | //Validate Stack Sequences 2 | //https://leetcode.com/problems/validate-stack-sequences/ 3 | class Solution { 4 | public boolean validateStackSequences(int[] pushed, int[] popped) { 5 | Stack stk = new Stack<>(); 6 | int j = 0 ; 7 | for(int i=0 ; i< pushed.length ; i++){ 8 | stk.push(pushed[i]); 9 | while(stk.size()>0 && stk.peek()==popped[j]){ 10 | j++; 11 | stk.pop(); 12 | } 13 | } 14 | return stk.size()==0; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Level 1/DP/Jump Game II.java: -------------------------------------------------------------------------------- 1 | //Jump Game II 2 | //https://leetcode.com/problems/jump-game-ii/ 3 | 4 | 5 | 6 | 7 | 8 | class Solution { 9 | public long memo(int src , int [] jumps , long[] dp){ 10 | if(src == jumps.length -1 )return 0;//length 11 | if(dp[src]!= -1)return dp[src]; 12 | long min = Integer.MAX_VALUE; 13 | 14 | for(int jump = 1 ; jump<=jumps[src] ; jump++){ 15 | if(src + jump < jumps.length ){ 16 | min = Math.min(min , memo(src + jump , jumps , dp) + 1l); 17 | } 18 | } 19 | dp[src] = min; 20 | 21 | return min; 22 | } 23 | public int jump(int[] nums) { 24 | long[] dp = new long[nums.length + 1]; 25 | Arrays.fill(dp , -1); 26 | return (int)memo(0 , nums , dp); 27 | } 28 | } -------------------------------------------------------------------------------- /Level 1/DP/Min Cost Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | //Min Cost Climbing Stairs 2 | //https://leetcode.com/problems/min-cost-climbing-stairs/ 3 | 4 | 5 | // memo 6 | 7 | class Solution { 8 | public int memo(int src , int[]cost , int[] dp){ 9 | if(src >= cost.length)return 0; 10 | if(dp[src]!=-1)return dp[src]; 11 | int ans1 = memo(src+1 , cost , dp); 12 | int ans2 = memo(src+2 , cost , dp); 13 | 14 | return dp[src] = Math.min(ans1 , ans2)+cost[src]; 15 | } 16 | 17 | 18 | public int minCostClimbingStairs(int[] cost) { 19 | int []dp = new int[cost.length + 1]; 20 | Arrays.fill(dp,-1); 21 | 22 | memo(0,cost,dp); 23 | return Math.min(dp[0],dp[1]); 24 | } 25 | } -------------------------------------------------------------------------------- /Level 1/DP/Minimum steps to minimize n as per given condition.java: -------------------------------------------------------------------------------- 1 | //Minimum steps to minimize n as per given condition 2 | //https://practice.geeksforgeeks.org/problems/minimum-steps-to-minimize-n-as-per-given-condition0618/1/ 3 | 4 | 5 | class Solution{ 6 | 7 | public int memo(int n , int[]dp){ 8 | if(n==1)return 0; 9 | if(dp[n]!=-1)return dp[n]; 10 | 11 | int ans1 = (n%2==0) ? memo(n/2 , dp):Integer.MAX_VALUE; 12 | int ans2 = (n%3 == 0 )? memo(n/3 , dp):Integer.MAX_VALUE; 13 | int ans3 = memo(n-1 , dp); 14 | 15 | return dp[n] = Math.min(ans1 , Math.min(ans2, ans3)) + 1; 16 | 17 | } 18 | public int minSteps(int N) 19 | { 20 | // Your code goes here 21 | int[] dp = new int [N+1]; 22 | 23 | Arrays.fill(dp , -1); 24 | return memo(N , dp); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/BenjaminBulbs.java: -------------------------------------------------------------------------------- 1 | 2 | // 1. You are given n number of bulbs. They are all switched off. A weird fluctuation in voltage hits the circuit n times. In the 1st fluctuation all bulbs are toggled, in the 2nd fluctuation every 2nd bulb is toggled, in the 3rd fluctuation every 3rd bulb is toggled and so on. You've to find which bulbs will be switched on after n fluctuations. 3 | // 2. Take as input a number n, representing the number of bulbs. 4 | // 3. Print all the bulbs that will be on after the nth fluctuation in voltage. 5 | import java.util.*; 6 | 7 | public class BenjaminBulbs{ 8 | 9 | public static void main(String[] args) { 10 | // write your code here 11 | Scanner scn = new Scanner (System.in); 12 | int n = scn.nextInt(); 13 | 14 | for( int i = 1; i*i<=n;i++){ 15 | for(int j = 1; j*j<=n ; j++ ){ 16 | if (i == j ){ 17 | System.out.println(i*j); 18 | } 19 | } 20 | } 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/GradingSystem.java: -------------------------------------------------------------------------------- 1 | //Second program 2 | //learn how to use if else satement in java 3 | 4 | import java.util.*; 5 | 6 | public class GradingSystem{ 7 | 8 | public static void main(String[] args) { 9 | // input - don''t change this code 10 | Scanner scn = new Scanner(System.in); 11 | int marks = scn.nextInt(); 12 | // input - don''t change this code 13 | 14 | // code here 15 | if (marks > 90){ 16 | System.out.println("excellent"); 17 | } 18 | else if (marks > 80 && marks <= 90){ 19 | System.out.println("good"); 20 | } 21 | else if (marks > 70 && marks <= 80){ 22 | System.out.println("fair"); 23 | } 24 | else if (marks > 60 && marks <= 70){ 25 | System.out.println("meets expectations"); 26 | } 27 | else { 28 | System.out.println("below par"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/PrimeFactorisation.java: -------------------------------------------------------------------------------- 1 | // find Prime Factorisation of a given number 2 | import java.util.*; 3 | 4 | public class PrimeFactorisation{ 5 | 6 | public static void main(String[] args) { 7 | // write your code here 8 | Scanner scn = new Scanner (System.in); 9 | int n = scn.nextInt(); 10 | 11 | for ( int fact = 2 ; fact*fact <=n ; fact=fact +1){ 12 | while ( n % fact == 0 ){ 13 | n=n/fact ; 14 | System.out.print(fact+ " "); 15 | } 16 | } 17 | if ( n!=1){ 18 | System.out.print(n); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/PrintFibonacciNumbers.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PrintFibonacciNumbers{ 4 | 5 | public static void main(String[] args) { 6 | // write your code here 7 | 8 | Scanner scn = new Scanner (System.in); 9 | int n = scn.nextInt(); 10 | int a=0; 11 | int b=1; 12 | for (int i=0; i < n ; i++){ 13 | System.out.println(a); 14 | int c=a+b; 15 | a=b; 16 | b=c; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/PrintPrimeNumber.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class PrintPrimeNumber{ 5 | public static void main(String[] args) { 6 | // write your code here 7 | Scanner scn = new Scanner(System.in); 8 | int low = scn.nextInt(); 9 | int high = scn.nextInt(); 10 | 11 | 12 | for (int i=low ;i<=high;i++){ 13 | int count =0; 14 | for (int num=2 ; num*num<=i; num++){ 15 | if (i%num==0){ 16 | count++; 17 | break; 18 | } 19 | } 20 | 21 | if (count==0){ 22 | System.out.println(i); 23 | } 24 | } 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/ReverseOFaNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class ReverseOFaNumber{ 4 | 5 | public static void main(String[] args) { 6 | // write your code here 7 | Scanner scn = new Scanner (System.in); 8 | int n = scn.nextInt(); 9 | 10 | while(n>0){ 11 | int s=0; 12 | s= (n%10); 13 | System.out.println(s); 14 | n = n/10; 15 | } 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/prime.java: -------------------------------------------------------------------------------- 1 | // Level 1 2 | //How to check prime number 3 | //learn how to use loop in java 4 | 5 | import java.util.*; 6 | 7 | public class prime{ 8 | 9 | public static void main(String[] args) { 10 | Scanner scn = new Scanner(System.in); 11 | 12 | // write ur code here 13 | int t =scn.nextInt(); 14 | 15 | int lv_t=1; 16 | while(lv_t<=t){ 17 | int n=scn.nextInt(); 18 | int lv=2; 19 | while(lvn){ 28 | System.out.println("prime"); 29 | } 30 | lv_t=lv_t+1; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/printZ.java: -------------------------------------------------------------------------------- 1 | // Java first program 2 | //learn how to print in java programming langauage 3 | 4 | public class printZ { 5 | 6 | public static void main(String[] args) { 7 | // Write your code here 8 | System.out.print("*****\n * \n * \n * \n*****"); 9 | } 10 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Basic Program/pythagorean_triplet.java: -------------------------------------------------------------------------------- 1 | // 1. You are required to check if a given set of numbers is a valid pythagorean triplet. 2 | // 2. Take as input three numbers a, b and c. 3 | // 3. Print true if they can form a pythagorean triplet and false otherwise. 4 | 5 | 6 | import java.util.*; 7 | 8 | public class pythagorean_triplet{ 9 | 10 | public static void main(String[] args) { 11 | // write your code here 12 | Scanner scn = new Scanner ( System.in ); 13 | int a =scn.nextInt(); 14 | int b =scn.nextInt(); 15 | int c = scn.nextInt(); 16 | 17 | if ( a>b && a>c){ 18 | if(a*a==b*b + c*c) 19 | System.out.println("true"); 20 | else System.out.println("false"); 21 | 22 | } 23 | else if ( b>a && b>c){ 24 | if (b*b==a*a + c*c) 25 | System.out.println("true"); 26 | else System.out.println("false"); 27 | } 28 | else { 29 | if(c*c==b*b+a*a) 30 | System.out.println("true"); 31 | else System.out.println("false"); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Functions and array/AnyBaseAddition.java: -------------------------------------------------------------------------------- 1 | //1. You are given a base b. 2 | //2. You are given two numbers n1 and n2 of base b. 3 | //3. You are required to add the two numbes and print their value in base b. 4 | 5 | import java.util.*; 6 | 7 | public class AnyBaseAddition{ 8 | 9 | public static void main(String[] args) { 10 | Scanner scn = new Scanner(System.in); 11 | int b = scn.nextInt(); 12 | int n1 = scn.nextInt(); 13 | int n2 = scn.nextInt(); 14 | 15 | int d = getSum(b, n1, n2); 16 | System.out.println(d); 17 | } 18 | 19 | public static int getSum(int b, int n1, int n2){ 20 | // write ur code here 21 | int carry = 0 ; 22 | int res = 0 ; 23 | int multiplier = 1; 24 | while ( carry >0 || n1>0 || n2>0){ 25 | int d1 = n1%10; 26 | int d2 = n2%10 ; 27 | int temp = carry + d1 + d2 ; 28 | 29 | int quet = temp / b; 30 | int rem = temp % b; 31 | 32 | 33 | res = res + (rem*multiplier) ; 34 | carry = quet; 35 | 36 | multiplier*=10; 37 | n1/=10; 38 | n2/=10; 39 | } 40 | return res; 41 | } 42 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Functions and array/AnyBaseToDecimal.java: -------------------------------------------------------------------------------- 1 | //1. You are given a number n. 2 | //2. You are given a base b. n is a number on base b. 3 | //3. You are required to convert the number n into its corresponding value in decimal number system. 4 | 5 | import java.util.*; 6 | 7 | public class AnyBaseToDecimal{ 8 | 9 | public static void main(String[] args) { 10 | Scanner scn = new Scanner(System.in); 11 | int n = scn.nextInt(); 12 | int b = scn.nextInt(); 13 | int d = getValueIndecimal(n, b); 14 | System.out.println(d); 15 | } 16 | 17 | public static int getValueIndecimal(int n, int b){ 18 | // write your code here 19 | int res = 0 ; 20 | int multiplier = 1; 21 | while ( n>0){ 22 | int divisor = n/10; 23 | int remainder = n%10; 24 | 25 | n= divisor; 26 | 27 | res = res + remainder*multiplier; 28 | multiplier*=b; 29 | } 30 | return res; 31 | } 32 | } 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Functions and array/DecimalToAnyBase.java: -------------------------------------------------------------------------------- 1 | //1. You are given a decimal number n. 2 | //2. You are given a base b. 3 | //3. You are required to convert the number n into its corresponding value in base b. 4 | 5 | 6 | import java.util.*; 7 | 8 | public class DecimalToAnyBase{ 9 | 10 | public static void main(String[] args) { 11 | Scanner scn = new Scanner(System.in); 12 | int n = scn.nextInt(); 13 | int b = scn.nextInt(); 14 | int dn = getValueInBase(n, b); 15 | System.out.println(dn); 16 | } 17 | 18 | public static int getValueInBase(int n, int b){ 19 | // write code here 20 | 21 | int res = 0 ; 22 | int multiplier = 1; 23 | while ( n>0){ 24 | int divisor = n/b; 25 | int remainder = n%b; 26 | n = divisor; 27 | res = res + remainder*multiplier; 28 | multiplier*=10; 29 | } 30 | return res ; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Functions and array/DigitFrequency.java: -------------------------------------------------------------------------------- 1 | 2 | //1. You are given a number n. 3 | //2. You are given a digit d. 4 | //3. You are required to calculate the frequency of digit d in number n. 5 | 6 | import java.util.*; 7 | 8 | public class DigitFrequency { 9 | 10 | public static void main(String[] args) { 11 | Scanner m=new Scanner(System.in); 12 | int n = m.nextInt(); 13 | int d = m.nextInt(); 14 | int f = getDigitFrequency(n, d); 15 | System.out.println(f); 16 | } 17 | 18 | public static int getDigitFrequency(int n, int d) { 19 | int freq=0 ; 20 | while (n!=0){ 21 | int ans = n%10; 22 | if (ans==d){ 23 | freq=freq+1; 24 | } 25 | n = n/10; 26 | } 27 | return freq; 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Patterns/Pattern1.java: -------------------------------------------------------------------------------- 1 | //1. You are given a number n. 2 | //2. You've to create a pattern of * and separated by tab as shown in output format. 3 | // * 4 | // * * 5 | // * * * 6 | 7 | 8 | import java.util.*; 9 | 10 | public class Pattern1 { 11 | 12 | public static void main(String[] args) { 13 | Scanner scn = new Scanner(System.in); 14 | int n = scn.nextInt(); 15 | 16 | // write ur code here 17 | for ( int i =1 ; i<=n ; i++){ 18 | 19 | for (int j = 1 ; j<=i; j++){ 20 | System.out.print("*\t"); 21 | } 22 | System.out.println(); 23 | } 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Patterns/Pattern2.java: -------------------------------------------------------------------------------- 1 | //1. You are given a number n. 2 | // 2. You've to create a pattern of * and separated by tab as shown in output format. 3 | //* * * * * 4 | //* * * * 5 | //* * * 6 | //* * 7 | //* 8 | 9 | import java.util.*; 10 | 11 | public class Pattern2 { 12 | 13 | public static void main(String[] args) { 14 | Scanner scn = new Scanner(System.in); 15 | int n = scn.nextInt(); 16 | 17 | // write ur code here 18 | for (int i = 1; i<=n;i++ ){ 19 | for ( int j=1; j<=n-(i-1);j++){ 20 | System.out.print("*\t"); 21 | } 22 | System.out.println(); 23 | } 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Patterns/pattern3.java: -------------------------------------------------------------------------------- 1 | //1. You are given a number n. 2 | //2. You've to create a pattern of * and separated by tab as shown in output format. 3 | 4 | // * 5 | // * * 6 | // * * * 7 | // * * * * 8 | // * * * * * 9 | 10 | import java.util.*; 11 | 12 | public class pattern3 { 13 | 14 | public static void main(String[] args) { 15 | Scanner scn = new Scanner(System.in); 16 | int n= scn.nextInt(); 17 | // write ur code here 18 | for( int i = 1 ; i<=n; i++){ 19 | 20 | for ( int j = 1 ; j<=n-i;j++){ 21 | System.out.print("\t"); 22 | } 23 | for( int j =1; j<=i;j++ ){ 24 | System.out.print("*\t"); 25 | } 26 | System.out.println(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Patterns/pattern4.java: -------------------------------------------------------------------------------- 1 | // * * * * * 2 | // * * * * 3 | // * * * 4 | // * * 5 | // * 6 | 7 | import java.util.*; 8 | 9 | public class pattern4 { 10 | 11 | public static void main(String[] args) { 12 | Scanner scn = new Scanner(System.in); 13 | int n = scn.nextInt(); 14 | 15 | // write ur code here 16 | 17 | for( int i = 1 ; i<=n;i++){ 18 | 19 | for ( int j = 1 ; j<=i-1;j++){ 20 | System.out.print("\t"); 21 | } 22 | for( int j = 1; j<=n-(i-1);j++){ 23 | System.out.print("*\t"); 24 | } 25 | System.out.println(); 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Level 1/Getting Started/Patterns/pattern5.java: -------------------------------------------------------------------------------- 1 | // * 2 | // * * * 3 | // * * * * * 4 | // * * * 5 | // * 6 | 7 | import java.util.*; 8 | 9 | public class pattern5 { 10 | 11 | public static void main(String[] args) { 12 | Scanner scn = new Scanner(System.in); 13 | int n= scn.nextInt(); 14 | 15 | // write ur code here 16 | //upper half 17 | 18 | for ( int i= 1 ; i<=(n/2+1);i++){ 19 | 20 | for ( int j =1 ; j<=(n/2+1)-i;j++){ 21 | System.out.print("\t"); 22 | } 23 | for( int j = 1 ; j<=2*i-1;j++){ 24 | System.out.print("*\t"); 25 | } 26 | System.out.println(); 27 | } 28 | 29 | //lower half 30 | int dec_count=n-2; 31 | for ( int i= 1 ; i<=(n/2);i++){ 32 | 33 | for ( int j =1 ; j<=i;j++){ 34 | System.out.print("\t"); 35 | } 36 | for( int j = 1 ; j<=dec_count;j++){ 37 | System.out.print("*\t"); 38 | } 39 | System.out.println(); 40 | dec_count=dec_count-2; 41 | } 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Patterns/pattern7.java: -------------------------------------------------------------------------------- 1 | // * 2 | // * 3 | // * 4 | // * 5 | // * 6 | 7 | import java.util.*; 8 | 9 | public class pattern7 { 10 | 11 | public static void main(String[] args) { 12 | Scanner scn = new Scanner(System.in); 13 | int n = scn.nextInt(); 14 | // write ur code here 15 | for(int i = 1 ; i<=n; i++){ 16 | 17 | for ( int j= 1 ; j <=i-1 ;j++){ 18 | System.out.print("\t"); 19 | } 20 | 21 | System.out.println("*"); 22 | } 23 | 24 | } 25 | } -------------------------------------------------------------------------------- /Level 1/Getting Started/Patterns/pattern8.java: -------------------------------------------------------------------------------- 1 | // * 2 | // * 3 | // * 4 | // * 5 | // * 6 | 7 | import java.util.*; 8 | 9 | public class pattern8 { 10 | 11 | public static void main(String[] args) { 12 | Scanner scn = new Scanner(System.in); 13 | int n = scn.nextInt(); 14 | 15 | // write ur code here 16 | for( int i = 1 ; i<=n;i++){ 17 | for ( int j= 1 ; j<=n-i; j++){ 18 | System.out.print("\t"); 19 | } 20 | System.out.println("*\t"); 21 | } 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Level 1/HashMap and Heap/Intersection of Two Arrays II.java: -------------------------------------------------------------------------------- 1 | //Intersection of Two Arrays II 2 | 3 | //https://leetcode.com/problems/intersection-of-two-arrays-ii/ 4 | 5 | 6 | /* 7 | class Solution { 8 | public int[] intersect(int[] nums1, int[] nums2) { 9 | List list = new ArrayList<>(); 10 | HashMap hm = new HashMap<>(); 11 | for(int i = 0 ; i 0){ 17 | list.add(nums2[i]); 18 | hm.put(nums2[i], hm.getOrDefault(nums2[i],0)-1); 19 | } 20 | } 21 | 22 | int[] result = new int[list.size()]; 23 | for(int i = 0; i < list.size(); i++) result[i] = list.get(i); 24 | 25 | return result; 26 | } 27 | } 28 | 29 | */ -------------------------------------------------------------------------------- /Level 1/HashMap and Heap/Intersection of Two Arrays.java: -------------------------------------------------------------------------------- 1 | //Intersection of Two Arrays 2 | //https://leetcode.com/problems/intersection-of-two-arrays/ 3 | 4 | 5 | /* 6 | class Solution { 7 | public int[] intersection(int[] nums1, int[] nums2) { 8 | List list = new ArrayList<>(); 9 | HashMap hm = new HashMap<>(); 10 | for(int i = 0 ; i 0){ 18 | int n = scn.nextInt(); 19 | int k = scn.nextInt(); 20 | 21 | int[] arr = new int[n]; 22 | for(int i=0; i q = new PriorityQueue<>(); 26 | for(int i=0; i= k){ 29 | System.out.print(q.remove() + " "); 30 | } 31 | } 32 | 33 | while(q.size() > 0){ 34 | System.out.print(q.remove() + " "); 35 | } 36 | 37 | System.out.println(); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Level 1/HashMap and Heap/array-of-doubled-pairs.java: -------------------------------------------------------------------------------- 1 | //array-of-doubled-pairs 2 | //https://leetcode.com/problems/array-of-doubled-pairs/ 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 1/Linked Lists/Big Integer/Subtraction in Linked List.java: -------------------------------------------------------------------------------- 1 | //Subtraction in Linked List 2 | //https://practice.geeksforgeeks.org/problems/subtraction-in-linked-list/1 3 | 4 | /*Given two linked lists that represent two large positive numbers. The task is to subtract the given two numbers represented by the linked list. Subtract the smaller from the larger one. 5 | 6 | Example 1: 7 | 8 | Input: 9 | L1 = 1->0->0 10 | L2 = 1->2 11 | Output: 8 8 12 | Explanation: 12 subtracted from 100 13 | gives us 88 as result. 14 | 15 | Your Task: 16 | The task is to complete the function subLinkedList() which should subtract the numbers represented by the linked list and return the head of the linked list representing the result. 17 | 18 | Expected Time Complexity: O(N). 19 | Expected Auxiliary Space: O(N). 20 | 21 | Constraints: 22 | 1 <= Length of the Linked List <= 10000*/ 23 | -------------------------------------------------------------------------------- /Level 1/Linked Lists/Odd Even Linked List.java: -------------------------------------------------------------------------------- 1 | //Odd Even Linked List 2 | //https://leetcode.com/problems/odd-even-linked-list/ 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * public class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode() {} 10 | * ListNode(int val) { this.val = val; } 11 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 12 | * } 13 | */ 14 | class Solution { 15 | public ListNode oddEvenList(ListNode head) { 16 | ListNode firstHead = new ListNode(-1); 17 | ListNode secondHead = new ListNode(-1); 18 | 19 | ListNode first = firstHead , second = secondHead; 20 | 21 | while ( head!= null){ 22 | first.next = head ; 23 | first = head ; 24 | head = head.next; 25 | if (head!= null){ 26 | second.next = head ; 27 | second = head ; 28 | head = head.next; 29 | } 30 | } 31 | second.next = null; 32 | + first.next = secondHead.next; 33 | return firstHead.next; 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Level 1/Linked Lists/Remove Duplicates from Sorted List.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 2 | //Remove Duplicate from Sorted List 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode deleteDuplicates(ListNode head) { 15 | ListNode dummy = new ListNode(-1); 16 | ListNode tail = dummy; 17 | while ( head != null){ 18 | if ( tail == dummy || head.val != tail.val){ 19 | tail.next = head ; 20 | tail = head ; 21 | } 22 | head = head.next; 23 | } 24 | tail.next = null ; 25 | return dummy.next; 26 | } 27 | } -------------------------------------------------------------------------------- /Level 1/Stack and Queue/Duplicate Brackets.java: -------------------------------------------------------------------------------- 1 | //Duplicate Brackets 2 | //https://nados.io/question/duplicate-brackets 3 | 4 | import java.io.*; 5 | import java.util.*; 6 | 7 | public class Main { 8 | 9 | public static void main(String[] args) throws Exception { 10 | Scanner scn = new Scanner (System.in); 11 | String str = scn.nextLine(); 12 | Stack stk = new Stack<>(); 13 | for(int i = 0 ; i< str.length(); i++){ 14 | char ch = str.charAt(i); 15 | if(ch ==')'){ 16 | if(stk.peek()=='('){ 17 | System.out.println("true"); 18 | return; 19 | } 20 | 21 | while(stk.peek()!='('){ 22 | stk.pop(); 23 | } 24 | stk.pop(); 25 | }else { 26 | stk.push(ch); 27 | } 28 | } 29 | 30 | System.out.println("false"); 31 | 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /Level 1/Stack and Queue/Sliding Window Maximum.java: -------------------------------------------------------------------------------- 1 | //Sliding Window Maximum 2 | //https://nados.io/question/sliding-window-maximum?zen=true 3 | 4 | //https://leetcode.com/problems/sliding-window-maximum/ 5 | 6 | class Solution { 7 | public int[] maxSlidingWindow(int[] nums, int k) { 8 | int[] res = new int[nums.length - k + 1]; 9 | int idx = 0; 10 | 11 | Deque q = new ArrayDeque<>(); 12 | 13 | for(int i=0; i when front element is excluded from current window 16 | if(q.size() > 0 && q.getFirst() <= i - k){ 17 | q.removeFirst(); 18 | } 19 | 20 | // removeLast -> smaller than our current element 21 | while(q.size() > 0 && nums[q.getLast()] < nums[i]){ 22 | q.removeLast(); 23 | } 24 | 25 | // addLast -> We may be answer of current or upcoming windows 26 | q.addLast(i); 27 | 28 | if(i >= k - 1){ 29 | // current window's maximum is at front of deque 30 | res[idx++] = nums[q.getFirst()]; 31 | } 32 | } 33 | 34 | return res; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Level 1/String, StringBuilder and arraylist/Print_All_Permutations_Of_A_String_Iteratively.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* --------------------------- */ 4 | 5 | import java.util.*; 6 | 7 | public class Print_All_Permutations_Of_A_String_Iteratively{ 8 | 9 | public static void solution(String str){ 10 | int n = factorial(str.length()); 11 | for(int i = 0 ; i < n; i++){ 12 | StringBuilder s = new StringBuilder(str); 13 | int dvd = i; 14 | for(int div = str.length(); div >= 1; div--){ 15 | int q = dvd / div; 16 | int r = dvd % div; 17 | System.out.print(s.charAt(r)); 18 | dvd = q; 19 | s.deleteCharAt(r); 20 | } 21 | System.out.println(); 22 | } 23 | } 24 | 25 | public static int factorial(int n){ 26 | int ans = 1; 27 | for(int i = 2; i <= n; i++){ 28 | ans *= i; 29 | } 30 | return ans; 31 | } 32 | public static void main(String[] args) { 33 | Scanner scn = new Scanner(System.in); 34 | String str = scn.next(); 35 | solution(str); 36 | scn.close(); 37 | } 38 | 39 | } 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Level 1/String, StringBuilder and arraylist/StringInterning.java: -------------------------------------------------------------------------------- 1 | // String Interning 2 | // difference between == and equals() 3 | // Imutability 4 | 5 | 6 | import java.util.*; 7 | 8 | public class StringInterning{ 9 | 10 | public static void main(String[] args) { 11 | Scanner scn = new Scanner(System.in); 12 | String str = "pepcoder"; 13 | String str2 = new String("hello"); 14 | String str3 ="hello"; 15 | String str4 = new String ("hello"); 16 | String str5 = "hello"; 17 | 18 | 19 | System.out.println(str2==str3); 20 | System.out.println(str3==str5); 21 | System.out.println(str2==str4); 22 | System.out.println(str2.equals(str3)); 23 | System.out.println(str3.equals(str5)); 24 | System.out.println(str2.equals(str4)); 25 | System.out.println(str==str2); 26 | System.out.println(str.equals(str2)); 27 | scn.close(); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /Level 1/Tree/Binary Search Tree/Convert Sorted Array to Binary.java: -------------------------------------------------------------------------------- 1 | //Convert Sorted Array to Binary 2 | //https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/submissions/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | 21 | public TreeNode constract(int[] arr , int lo , int hi){ 22 | int mid = lo + (hi - lo) /2; 23 | //mid = (lo+hi)>>1 24 | 25 | if(lo>hi){ 26 | return null; 27 | } 28 | TreeNode node = new TreeNode(arr[mid]); 29 | 30 | node.left = constract(arr , lo , mid-1); 31 | node.right = constract(arr , mid+1 , hi); 32 | return node; 33 | 34 | 35 | } 36 | public TreeNode sortedArrayToBST(int[] nums) { 37 | return constract(nums , 0 , nums.length -1); 38 | } 39 | } -------------------------------------------------------------------------------- /Level 1/Tree/Binary Tree/Binary Tree Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | //Binary Tree Inorder Traversal 2 | //https://leetcode.com/problems/binary-tree-inorder-traversal/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | List ans = new ArrayList(); 21 | 22 | public void inorder(TreeNode root) { 23 | if(root == null) 24 | return; 25 | 26 | inorder(root.left); 27 | ans.add(root.val); 28 | inorder(root.right); 29 | } 30 | 31 | public List inorderTraversal(TreeNode root) { 32 | inorder(root); 33 | return ans; 34 | } 35 | } -------------------------------------------------------------------------------- /Level 1/Tree/Binary Tree/Delete Leaves With a Given Value.java: -------------------------------------------------------------------------------- 1 | //Delete Leaves With a Given Value 2 | 3 | //https://leetcode.com/problems/delete-leaves-with-a-given-value/ 4 | 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * public class TreeNode { 9 | * int val; 10 | * TreeNode left; 11 | * TreeNode right; 12 | * TreeNode() {} 13 | * TreeNode(int val) { this.val = val; } 14 | * TreeNode(int val, TreeNode left, TreeNode right) { 15 | * this.val = val; 16 | * this.left = left; 17 | * this.right = right; 18 | * } 19 | * } 20 | */ 21 | class Solution { 22 | public TreeNode removeLeafNodes(TreeNode root, int target) { 23 | if(root==null){ 24 | return null; 25 | } 26 | if(root.right==null&&root.left==null&&root.val==target){ 27 | return null; 28 | } 29 | root.left=removeLeafNodes(root.left,target); 30 | root.right=removeLeafNodes(root.right,target); 31 | 32 | if(root.right==null&&root.left==null&&root.val==target){ 33 | return null; 34 | } 35 | return root; 36 | } 37 | } -------------------------------------------------------------------------------- /Level 1/Tree/Binary Tree/Lowest Common Ancestor of a Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Lowest Common Ancestor of a Binary Tree 2 | 3 | //https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/submissions/ 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class Solution { 15 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 16 | if(root == null) return null; 17 | 18 | if(root == p || root == q ){ 19 | return root; 20 | } 21 | 22 | TreeNode left = lowestCommonAncestor(root.left , p , q); 23 | TreeNode right = lowestCommonAncestor(root.right , p , q); 24 | if(left != null && right != null){ 25 | return root; 26 | } 27 | 28 | if(left==null)return right; 29 | return left; 30 | } 31 | } -------------------------------------------------------------------------------- /Level 1/Tree/Binary Tree/Same Tree.java: -------------------------------------------------------------------------------- 1 | //Same Tree 2 | //https://leetcode.com/problems/same-tree/ 3 | 4 | 5 | class Solution { 6 | public boolean isSameTree(TreeNode p, TreeNode q) { 7 | if(p==null || q==null) return p==q; 8 | 9 | if(p.val==q.val) 10 | return isSameTree(p.left,q.left) && isSameTree(p.right,q.right); 11 | 12 | return false; 13 | } 14 | } -------------------------------------------------------------------------------- /Level 1/Tree/Binary Tree/Symmetric Tree.java: -------------------------------------------------------------------------------- 1 | //Symmetric Tree 2 | //https://leetcode.com/problems/symmetric-tree/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | public boolean sym(TreeNode r1 , TreeNode r2){ 21 | if(r1== null || r2 == null)return r1==r2; 22 | 23 | return (r1.val == r2.val)&& sym(r1.left , r2.right)&&sym(r1.right,r2.left); 24 | } 25 | public boolean isSymmetric(TreeNode root) { 26 | if(root == null || (root.left == null && root.right == null))return true; 27 | 28 | if(root.left == null)return false ; 29 | if(root.right == null)return false ; 30 | 31 | return sym(root,root); 32 | 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Level 1/Tree/Binary Tree/Unique Binary Search Trees.java: -------------------------------------------------------------------------------- 1 | //Unique Binary Search Trees 2 | //https://leetcode.com/problems/unique-binary-search-trees/ 3 | 4 | class Solution { 5 | public int numTrees(int n) { 6 | return (int)(comb(2*n, n)/(n+1)); 7 | } 8 | public double comb( int n, int k ) { 9 | double res = 1; 10 | if ( k > n-k ) { 11 | k = n - k; 12 | } 13 | for ( int i=0; i= max1){ 9 | max2 = max1; 10 | max1 = hc; 11 | } else if(hc >= max2){ 12 | max2 = hc; 13 | } 14 | } 15 | 16 | int dia = max1 + max2 + 2; 17 | maxDiameter = Math.max(dia, maxDiameter); 18 | 19 | return max1 + 1; 20 | } 21 | -------------------------------------------------------------------------------- /Level 1/Tree/Generic Tree/Maximum Depth of N-ary Tree.java: -------------------------------------------------------------------------------- 1 | //Maximum Depth of N-ary Tree 2 | //https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ 3 | /* 4 | // Definition for a Node. 5 | class Node { 6 | public int val; 7 | public List children; 8 | 9 | public Node() {} 10 | 11 | public Node(int _val) { 12 | val = _val; 13 | } 14 | 15 | public Node(int _val, List _children) { 16 | val = _val; 17 | children = _children; 18 | } 19 | }; 20 | */ 21 | 22 | class Solution { 23 | public int maxDepth(Node root) { 24 | if(root == null ) return 0 ; 25 | int height = 0 ; 26 | for(Node child : root.children){ 27 | height = Math.max(height , maxDepth(child)); 28 | } 29 | return 1+height; 30 | } 31 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Balance Array.java: -------------------------------------------------------------------------------- 1 | //Balance Array 2 | //https://www.interviewbit.com/problems/balance-array/ 3 | 4 | 5 | class main { 6 | public int solve(int[] A) { 7 | int even = 0; 8 | int odd = 0; 9 | 10 | for(int i = 0 ; i=0 ; i--){ 18 | Car c = cars[i]; 19 | double ctime = (target - c.pos) * 1.0/c.speed; 20 | 21 | if(ctime > time){ 22 | time = ctime; 23 | groups++; 24 | } 25 | } 26 | return groups; 27 | } 28 | 29 | public class Car implements Comparable{ 30 | int pos; 31 | int speed ; 32 | Car(int pos , int speed){ 33 | this.pos = pos ; 34 | this.speed = speed; 35 | } 36 | 37 | public int compareTo(Car o){ 38 | return this.pos - o.pos; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Chaining Technique/Max Chunks To Make Sorted II.java: -------------------------------------------------------------------------------- 1 | //Max Chunks To Make Sorted II 2 | //https://leetcode.com/problems/max-chunks-to-make-sorted-ii/ 3 | 4 | 5 | class Solution { 6 | public int maxChunksToSorted(int[] arr) { 7 | //1. Generate rmin and fill it 8 | int [] rmin = new int [arr.length + 1]; 9 | rmin[arr.length] = Integer.MAX_VALUE; 10 | 11 | for(int i = arr.length - 1; i>= 0 ; i--){ 12 | rmin[i] = Math.min(rmin[i+1] , arr[i]); 13 | } 14 | //2. generate lmax and count the chunks 15 | int count = 0 ; 16 | int lmax = Integer.MIN_VALUE; 17 | for(int i = 0 ; i partitionLabels(String s) { 7 | HashMap map = new HashMap<>(); 8 | //1. Filing of impact of charcter 9 | 10 | for(int i = 0 ; i< s.length() ; i++){ 11 | char ch = s.charAt(i); 12 | map.put(ch , i); 13 | } 14 | 15 | //2. Making of result 16 | 17 | List res = new ArrayList<>(); 18 | int prev = -1 ; 19 | int max = 0 ; 20 | 21 | for(int i = 0 ; i< s.length() ; i++){ 22 | char ch = s.charAt(i); 23 | max = Math.max(max , map.get(ch)); 24 | if(max == i){ 25 | res.add(max - prev); 26 | prev = max; 27 | } 28 | } 29 | 30 | return res; 31 | } 32 | } */ -------------------------------------------------------------------------------- /Level 2/Array & String/Chocolate Distribution Problem.java: -------------------------------------------------------------------------------- 1 | //Chocolate Distribution Problem 2 | 3 | //https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1 4 | 5 | import java.util.*; 6 | 7 | class Solution 8 | { 9 | public long findMinDiff (ArrayList a, int n, int m) 10 | { 11 | // your code here 12 | Collections.sort(a); 13 | 14 | int ans = Integer.MAX_VALUE; 15 | 16 | for(int e = m - 1; e < a.size() ; e++){ 17 | int s = e - m + 1; 18 | 19 | int diff = a.get(e) - a.get(s); 20 | ans = Math.min(ans , diff); 21 | 22 | } 23 | 24 | return ans; 25 | } 26 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Consecutive Numbers Sum.java: -------------------------------------------------------------------------------- 1 | //Consecutive Numbers Sum 2 | //https://leetcode.com/problems/consecutive-numbers-sum/ 3 | 4 | 5 | class Solution { 6 | public int consecutiveNumbersSum(int n) { 7 | int res = 0 ; 8 | int k = 1; 9 | int check = k*(k-1)/2; 10 | while(check < n){ 11 | if((n-check)%k == 0){ 12 | res++; 13 | } 14 | k++; 15 | check = k*(k-1)/2; 16 | } 17 | 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Container With Most Water.java: -------------------------------------------------------------------------------- 1 | //Container With Most Water 2 | 3 | 4 | class Solution { 5 | public int maxArea(int[] height) { 6 | int i = 0 ; 7 | int j = height.length - 1; 8 | 9 | int water = 0 ; 10 | while(i1; i--) 20 | { 21 | while (n%i == 0) 22 | { 23 | n = n/i; 24 | res[j] = i; 25 | j++; 26 | } 27 | } 28 | 29 | 30 | if (n > 10) 31 | { 32 | return "-1"; 33 | } 34 | 35 | for (i=j-1; i>=0; i--) 36 | ans.append(res[i]); 37 | 38 | return ans.toString(); 39 | } 40 | }; -------------------------------------------------------------------------------- /Level 2/Array & String/Extra Space/Contains Duplicate II.java: -------------------------------------------------------------------------------- 1 | //Contains Duplicate II 2 | 3 | //https://leetcode.com/problems/contains-duplicate-ii/ 4 | 5 | 6 | import java.util.*; 7 | class Solution { 8 | public boolean containsNearbyDuplicate(int[] nums, int k) { 9 | HashMap valueToIndexMap = new HashMap<>(); 10 | int n = nums.length; 11 | 12 | for(int i = 0; i < n; i++) { 13 | if(valueToIndexMap.containsKey(nums[i]) && 14 | (Math.abs(valueToIndexMap.get(nums[i]) - i)) <= k) { 15 | return true; 16 | } else { 17 | valueToIndexMap.put(nums[i], i); 18 | } 19 | } 20 | return false; 21 | } 22 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Extra Space/Contains Duplicate.java: -------------------------------------------------------------------------------- 1 | // Contains Duplicate 2 | //https://leetcode.com/problems/contains-duplicate/ 3 | 4 | 5 | import java.util.*; 6 | class Solution { 7 | public boolean containsDuplicate(int[] nums) { 8 | HashSet vis = new HashSet<>(); 9 | for(int val : nums){ 10 | if(vis.contains(val) == true){ 11 | return true; 12 | } 13 | vis.add(val); 14 | } 15 | return false; 16 | } 17 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Find Minimum in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | //Find Minimum in Rotated Sorted Array 2 | //https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 3 | 4 | class Solution { 5 | public int findMin(int[] nums) { 6 | int left = 0 ; 7 | int right = nums.length - 1; 8 | int min = Integer.MAX_VALUE; 9 | 10 | while(left < right){ 11 | 12 | int mid = left - ( left - right)/2; 13 | 14 | if(nums[right] > nums[mid]){ 15 | right = mid; 16 | }else if(nums[right] < nums[mid]){ 17 | left = mid + 1; 18 | } 19 | 20 | } 21 | return nums[left]; 22 | } 23 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Find Pair Given Difference.java: -------------------------------------------------------------------------------- 1 | //Find Pair Given Difference 2 | //https://practice.geeksforgeeks.org/problems/find-pair-given-difference1559/1 3 | 4 | /* 5 | class Solution 6 | { 7 | public boolean findPair(int arr[], int size, int n) 8 | { 9 | //code here. 10 | Arrays.sort(arr); 11 | 12 | int i = 1 , j=0; 13 | while(i n){ 17 | j++; 18 | if(j == i){ 19 | i++; 20 | } 21 | }else if(diff < n) { 22 | i++; 23 | }else { 24 | return true; 25 | } 26 | } 27 | 28 | return false ; 29 | } 30 | } */ -------------------------------------------------------------------------------- /Level 2/Array & String/Find the Smallest Divisor Given a Threshold.java: -------------------------------------------------------------------------------- 1 | //Find the Smallest Divisor Given a Threshold 2 | //https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/ 3 | 4 | class Solution { 5 | public int smallestDivisor(int[] nums, int threshold) { 6 | int left = 1 ; 7 | int right = 1000000; 8 | 9 | while(left < right){ 10 | int mid = left + (right - left)/2; 11 | 12 | int sum = 0; 13 | for(int num : nums){ 14 | sum += ( num + mid -1 )/mid;// mid - 1 for ceil value; 15 | } 16 | 17 | if(sum > threshold){ 18 | left = mid + 1 ; 19 | }else { 20 | right = mid; 21 | } 22 | } 23 | return left; 24 | } 25 | } -------------------------------------------------------------------------------- /Level 2/Array & String/First Missing Positive.java: -------------------------------------------------------------------------------- 1 | //First Missing Positive 2 | //https://leetcode.com/problems/first-missing-positive/ 3 | 4 | 5 | class Solution { 6 | public int firstMissingPositive(int[] nums) { 7 | int n = nums.length; 8 | for(int i = 0 ; i< nums.length ; i++){ 9 | if(nums[i] <=0 || nums[i] > n){ 10 | nums[i] = n + 1; 11 | } 12 | } 13 | 14 | for(int i = 0 ; i0){ 21 | nums[idx] = -1 * nums[idx]; 22 | } 23 | } 24 | } 25 | 26 | for( int i = 0 ; i 0){ 28 | return i+1; 29 | } 30 | } 31 | 32 | return n + 1; 33 | } 34 | } -------------------------------------------------------------------------------- /Level 2/Array & String/First negative integer in every window of size k.java: -------------------------------------------------------------------------------- 1 | //First negative integer in every window of size k 2 | 3 | //https://practice.geeksforgeeks.org/problems/first-negative-integer-in-every-window-of-size-k3345/1 4 | 5 | 6 | 7 | class Compute { 8 | 9 | public long[] printFirstNegativeInteger(long A[], int N, int K) 10 | { 11 | long[] ans = new long[N-K+1]; 12 | int j = 0 ; 13 | for(int i = 0 ; i<=N -K ; i++){ 14 | if(j= 0){ 19 | j++; 20 | } 21 | 22 | if(A[j] < 0){ 23 | ans[i] = A[j]; 24 | } 25 | } 26 | 27 | return ans; 28 | } 29 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Indexing Based Sorting/Find All Duplicates in an Array.java: -------------------------------------------------------------------------------- 1 | //Find All Duplicates in an Array 2 | //https://leetcode.com/problems/find-all-duplicates-in-an-array/ 3 | 4 | import java.util.*;; 5 | class Solution { 6 | public List findDuplicates(int[] nums) { 7 | int n = nums.length ; 8 | for(int i=0 ; i< n ; i++){ 9 | int val = nums[i] % (n+1); 10 | nums[val - 1] += (n+1); 11 | } 12 | List List = new ArrayList<>(); 13 | for(int i = 0 ; i< n; i++){ 14 | if(nums[i]/(n+1) > 1){ 15 | List.add(i+1); 16 | } 17 | } 18 | return List; 19 | } 20 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Indexing Based Sorting/Find All Numbers Disappeared in an Array.java: -------------------------------------------------------------------------------- 1 | //Find All Numbers Disappeared in an Array 2 | //https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ 3 | 4 | 5 | import java.util.*; 6 | class Solution { 7 | public List findDisappearedNumbers(int[] nums) { 8 | //visiting Each elemnets 9 | 10 | int n = nums.length ; 11 | 12 | for(int i = 0 ; i< n ; i++){ 13 | int val = nums[i] % (n+1); 14 | 15 | nums[val - 1] += (n+1); 16 | } 17 | 18 | // Find 19 | List missing = new ArrayList<>(); 20 | for(int i = 0 ; i < n ; i++){ 21 | if(nums[i] < n+1){ 22 | missing.add(i+1); 23 | } 24 | } 25 | return missing ; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Level 2/Array & String/Indexing Based Sorting/First Missing Positive.java: -------------------------------------------------------------------------------- 1 | //First Missing Positive 2 | //https://leetcode.com/problems/first-missing-positive/ 3 | 4 | class Solution { 5 | public int firstMissingPositive(int[] nums) { 6 | //Discard number <=0 AND >= n+1 7 | for(int i = 0 ; i< nums.length ; i++){ 8 | if(nums[i] <= 0 || nums[i] >= nums.length+1){ 9 | nums[i] = 0 ; 10 | } 11 | } 12 | 13 | //Visiting each element and fill 14 | 15 | for(int i = 0 ; i< nums.length ; i++){ 16 | int val = nums[i] % (nums.length + 1); 17 | if(val != 0) nums[val -1] += (nums.length +1); 18 | } 19 | 20 | //Missing Positive 21 | for(int i = 0 ; i< nums.length ; i++){ 22 | if((nums[i]) < nums.length+1) return (i+1); 23 | } 24 | return nums.length+1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Level 2/Array & String/Indexing Based Sorting/Maximum repeating number.java: -------------------------------------------------------------------------------- 1 | //Maximum repeating number 2 | 3 | //https://practice.geeksforgeeks.org/problems/maximum-repeating-number4858/1 4 | 5 | 6 | class Solution { 7 | int maxRepeating(int[] nums, int n, int k) { 8 | for(int i = 0 ; i maxfreq){ 16 | maxfreq = nums[i] / k; 17 | maxRepeating = i; 18 | } 19 | } 20 | 21 | return maxRepeating; 22 | } 23 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Indexing Based Sorting/Missing Number.java: -------------------------------------------------------------------------------- 1 | //Missing Number 2 | //https://leetcode.com/problems/missing-number/submissions/ 3 | 4 | 5 | class Solution { 6 | public int missingNumber(int[] nums) { 7 | //Indexing based firat question 8 | 9 | int n = nums.length ; 10 | 11 | //visiting each number and fill 12 | for(int i =0 ; i=nums[l1]){ 10 | l2 = l1; 11 | l1 = i; 12 | }else if(l2 == -1 || nums[i]>= nums[l2]){ 13 | l2 = i; 14 | } 15 | } 16 | 17 | if(nums[l1] >= 2*nums[l2])return l1; 18 | else return -1; 19 | } 20 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Long Pressed Name.java: -------------------------------------------------------------------------------- 1 | //Long Pressed Name 2 | //https://leetcode.com/problems/long-pressed-name/ 3 | 4 | class Solution { 5 | public boolean isLongPressedName(String name, String typed) { 6 | if(name.length()>typed.length())return false ; 7 | 8 | int i = 0 ; 9 | int j = 0 ; 10 | 11 | while(i0 && name.charAt(i-1) == typed.charAt(j)){ 16 | j++; 17 | }else { 18 | return false ; 19 | } 20 | } 21 | 22 | while(j majorityElement(int[] arr, int k) { 6 | // write yout code here 7 | int n = arr.length ; 8 | 9 | HashMap map = new HashMap<>(); 10 | 11 | for(int i = 0 ; i res = new ArrayList<>(); 20 | 21 | for(int key : map.keySet()){ 22 | if(map.get(key) > n/k){ 23 | res.add(key); 24 | } 25 | } 26 | return res; 27 | } 28 | */ -------------------------------------------------------------------------------- /Level 2/Array & String/Majority Elements/Majority Element.java: -------------------------------------------------------------------------------- 1 | //Majority Element 2 | //https://leetcode.com/problems/majority-element/ 3 | 4 | 5 | class Solution { 6 | public int majorityElement(int[] nums) { 7 | int majority = nums[0]; 8 | int freq = 0; 9 | 10 | for(int val : nums){ 11 | if(majority == val){ 12 | freq ++; 13 | }else { 14 | freq--; 15 | if(freq == 0){ 16 | majority = val; 17 | freq = 1; 18 | } 19 | } 20 | } 21 | 22 | return majority; 23 | } 24 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Majority Elements/Set Matrix Zeroes.java: -------------------------------------------------------------------------------- 1 | //Set Matrix Zeroes} 2 | //https://leetcode.com/problems/set-matrix-zeroes/ 3 | 4 | 5 | class Solution { 6 | public void setZeroes(int[][] matrix) { 7 | boolean [] rows = new boolean [matrix.length]; 8 | boolean [] cols = new boolean [matrix[0].length]; 9 | 10 | for(int i = 0 ; i k){ 18 | if(nums[j] == 0){ 19 | count0--; 20 | } 21 | j++; 22 | } 23 | // 24 | int length = i-j + 1; 25 | res = Math.max(res , length); 26 | 27 | } 28 | 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Max sum in sub-arrays.java: -------------------------------------------------------------------------------- 1 | //Max sum in sub-arrays 2 | //https://practice.geeksforgeeks.org/problems/max-sum-in-sub-arrays0824/1 3 | 4 | class Solution { 5 | 6 | public static long pairWithMaxSum(long arr[], long N) 7 | { 8 | // Your code goes here 9 | long ans = 0 ; 10 | 11 | for(int i = 0 ; i < N - 1 ; i++){ 12 | if(arr[i] + arr[i+1] >ans){ 13 | ans = arr[i] + arr[i+1]; 14 | } 15 | } 16 | return ans; 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Maximize Distance to Closest Person.java: -------------------------------------------------------------------------------- 1 | //Maximize Distance to Closest Person 2 | //https://leetcode.com/problems/maximize-distance-to-closest-person/submissions/ 3 | 4 | 5 | class Solution { 6 | public int maxDistToClosest(int[] seats) { 7 | int j = - 1; 8 | int res = 0 ; 9 | 10 | for(int i = 0 ; i< seats.length ; i++ ){ 11 | if(seats[i] == 1){ 12 | int ans = 0 ; 13 | 14 | if(j<0){ 15 | ans = i; 16 | }else { 17 | ans = (i-j)/2; 18 | } 19 | res = Math.max(res , ans); 20 | j=i; 21 | } 22 | } 23 | 24 | int ans = seats.length -1 -j; 25 | res = Math.max(res , ans); 26 | 27 | return res; 28 | } 29 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Maximum Swap.java: -------------------------------------------------------------------------------- 1 | //Maximum Swap 2 | 3 | 4 | class Solution { 5 | public int maximumSwap(int num) { 6 | char[] arr = (num + "").toCharArray(); 7 | 8 | int[] right = new int[arr.length]; 9 | for(int i = arr.length - 2; i >= 0; i--){ 10 | if(i == arr.length - 1){ 11 | right[i] = -1; 12 | } else if(i == arr.length - 2){ 13 | right[i] = arr.length - 1; 14 | } else { 15 | if(arr[i + 1] > arr[right[i + 1]]){ 16 | right[i] = i + 1; 17 | } else { 18 | right[i] = right[i + 1]; 19 | } 20 | } 21 | } 22 | 23 | for(int i = 0; i < arr.length - 1; i++){ 24 | if(arr[i] < arr[right[i]]){ 25 | char temp = arr[i]; 26 | arr[i] = arr[right[i]]; 27 | arr[right[i]] = temp; 28 | break; 29 | } 30 | } 31 | 32 | return Integer.parseInt(new String(arr)); 33 | } 34 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Minimum Moves to Equal Array Elements II.java: -------------------------------------------------------------------------------- 1 | //Minimum Moves to Equal Array Elements II 2 | //https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ 3 | 4 | /* 5 | class Solution { 6 | public int minMoves2(int[] nums) { 7 | Arrays.sort(nums); 8 | int sum = 0 ; 9 | int left = 0 ; 10 | int right = nums.length -1 ; 11 | while(left < right){ 12 | sum += Math.abs(nums[left] -nums[right]); 13 | left++; 14 | right--; 15 | } 16 | return sum; 17 | } 18 | } */ -------------------------------------------------------------------------------- /Level 2/Array & String/Minimum Moves to Equal Array Elements.java: -------------------------------------------------------------------------------- 1 | //Minimum Moves to Equal Array Elements 2 | class Solution { 3 | public int minMoves(int[] nums) { 4 | int min = Integer.MAX_VALUE; 5 | for(int i = 0 ;i < nums.length ; i++){ 6 | min = Math.min(nums[i] , min); 7 | } 8 | 9 | int ans = 0 ; 10 | for(int i = 0 ; i< nums.length ; i++){ 11 | ans += nums[i] - min; 12 | } 13 | 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Minimum Platforms.java: -------------------------------------------------------------------------------- 1 | //Minimum Platforms 2 | //https://practice.geeksforgeeks.org/problems/minimum-platforms-1587115620/1 3 | 4 | /* 5 | class Solution 6 | { 7 | 8 | static int findPlatform(int arr[], int dep[], int n) 9 | { 10 | Arrays.sort(arr); 11 | Arrays.sort(dep); 12 | 13 | int count = 0 ; 14 | int max = 0 ; 15 | int i = 0 , j = 0 ; 16 | while(i= left && nums[i] <=right){ 10 | e = i ; 11 | }else if(nums[i] > right){ 12 | e = s = i; 13 | }else { 14 | //lesser 15 | } 16 | res +=(e-s); 17 | } 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Pairs of Songs With Total Durations Divisible by 60.java: -------------------------------------------------------------------------------- 1 | //Pairs of Songs With Total Durations Divisible by 60 2 | //https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ 3 | -------------------------------------------------------------------------------- /Level 2/Array & String/Reach a Number.java: -------------------------------------------------------------------------------- 1 | //Reach a Number 2 | //https://leetcode.com/problems/reach-a-number/ 3 | 4 | 5 | 6 | class Solution { 7 | public int reachNumber(int target) { 8 | int x = 0 ; 9 | target = Math.abs(target); 10 | while(true){ 11 | int range = x*(x+1)/2; 12 | if(range >= target && range % 2 == target % 2){ 13 | break; 14 | } 15 | x++; 16 | } 17 | 18 | return x; 19 | } 20 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Reverse Vowels of a String.java: -------------------------------------------------------------------------------- 1 | //Reverse Vowels of a String 2 | //https://leetcode.com/problems/reverse-vowels-of-a-string/ 3 | 4 | 5 | class Solution { 6 | public String reverseVowels(String s) { 7 | String check = "aeiouAEIOU"; 8 | StringBuilder sb = new StringBuilder(s); 9 | int left = 0 ; 10 | int right = sb.length() -1; 11 | while(left < right){ 12 | while(left < right && check.indexOf(sb.charAt(left)) == -1){ 13 | left++; 14 | } 15 | 16 | while(left < right && check.indexOf(sb.charAt(right))==-1){ 17 | right--; 18 | } 19 | char temp = sb.charAt(left); 20 | sb.setCharAt(left , sb.charAt(right)); 21 | sb.setCharAt(right , temp); 22 | 23 | left++; 24 | right--; 25 | } 26 | 27 | return sb.toString(); 28 | } 29 | } -------------------------------------------------------------------------------- /Level 2/Array & String/Shortest Unsorted Continuous Subarray.java: -------------------------------------------------------------------------------- 1 | //Shortest Unsorted Continuous Subarray 2 | //https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ 3 | 4 | class Solution { 5 | public int findUnsortedSubarray(int[] nums) { 6 | int end = -1; 7 | int max = nums[0]; 8 | for(int i = 0 ; i< nums.length ; i++){ 9 | if(max>nums[i]){ 10 | end = i; 11 | }else { 12 | max = nums[i]; 13 | } 14 | } 15 | 16 | int st = 0; 17 | int min = nums[nums.length - 1]; 18 | 19 | for(int i = nums.length -2 ; i>=0 ; i--){ 20 | if(min sieveOfEratosthenes(int N){ 7 | // code here 8 | ArrayList ans = new ArrayList<>(); 9 | boolean [] isPrime = new boolean[N+1]; 10 | Arrays.fill(isPrime , true); 11 | 12 | for(int i = 2 ; i*i <= isPrime.length ; i++){ 13 | if(isPrime[i] == true){ 14 | for(int j = i+i ; j 0) swap += freq[i]; 22 | } 23 | 24 | if(swap<=k)return true; 25 | return false; 26 | } 27 | } -------------------------------------------------------------------------------- /Level 2/Array & String/String Matching Problems/Find All Anagrams in a String.java: -------------------------------------------------------------------------------- 1 | //Find All Anagrams in a String 2 | //https://leetcode.com/problems/find-all-anagrams-in-a-string/ 3 | 4 | 5 | import java.util.*; 6 | class Solution { 7 | public boolean isAnagram(int[] freq){ 8 | for(int i = 0 ; i < 26 ; i++){ 9 | if(freq[i] != 0) return false; 10 | } 11 | return true; 12 | } 13 | public List findAnagrams(String s, String p) { 14 | int [] freq = new int[26]; 15 | for(int i = 0 ; i< p.length() ; i++){ 16 | freq[p.charAt(i) -'a']--; 17 | } 18 | List ans = new ArrayList<>(); 19 | for(int r = 0; r< s.length() ; r++){ 20 | freq[s.charAt(r) -'a']++;//right include 21 | int l = r - p.length(); 22 | if(l>=0)freq[s.charAt(l)-'a']--;//left exclued 23 | 24 | if(isAnagram(freq) == true)ans.add(l+1); 25 | } 26 | return ans; 27 | } 28 | } -------------------------------------------------------------------------------- /Level 2/Array & String/String Matching Problems/Find largest word in dictionary.java: -------------------------------------------------------------------------------- 1 | //Find largest word in dictionary 2 | //https://practice.geeksforgeeks.org/problems/find-largest-word-in-dictionary2430/1 3 | 4 | 5 | import java.util.*; 6 | class Solution { 7 | public static boolean isSubsequence(String s, String t) { 8 | int i = 0 , j = 0 ; 9 | while(i d) { 23 | String ans =""; 24 | for(String word : d){ 25 | if(isSubsequence(word , str) == true){ 26 | if(word.length() > ans.length() || (word.length() == ans.length() && word.compareTo(ans)<0)){ 27 | ans = word; 28 | } 29 | } 30 | } 31 | return ans; 32 | } 33 | } -------------------------------------------------------------------------------- /Level 2/Array & String/String Matching Problems/Group Anagrams.java: -------------------------------------------------------------------------------- 1 | //Group Anagrams 2 | //https://leetcode.com/problems/group-anagrams/ 3 | 4 | import java.util.*; 5 | class Solution { 6 | public List> groupAnagrams(String[] strs) { 7 | HashMap> groups = new HashMap<>(); 8 | 9 | //key -> sorted String , value -> List of ansgram 10 | 11 | for(String word : strs){ 12 | char[] arr = word.toCharArray(); 13 | Arrays.sort(arr); 14 | String parent = new String(arr); 15 | 16 | if(groups.containsKey(parent) == false){ 17 | groups.put(parent , new ArrayList<>()); 18 | } 19 | groups.get(parent).add(word); 20 | } 21 | 22 | 23 | List> res = new ArrayList<>(); 24 | 25 | for(String key : groups.keySet()){ 26 | res.add(groups.get(key)); 27 | } 28 | 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /Level 2/Array & String/String Matching Problems/Is Subsequence.java: -------------------------------------------------------------------------------- 1 | //Is Subsequence 2 | //https://leetcode.com/problems/is-subsequence/ 3 | 4 | class Solution { 5 | public boolean isSubsequence(String s, String t) { 6 | int i = 0 , j = 0 ; 7 | while(i= requiredWood?true:false; 13 | } 14 | public int solve(int[] trees, int requiredWood) { 15 | 16 | int left = 0 , right = 1000000; 17 | while(left <= right){ 18 | int mid = left + (right - left)/2; 19 | 20 | if(isPossible(trees , mid , requiredWood) == true){ 21 | left = mid + 1 ; 22 | }else { 23 | right = mid - 1; 24 | } 25 | } 26 | return right; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Level 2/Binary Search/Binary Search On Matrix/(Only Row Sorted ) Row with max 1s.java: -------------------------------------------------------------------------------- 1 | //// https://practice.geeksforgeeks.org/problems/row-with-max-1s0023/1 2 | 3 | // Time = Avg O(N) Similar to Stepcase, Worst O(N * log N) BS on each row 4 | // Space = O(1) 5 | 6 | class Solution { 7 | public int binarySerach(int [][]arr, int row , int left , int right){ 8 | while(left<=right){ 9 | int mid = left + (right - left)/2; 10 | 11 | if(arr[row][mid] == 0){ 12 | left = mid + 1; 13 | }else right = mid - 1; 14 | } 15 | return left; 16 | } 17 | int rowWithMax1s(int arr[][], int n, int m) { 18 | // Binary Search on Each Row 19 | //Stepcse Search not happen 20 | int right = m-1 ,ans = -1; 21 | int left = 0 ; 22 | for(int row = 0 ; row < n ; row++){ 23 | int mid = binarySerach(arr , row , 0 , right); 24 | if(mid <= right){ 25 | ans = row ; 26 | right = mid - 1;//reduced Binary Serach for next row 27 | } 28 | } 29 | return ans; 30 | } 31 | } -------------------------------------------------------------------------------- /Level 2/Binary Search/Binary Search On Matrix/Count zeros in a sorted matrix.java: -------------------------------------------------------------------------------- 1 | //Row and Col Sorted 2 | // https://practice.geeksforgeeks.org/problems/count-zeros-in-a-sorted-matrix/1 3 | 4 | 5 | // Time = O(N) : Stepcase Search, Space = O(1) 6 | 7 | 8 | class GfG { 9 | int countZeros(int mat[][], int N) { 10 | int row = 0, col = N - 1, zeros = 0; 11 | 12 | while (row < N && col >= 0) { 13 | if (mat[row][col] == 0) { 14 | zeros = zeros + (col + 1); // all zeros in current row 15 | row++; // no more zeros: discard row 16 | } else { 17 | col--; // no zero in current column: discard column 18 | } 19 | } 20 | return zeros; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Level 2/Binary Search/Binary Search On Matrix/Row , Col Sorted.java: -------------------------------------------------------------------------------- 1 | // Optimized Approach: Divide & Conquer Based 2 | // Stepcase or Staircase Search 3 | // Time = O(N), Space = O(1) 4 | 5 | class Solution { 6 | public boolean searchMatrix(int[][] mat, int target) { 7 | int rows = mat.length, cols = mat[0].length; 8 | int row = 0, col = cols - 1; 9 | 10 | while (row < rows && col >= 0) { 11 | if (mat[row][col] == target) 12 | return true; 13 | if (mat[row][col] < target) 14 | row++; // discard the topmost row 15 | else 16 | col--; // discard the rightmost column 17 | } 18 | 19 | return false; 20 | } 21 | } -------------------------------------------------------------------------------- /Level 2/Binary Search/Binary Search in Sorted Array/Staircase Search.java: -------------------------------------------------------------------------------- 1 | //Staircase Search 2 | 3 | // Brute force approach 4 | // directly Binary search on each row ===>> O(n*logn) 5 | 6 | // Staircase Search -> O(N + M) 7 | 8 | /* 9 | 10 | row ---> Soreted 11 | Column ---> Sorted 12 | 13 | */ 14 | 15 | /* 16 | arr[mid]>target ===> discard column 17 | arr[mid ]discard row 18 | Unsucessfull Serach ==> out of the array 19 | */ 20 | 21 | 22 | class Solution { 23 | public boolean searchMatrix(int[][] matrix, int target) { 24 | // Staircase Search -> O(N + M) in Worst Case 25 | int row = 0, col = matrix[0].length - 1; // top right corner 26 | 27 | while (row < matrix.length && col >= 0) { 28 | if (matrix[row][col] == target) 29 | return true; 30 | if (target < matrix[row][col]) 31 | col--; 32 | else 33 | row++; 34 | } 35 | 36 | return false; 37 | } 38 | } -------------------------------------------------------------------------------- /Level 2/Binary Search/Find Nth root of M.java: -------------------------------------------------------------------------------- 1 | //Find Nth root of M 2 | 3 | 4 | public class Nthroot { 5 | public int NthRoot(int n, int m) 6 | { 7 | int low = 1, high = m; 8 | 9 | while(low <= high){ 10 | int mid = (low + high)/2; 11 | int mul = (int)Math.pow(mid,n); 12 | if(mul == m) return mid; 13 | else if(mul > m) high = mid - 1; 14 | else low = mid + 1; 15 | 16 | } 17 | return -1; 18 | } 19 | } 20 | 21 | 22 | 23 | 24 | /*You are given 2 numbers (n , m); the task is to find n√m (nth root of m). 25 | 26 | 27 | Example 1: 28 | 29 | Input: n = 2, m = 9 30 | Output: 3 31 | Explanation: 32 = 9 32 | Example 2: 33 | 34 | Input: n = 3, m = 9 35 | Output: -1 36 | Explanation: 3rd root of 9 is not 37 | integer. 38 | 39 | 40 | Your Task: 41 | You don't need to read or print anyhting. Your task is to complete the function NthRoot() which takes n and m as input parameter and returns the nth root of m. If the root is not integer then returns -1. 42 | 43 | 44 | Expected Time Complexity: O(n* log(m)) 45 | Expected Space Complexity: O(1) 46 | 47 | 48 | Constraints: 49 | 1 <= n <= 30 50 | 1 <= m <= 109*/ -------------------------------------------------------------------------------- /Level 2/Binary Search/Preimage Size of Factorial Zeroes Function.java: -------------------------------------------------------------------------------- 1 | //Preimage Size of Factorial Zeroes Function 2 | //https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/ 3 | 4 | 5 | //Time - 0(logN) 6 | //Space - 0(1) 7 | 8 | class Solution { 9 | public int preimageSizeFZF(int k) { 10 | long low = 0; 11 | long high = Long.MAX_VALUE; 12 | 13 | while(low <= high){ 14 | long mid = (low+high)/2; 15 | if(k == check(mid)) 16 | return 5; 17 | else if(k < check(mid)) 18 | high = mid - 1; 19 | else 20 | low = mid + 1; 21 | } 22 | 23 | return 0; 24 | } 25 | public long check(long k){ 26 | long sum = 0; 27 | long x = 5; 28 | while(x <= k){ 29 | sum += k/x; 30 | x = x*5; 31 | } 32 | 33 | return sum; 34 | } 35 | } -------------------------------------------------------------------------------- /Level 2/Binary Search/StepArraySearch.java: -------------------------------------------------------------------------------- 1 | //StepArraySearch 2 | // https://practice.geeksforgeeks.org/problems/searching-in-an-array-where-adjacent-differ-by-at-most-k0456/1 3 | 4 | 5 | // Time = O(N) Linear Search Worst Case, O(N / K) Avg Case 6 | 7 | // Using Jump Search Algorithm 8 | 9 | 10 | class Complete{ 11 | 12 | // Function for finding maximum and value pair 13 | public static int search (int arr[], int n, int target, int jump) { 14 | //Complete the function 15 | int idx = 0; 16 | 17 | while(idx=0 ; idx--){ 11 | aheadNotBuy = Math.max(0+aheadNotBuy, prices[idx]-fee+ aheadBuy); 12 | aheadBuy = Math.max(0+aheadBuy, -prices[idx] + aheadNotBuy); 13 | } 14 | return aheadBuy; 15 | } 16 | } -------------------------------------------------------------------------------- /Level 2/DP/DP on Stocks/Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | //Best Time to Buy and Sell Stock 2 | //https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 3 | 4 | 5 | class Solution { 6 | public int maxProfit(int[] prices) { 7 | int mini = prices[0] , profit = 0; 8 | 9 | for(int i = 1; i=2 ? dp[i-2] : 1); 20 | }else { 21 | dp[i] = 0; 22 | } 23 | }else { 24 | if(Integer.parseInt(s.substring(i-1 , i+1)) <= 26){ 25 | dp[i] = dp[i-1] + (i>=2?dp[i-2]:1); 26 | }else { 27 | dp[i] = dp[i-1]; 28 | } 29 | } 30 | } 31 | 32 | return dp[s.length() - 1]; 33 | } 34 | } -------------------------------------------------------------------------------- /Level 2/DP/Fibonacci/Distinct Subsequences II.java: -------------------------------------------------------------------------------- 1 | //Distinct Subsequences II 2 | //https://leetcode.com/problems/distinct-subsequences-ii/ 3 | 4 | import java.util.*; 5 | class Solution { 6 | public int distinctSubseqII(String s) { 7 | int[] dp = new int[s.length()+1]; 8 | int mod = 1000000007; 9 | dp[0] = 1; 10 | HashMap map = new HashMap<>(); 11 | for(int i = 1; i nums[j] && dp1[i] < dp1[j] + 1){ 16 | dp1[i] = dp1[j] + 1; 17 | } 18 | } 19 | } 20 | 21 | 22 | int [] dp2 = new int [n]; 23 | Arrays.fill(dp2 , 1); 24 | for(int i = n-1 ; i>=0 ; i--){ 25 | for(int j = n-1 ; j>i ; j--){ 26 | if(nums[i] > nums[j] && dp2[i] < dp2[j] + 1){ 27 | dp2[i] = dp2[j] + 1; 28 | } 29 | } 30 | } 31 | 32 | int maxi = 0; 33 | for(int i = 0 ; i< n ; i++){ 34 | maxi = Math.max(maxi , dp1[i] + dp2[i] - 1); 35 | } 36 | return maxi; 37 | } 38 | } -------------------------------------------------------------------------------- /Level 2/DP/LIS/Maximum Profit in Job Scheduling.java: -------------------------------------------------------------------------------- 1 | //Maximum Profit in Job Scheduling 2 | //https://leetcode.com/problems/maximum-profit-in-job-scheduling/ 3 | -------------------------------------------------------------------------------- /Level 2/DP/LIS/Minimum number of increasing subsequences.java: -------------------------------------------------------------------------------- 1 | //Minimum number of increasing subsequences 2 | //https://www.geeksforgeeks.org/minimum-number-of-increasing-subsequences/ 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 2/DP/LIS/Russian Doll Envelopes.java: -------------------------------------------------------------------------------- 1 | //Russian Doll Envelopes 2 | //https://leetcode.com/problems/russian-doll-envelopes/ 3 | 4 | 5 | //TLE Solutions 6 | 7 | import java.util.*; 8 | class Solution { 9 | public int maxEnvelopes(int[][] envelopes) { 10 | Arrays.sort(envelopes , (e1,e2)->{ 11 | if(e1[0] != e2[0]){ 12 | return e1[0] - e2[0]; 13 | }else { 14 | return e2[1] - e1[1]; 15 | } 16 | }); 17 | 18 | int [] lis = new int[envelopes.length]; 19 | lis[0] = 1; 20 | for(int i =1 ; i< lis.length ; i++){ 21 | int max = 0; 22 | for(int j = 0 ; j < i ; j++){ 23 | if(envelopes[j][1] < envelopes[i][1]){ 24 | max = Math.max(max , lis[j]); 25 | } 26 | } 27 | lis[i] = max + 1; 28 | } 29 | int len =0 ; 30 | for(int val : lis){ 31 | len = Math.max(len , val); 32 | } 33 | return len; 34 | } 35 | } -------------------------------------------------------------------------------- /Level 2/DP/LIS/Weighted Job Scheduling.java: -------------------------------------------------------------------------------- 1 | //Weighted Job Scheduling 2 | //https://www.geeksforgeeks.org/weighted-job-scheduling-set-2-using-lis/?ref=rp -------------------------------------------------------------------------------- /Level 2/DP/LIS/min max/Paint House - Many Colors.java: -------------------------------------------------------------------------------- 1 | //Paint House - Many Colors 2 | ///https://pepcoding.com/resources/online-java-foundation/dynamic-programming-and-greedy/paint-house-many-colors-official/ojquestion 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 2/DP/LIS/min max/Paint House.java: -------------------------------------------------------------------------------- 1 | 2 | //Paint House 3 | //https://pepcoding.com/resources/online-java-foundation/dynamic-programming-and-greedy/paint-house-official/ojquestion 4 | 5 | 6 | import java.util.*; 7 | 8 | class Main { 9 | 10 | public static void main(String[] args) throws Exception { 11 | Scanner scn = new Scanner(System.in); 12 | 13 | int n = scn.nextInt(); 14 | 15 | int[][] arr = new int[n][3] 16 | ; 17 | 18 | for(int i = 0 ; i< n ; i++ ){ 19 | 20 | arr[i][0] = scn.nextInt(); 21 | arr[i][1] = scn.nextInt(); 22 | arr[i][2] = scn.nextInt(); 23 | 24 | } 25 | 26 | 27 | int r = arr[0][0]; 28 | int g = arr[0][1]; 29 | int b = arr[0][2]; 30 | 31 | for(int i = 1 ; i> generate(int rows) { 7 | List> pascal = new ArrayList<>(); 8 | pascal.add(new ArrayList<>()); 9 | 10 | pascal.get(0).add(1); 11 | 12 | for(int n = 1 ; n row = new ArrayList<>(); 14 | row.add(1); //nC0 15 | 16 | for(int k = 1 ; k1.0){ 15 | pascal[i+1][j] += (pascal[i][j] - 1.0) /2.0; 16 | pascal[i+1][j+1] += (pascal[i][j] - 1.0) /2.0; 17 | pascal[i][j] = 1.0; 18 | } 19 | } 20 | } 21 | 22 | return pascal[R-1][C-1]; 23 | 24 | } 25 | } -------------------------------------------------------------------------------- /Level 2/DP/Pascals-triangle/nCr.java: -------------------------------------------------------------------------------- 1 | //nCr 2 | //https://practice.geeksforgeeks.org/problems/ncr1019/1 3 | 4 | /* 5 | class Solution{ 6 | static int nCr(int rows, int col) 7 | { 8 | // code here 9 | if(col>rows) return 0; 10 | if(rows == 0|| rows == col || col == 0 ) return 1; 11 | 12 | List prev = new ArrayList<>(); 13 | 14 | prev.add(1); 15 | 16 | for(int n = 1 ; n<=rows ; n++){ 17 | List curr = new ArrayList<>(); 18 | curr.add(1); 19 | 20 | for(int k = 1 ; k path, List>paths){ 7 | 8 | if(vis[src] == true) return ; 9 | 10 | vis[src] = true; 11 | path.add(src); 12 | 13 | if(src == dest) paths.add(new ArrayList<>(path));//Deep Copy 14 | 15 | for(int nbr : graph[src]){ 16 | DFS(nbr , dest , vis , graph , path , paths ); 17 | } 18 | 19 | //Backtraking 20 | vis[src] = false ; 21 | path.remove(path.size()-1); 22 | } 23 | public List> allPathsSourceTarget(int[][] graph) { 24 | List path = new ArrayList<>(); 25 | List> paths = new ArrayList<>(); 26 | 27 | boolean[] vis = new boolean[graph.length]; 28 | 29 | DFS(0 , graph.length - 1 , vis , graph , path , paths); 30 | return paths; 31 | } 32 | } */ -------------------------------------------------------------------------------- /Level 2/Graph/Bellmon ford Algorithm/Distance from the Source (Bellman-Ford Algorithm).java: -------------------------------------------------------------------------------- 1 | //Distance from the Source (Bellman-Ford Algorithm) 2 | //https://practice.geeksforgeeks.org/problems/distance-from-the-source-bellman-ford-algorithm/1 3 | 4 | /* class Solution 5 | { 6 | static int[] bellman_ford(int v, ArrayList> edges, int s) 7 | { 8 | // Write your code here 9 | int []dist = new int[v]; 10 | 11 | Arrays.fill(dist , 100000000); 12 | 13 | dist[s] = 0; 14 | 15 | for(int i = 1 ; i< v ; i++){ 16 | for(ArrayList edge : edges){ 17 | int out = edge.get(0); 18 | int in = edge.get(1); 19 | int w = edge.get(2); 20 | 21 | if(dist[out] == 100000000)continue; 22 | 23 | dist[in] = Math.min(dist[in] , dist[out] + w); 24 | 25 | 26 | } 27 | } 28 | return dist; 29 | 30 | 31 | } 32 | } */ -------------------------------------------------------------------------------- /Level 2/Graph/Connected Components/Number Of Distinct Island.java: -------------------------------------------------------------------------------- 1 | //Number Of Distinct Island 2 | //https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/graphs/number-of-distinct-island-official/ojquestion 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 2/Graph/Connected Components/Number of Islands.java: -------------------------------------------------------------------------------- 1 | //Number of Islands 2 | //https://leetcode.com/problems/number-of-islands/ 3 | 4 | class Solution { 5 | public int numIslands(char[][] grid) { 6 | 7 | int count = 0 ; 8 | boolean [][] visited = new boolean[grid.length][grid[0].length]; 9 | 10 | for(int i = 0 ; i=grid.length || j>=grid[0].length)return; 24 | else if(grid[i][j] == '0')return; 25 | else if(visited[i][j] == true)return; 26 | 27 | visited[i][j] = true; 28 | traverse(grid , visited , i-1 , j); 29 | traverse(grid , visited , i+1 , j); 30 | traverse(grid , visited , i , j-1); 31 | traverse(grid , visited , i , j+1); 32 | } 33 | } -------------------------------------------------------------------------------- /Level 2/Graph/Cycle Detection/PrintCycle.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Level 2/Graph/DSU/Kruskal (MST) Algo/Minimum Spanning Tree.java: -------------------------------------------------------------------------------- 1 | //Minimum Spanning Tree 2 | //https://practice.geeksforgeeks.org/problems/minimum-spanning-tree/1 3 | -------------------------------------------------------------------------------- /Level 2/Graph/Euler Circuit and Path/CODE/(Undirected Graph) Euler circuit and Path.java: -------------------------------------------------------------------------------- 1 | package CODE; 2 | //Euler circuit and Path 3 | //https://practice.geeksforgeeks.org/problems/euler-circuit-and-path/1 4 | 5 | import java.util.*; 6 | class Solution 7 | { 8 | public int isEularCircuitExist(int V, ArrayList> adj) 9 | { 10 | // Code here 11 | int oddCount = 0 ; 12 | for(int i = 0 ; i=image.length || sc >= image[0].length)return ; 10 | 11 | if(image[sr][sc] != startColor)return ; 12 | 13 | image[sr][sc] = newColor; 14 | DFS(image , sr+1, sc , newColor , startColor); 15 | DFS(image , sr-1 , sc , newColor , startColor); 16 | DFS(image , sr , sc+1 , newColor , startColor); 17 | DFS(image , sr , sc-1 , newColor , startColor); 18 | } 19 | public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { 20 | if(image[sr][sc] == newColor)return image; 21 | DFS(image , sr , sc , newColor , image[sr][sc]); 22 | return image; 23 | } 24 | } -------------------------------------------------------------------------------- /Level 2/Graph/Floyd's Warshall Algorithm/Floyd Warshall.java: -------------------------------------------------------------------------------- 1 | //Floyd Warshall 2 | //https://practice.geeksforgeeks.org/problems/implementing-floyd-warshall2042/1 3 | 4 | 5 | class Solution 6 | { 7 | public void shortest_distance(int[][] dist) 8 | { 9 | // Code here 10 | int n = dist.length; 11 | for(int inter = 0 ; inter>adj) 9 | { 10 | // Code here 11 | int mv = -1; 12 | boolean[] vis = new boolean[V]; 13 | for(int v = 0; v < V; v++){ 14 | if(!vis[v]){ 15 | dfs(v, vis, adj); 16 | mv = v; 17 | } 18 | } 19 | 20 | Arrays.fill(vis, false); 21 | dfs(mv, vis, adj); 22 | 23 | for(int v = 0; v < V; v++){ 24 | if(vis[v] == false){ 25 | return -1; 26 | } 27 | } 28 | 29 | return mv; 30 | } 31 | 32 | public void dfs(int v, boolean[] vis, ArrayList> adj){ 33 | vis[v] = true; 34 | for(int n: adj.get(v)){ 35 | if(!vis[n]){ 36 | dfs(n, vis, adj); 37 | } 38 | } 39 | } 40 | 41 | 42 | } */ -------------------------------------------------------------------------------- /Level 2/Graph/Shortest Path In Unweighted Graph/Shortest path in an unweighted graph.java: -------------------------------------------------------------------------------- 1 | //Shortest path in an unweighted graph 2 | //https://www.codingninjas.com/codestudio/problems/shortest-path-in-an-unweighted-graph_981297 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 2/Graph/Shortest Path In Unweighted Graph/Spread Of Infection.java: -------------------------------------------------------------------------------- 1 | //Spread Of Infection 2 | //https://www.pepcoding.com/resources/online-java-foundation/graphs/infection-spread-official/ojquestion#! 3 | 4 | -------------------------------------------------------------------------------- /Level 2/Greedy/BAISED.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* ------------------------------------ */ 4 | import java.util.*; 5 | 6 | class BiasedStandings { 7 | 8 | public static void solve(){ 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | 12 | ArrayList[] buckets = new ArrayList[n+1]; 13 | 14 | for(int i=0; i<=n; i++) 15 | buckets[i] = new ArrayList<>(); 16 | 17 | for(int i=0; i<=n; i++){ 18 | String str = sc.next(); 19 | int rank = sc.nextInt(); 20 | buckets[rank].add(str); 21 | } 22 | 23 | int currRank = 1, badness = 0; 24 | for(int i=0; i<=n; i++){ 25 | for(String str: buckets[i]){ 26 | badness += (Math.abs(i - currRank)); 27 | currRank++; 28 | } 29 | } 30 | System.out.println(badness); 31 | } 32 | 33 | public static void main(String[] args){ 34 | Scanner sc = new Scanner(System.in); 35 | int t = sc.nextInt(); 36 | while(t-- > 0){ 37 | String temp = sc.nextLine(); 38 | solve(); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Level 2/Linked Lists/0's and 1's.java: -------------------------------------------------------------------------------- 1 | //0's and 1's 2 | 3 | //https://www.interviewbit.com/problems/sort-binary-linked-list/ 4 | 5 | public class Solution { 6 | public ListNode solve(ListNode head) { 7 | 8 | ListNode lHead = new ListNode(-1); 9 | ListNode lTail = lHead; 10 | 11 | ListNode rHead = new ListNode(-1); 12 | ListNode rTail = rHead; 13 | 14 | while ( head != null){ 15 | if ( head.val == 0){ 16 | lTail.next = head; 17 | lTail = head; 18 | }else { 19 | rTail.next = head ; 20 | rTail = head; 21 | } 22 | head = head.next; 23 | } 24 | 25 | lTail.next = rHead.next; 26 | rTail.next = null; 27 | return lHead.next; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Level 2/Linked Lists/Linked List Cycle II.java: -------------------------------------------------------------------------------- 1 | //Linked List Cycle II 2 | //https://leetcode.com/problems/linked-list-cycle-ii/ 3 | /** 4 | * Definition for singly-linked list. 5 | * class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { 9 | * val = x; 10 | * next = null; 11 | * } 12 | * } 13 | */ 14 | public class Solution { 15 | public ListNode detectCycle(ListNode head) { 16 | ListNode slow = head, fast =head; 17 | 18 | while (fast!=null && fast.next != null){ 19 | slow = slow.next; 20 | fast = fast.next.next; 21 | 22 | if ( slow == fast ) break;// detected 23 | } 24 | 25 | 26 | if (fast==null || fast.next == null ){ 27 | return null; 28 | } 29 | 30 | ListNode curr1=head , curr2= slow; 31 | 32 | while ( curr1 != curr2){ 33 | curr1 = curr1.next; 34 | curr2 = curr2.next; 35 | } 36 | 37 | return curr1; 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Level 2/Linked Lists/Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | //Linked List Cycle 2 | //https://leetcode.com/problems/linked-list-cycle/ 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if ( head == null || head.next == null){// 0 node and 1 node 18 | return false ; 19 | } 20 | 21 | if ( head.next == head ){ // self refrencial Node 22 | return true; 23 | } 24 | ListNode slow = head, fast =head; 25 | 26 | while (fast!=null && fast.next != null){ 27 | slow = slow.next; 28 | fast = fast.next.next; 29 | 30 | if ( slow == fast )return true;// detected 31 | } 32 | return false;} 33 | } -------------------------------------------------------------------------------- /Level 2/Linked Lists/Partition List.java: -------------------------------------------------------------------------------- 1 | // Partition List 2 | //https://leetcode.com/problems/partition-list/ 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode partition(ListNode head, int x) { 15 | ListNode lHead = new ListNode(-1); 16 | ListNode lTail = lHead; 17 | 18 | ListNode rHead = new ListNode(-1); 19 | ListNode rTail = rHead; 20 | 21 | while ( head != null){ 22 | if ( head.val < x){ 23 | lTail.next = head; 24 | lTail = head; 25 | }else { 26 | rTail.next = head ; 27 | rTail = head; 28 | } 29 | head = head.next; 30 | } 31 | 32 | lTail.next = rHead.next; 33 | rTail.next = null; 34 | return lHead.next; 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Level 2/Linked Lists/Quick Sort on Linked List.java: -------------------------------------------------------------------------------- 1 | ///Quick Sort on Linked List 2 | //https://practice.geeksforgeeks.org/problems/quick-sort-on-linked-list/1 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 2/Number Theory/Cutting Rectangles.java: -------------------------------------------------------------------------------- 1 | //Cutting Rectangles 2 | //https://practice.geeksforgeeks.org/problems/cutting-rectangles3659/1 3 | 4 | import java.util.*; 5 | 6 | class Solution{ 7 | static long gcd(long a , long b){ 8 | if(b==0)return a; 9 | return gcd(b , a%b); 10 | } 11 | static List minimumSquares(long L, long B) 12 | { 13 | // code here 14 | long side = gcd(L , B); 15 | 16 | long square = (L*B)/(side * side); 17 | List res = new ArrayList<>(); 18 | res.add(square); 19 | res.add(side); 20 | 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /Level 2/Number Theory/Find Greatest Common Divisor of Array.java: -------------------------------------------------------------------------------- 1 | //Find Greatest Common Divisor of Array 2 | //https://leetcode.com/problems/find-greatest-common-divisor-of-array/ 3 | 4 | 5 | class Solution { 6 | 7 | public int max(int [] arr){ 8 | int max = Integer.MIN_VALUE; 9 | for(int i = 0 ; i< arr.length ; i++){ 10 | max = Math.max(arr[i] , max); 11 | } 12 | return max; 13 | } 14 | 15 | public int min(int [] arr){ 16 | int min = Integer.MAX_VALUE; 17 | for(int i =0 ; i res = new ArrayList<>(); 10 | List right = new ArrayList<>(); 11 | 12 | for(int factor = 1 ; factor * factor <= n ; factor ++){ 13 | if(n % factor == 0){ 14 | res.add(factor); 15 | if(factor != n / factor)right.add(n/factor); 16 | 17 | } 18 | } 19 | 20 | Collections.reverse(right); 21 | res.addAll(right); 22 | 23 | if(k > res.size()){ 24 | return -1; 25 | } 26 | return res.get(k-1); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Level 2/Number Theory/Prime/Three Divisors.java: -------------------------------------------------------------------------------- 1 | //Three Divisors 2 | //https://leetcode.com/problems/three-divisors/ 3 | 4 | package Prime; 5 | class Solution { 6 | public boolean isPerfect(int n ){ 7 | int sqrt = (int)Math.sqrt(n); 8 | return (sqrt*sqrt == n); 9 | } 10 | public boolean isPrime(int n){ 11 | if(n == 0 || n==1)return false; 12 | 13 | for(int factor = 2 ; factor * factor <= n ; factor++){ 14 | if(n%factor == 0 )return false; 15 | } 16 | return true; 17 | } 18 | public boolean isThree(int n) { 19 | //Numer shoud be perfect square (odd divisior) 20 | // if it is square of prime , then odd divisors = exactly three 21 | if(isPerfect(n) == false)return false; 22 | 23 | int sqrt = (int)Math.sqrt(n); 24 | return isPrime(sqrt); 25 | } 26 | } -------------------------------------------------------------------------------- /Level 2/Number Theory/Required Rooms.java: -------------------------------------------------------------------------------- 1 | //Required Rooms 2 | 3 | //https://practice.geeksforgeeks.org/problems/required-rooms3939/1 4 | 5 | 6 | class Solution{ 7 | static int GCD(int a , int b){ 8 | if(b==0)return a; 9 | return GCD(b , a%b); 10 | } 11 | static int rooms(int N, int M){ 12 | // code here 13 | int gcd = GCD(N , M); 14 | int a = N/gcd; 15 | int b = M/gcd; 16 | return a + b; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Level 2/Recursion&Backtracking/Permutation Sequence.java: -------------------------------------------------------------------------------- 1 | //Permutation Sequence 2 | //https://leetcode.com/problems/permutation-sequence/ 3 | 4 | 5 | import java.util.*; 6 | class Solution { 7 | public String getPermutation(int n, int k) { 8 | int fact = 1 ; 9 | List numbers = new ArrayList<>(); 10 | for(int i = 1 ; i> permute(int[] nums) { 9 | List> ans = new ArrayList(); 10 | int[] visited = new int[nums.length]; 11 | permuteRec(nums, visited, new ArrayList(),ans); 12 | return ans; 13 | } 14 | 15 | public void permuteRec(int[] nums, int[] visited, List curr, List> ans){ 16 | if(curr.size() == visited.length){ 17 | ans.add(new ArrayList(curr)); 18 | return; 19 | } 20 | for(int i=0;i=0){ 7 | if(matrix[i][j] == target) return true; 8 | else if(matrix[i][j]>target) j--; 9 | else i++; 10 | } 11 | return false ; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Level 2/Sorting/StringSort.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* --------------------------String Sorting ----------------------- */ 4 | 5 | 6 | /* 7 | int[] lowerCase = new int[26]; 8 | int[] upperCase = new int[26]; 9 | int[] digits = new int[10]; 10 | 11 | for(int i=0; i= 'a' && ch <= 'z'){ 15 | lowerCase[ch - 'a']++; 16 | } else if(ch >= 'A' && ch <= 'Z'){ 17 | upperCase[ch - 'A']++; 18 | } else { 19 | digits[ch - '0']++; 20 | } 21 | } 22 | 23 | 24 | StringBuilder sb = new StringBuilder(""); 25 | for(int i=0; i<10; i++){ 26 | char ch = (char)(i + '0'); 27 | for(int j=0; j0) 21 | { 22 | result.append(r); 23 | } 24 | idx++; 25 | } 26 | else 27 | { 28 | result.append(s.charAt(idx++)); 29 | } 30 | } 31 | return result.toString(); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Evaluate Expression Tree.java: -------------------------------------------------------------------------------- 1 | //Evaluate Expression Tree 2 | //https://www.codingninjas.com/codestudio/problems/evaluate-expression-tree_975484?leftPanelTab=0 3 | 4 | 5 | /******************************************************* 6 | Following is the BinaryTreeNode class structure 7 | 8 | class BinaryTreeNode { 9 | T data; 10 | BinaryTreeNode left; 11 | BinaryTreeNode right; 12 | 13 | public BinaryTreeNode(T data) { 14 | this.data = data; 15 | } 16 | } 17 | *******************************************************/ 18 | public class Solution 19 | { 20 | public static int evaluateExpression(BinaryTreeNode root) 21 | { 22 | //WRITE YOUR CODE HERE 23 | 24 | if(root.left == null && root.right == null){ 25 | return Integer.parseInt(root.data); 26 | } 27 | 28 | int left = evaluateExpression(root.left); 29 | int right = evaluateExpression(root.right); 30 | 31 | if(root.data.equals("+"))return left + right ; 32 | if(root.data.equals("-"))return left - right ; 33 | if(root.data.equals("*"))return left * right ; 34 | return left / right ; 35 | } 36 | } -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Find the Most Competitive Subsequence.java: -------------------------------------------------------------------------------- 1 | //Find the Most Competitive Subsequence 2 | //https://leetcode.com/problems/find-the-most-competitive-subsequence/ -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Longest Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | //Longest Valid Parentheses 2 | //https://leetcode.com/problems/longest-valid-parentheses/ 3 | 4 | class Solution { 5 | public int longestValidParentheses(String s) { 6 | Stack stk = new Stack<>(); 7 | int maxLen = 0; 8 | 9 | for(int i=0; i 0 && s.charAt(stk.peek()) == '(') 14 | stk.pop(); 15 | else stk.push(i); 16 | } 17 | 18 | int j = (stk.size() == 0) ? -1 : stk.peek(); 19 | maxLen = Math.max(maxLen, i-j); 20 | } 21 | return maxLen; 22 | } 23 | } -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Minimum Add to Make Parentheses Valid.java: -------------------------------------------------------------------------------- 1 | //Minimum Add to Make Parentheses Valid 2 | //https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ 3 | 4 | class Solution { 5 | public int minAddToMakeValid(String str) { 6 | 7 | int obr = 0; // opening brackets 8 | int cbr = 0; // closing brackets 9 | 10 | for(int i=0; i 0) open--; 18 | else additions++; // add one opening character 19 | 20 | if(i + 1 < s.length() && s.charAt(i + 1) == ')') 21 | i++; 22 | else additions++; // add one closing character 23 | } 24 | } 25 | return additions + 2 * open; 26 | } 27 | } -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Minimum Remove to Make Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | //Minimum Remove to Make Valid Parentheses 2 | //e.com/problems/minimum-remove-to-make-valid-parentheses/ 3 | 4 | class Solution { 5 | public String minRemoveToMakeValid(String s) { 6 | Deque q = new ArrayDeque<>(); 7 | for(int i=0; i 0 && q.getFirst() == i){ 22 | q.removeFirst(); 23 | continue; 24 | } 25 | res.append(s.charAt(i)); 26 | } 27 | return res.toString(); 28 | } 29 | } -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Remove K Digits.java: -------------------------------------------------------------------------------- 1 | //Remove K Digits 2 | //https://leetcode.com/problems/remove-k-digits/ 3 | 4 | class Solution { 5 | public String removeKdigits(String num, int k) { 6 | Deque q = new ArrayDeque<>() ; 7 | 8 | for(int i = 0 ; i< num.length(); i++){ 9 | char ch = num.charAt(i); 10 | 11 | while(q.size() >0 && k > 0 && q.getLast()>ch){ 12 | q.removeLast(); 13 | k--; 14 | } 15 | q.addLast(ch); 16 | } 17 | while(q.size()>0 && k>0){ 18 | q.removeLast(); 19 | k--; 20 | } 21 | 22 | //remove leading 0's 23 | while(q.size()>0 && q.getFirst()=='0'){ 24 | q.removeFirst(); 25 | } 26 | 27 | if(q.size()==0 )return "0"; 28 | StringBuilder str = new StringBuilder(""); 29 | while(q.size() > 0 ){ 30 | str.append(q.removeFirst()); 31 | } 32 | 33 | return str.toString(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Reverse Stack Using Recursion.java: -------------------------------------------------------------------------------- 1 | // /Reverse Stack Using Recursion 2 | //https://www.codingninjas.com/codestudio/problems/reverse-stack-using-recursion_631875?leftPanelTab=0 3 | import java.util.Stack; 4 | 5 | public class Solution { 6 | public static void insertAtBottom(Stack stack , int bottom){ 7 | if(stack.isEmpty()){ 8 | stack.push(bottom); 9 | return ; 10 | } 11 | int val = stack.pop(); 12 | insertAtBottom(stack, bottom); 13 | stack.push(val); 14 | } 15 | public static void reverseStack(Stack stack) { 16 | if ( stack.isEmpty()){ 17 | return ; 18 | } 19 | 20 | int val = stack.pop(); 21 | reverseStack(stack); 22 | insertAtBottom(stack, val); 23 | } 24 | 25 | } 26 | 27 | -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Reverse Substrings Between Each Pair of Parentheses.java: -------------------------------------------------------------------------------- 1 | //Reverse Substrings Between Each Pair of Parentheses 2 | //https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ 3 | 4 | -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Reversing Queue.java: -------------------------------------------------------------------------------- 1 | //Reversing Queue 2 | //https://www.codingninjas.com/codestudio/problems/reversing-queue_1170046?leftPanelTab=0 3 | 4 | 5 | import java.util.Queue; 6 | 7 | public class Solution { 8 | public static void reverse(Queue < Integer > q) { 9 | // Write your code here. 10 | if ( q.size() == 0 ){ 11 | return ; 12 | } 13 | int val = q.remove(); 14 | reverse(q); 15 | q.add(val); 16 | } 17 | } -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Score of Parentheses.java: -------------------------------------------------------------------------------- 1 | //Score of Parentheses 2 | //https://leetcode.com/problems/score-of-parentheses/ 3 | 4 | class Solution { 5 | public int scoreOfParentheses(String s) { 6 | Stack stk = new Stack<>(); 7 | 8 | for(int i=0; i 0){ 26 | ans += stk.pop(); 27 | } 28 | return ans; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Sort a Stack.java: -------------------------------------------------------------------------------- 1 | //Sort a Stack 2 | //https://www.codingninjas.com/codestudio/problems/sort-a-stack_985275 3 | 4 | 5 | import java.util.*; 6 | public class Solution { 7 | public static void InsertAtSorted( Stack stack , int val){ 8 | if(stack.isEmpty() || stack.peek()<=val){ 9 | stack.push(val); 10 | return ; 11 | } 12 | int top = stack.pop(); 13 | InsertAtSorted(stack , val); 14 | stack.push(top); 15 | } 16 | public static void sortStack(Stack stack) { 17 | 18 | if ( stack.isEmpty()){ 19 | return ; 20 | } 21 | int top =stack.pop(); 22 | sortStack(stack); 23 | InsertAtSorted(stack , top); 24 | } 25 | } -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Sum of Subarray Minimums.java: -------------------------------------------------------------------------------- 1 | //Sum of Subarray Minimums 2 | //https://leetcode.com/problems/sum-of-subarray-minimums/ -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | //Valid Parentheses 2 | //https://leetcode.com/problems/valid-parentheses/ 3 | 4 | class Solution { 5 | public boolean isValid(String s) { 6 | 7 | Stack stack = new Stack<>(); 8 | for (int i = 0 ; i< s.length() ; i++){ 9 | char ch = s.charAt(i); 10 | if ( ch == '('||ch=='['||ch=='{'){ 11 | stack.push(ch); 12 | }else { 13 | 14 | if (stack.isEmpty()) return false ; 15 | 16 | char pk = stack.peek(); 17 | if ( (ch ==')'&&pk=='(')|| (ch ==']' && pk =='[')|| (ch == '}'&&pk=='{')){ 18 | stack.pop(); 19 | }else { 20 | return false ; 21 | } 22 | } 23 | 24 | } 25 | return stack.isEmpty(); 26 | } 27 | 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Valid Parenthesis String.java: -------------------------------------------------------------------------------- 1 | //Valid Parenthesis String 2 | //https://leetcode.com/problems/valid-parenthesis-string/ 3 | 4 | class Solution { 5 | public boolean checkValidString(String s) { 6 | Stack open = new Stack<>(); 7 | Stack star = new Stack<>(); 8 | 9 | for(int i=0; i 0) open.pop(); // opening balance with closing 18 | else if(star.size() > 0) star.pop(); // convert star to opening 19 | else return false; // unbalanced closing 20 | } 21 | } 22 | 23 | if(open.size() > star.size()) 24 | return false; // opening will remain unbalance 25 | 26 | while(open.size() > 0){ 27 | int openIdx = open.pop(); 28 | int closeIdx = star.pop(); 29 | 30 | if(openIdx > closeIdx) return false; 31 | } 32 | 33 | return true; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Level 2/Stack and Queue/Validate Stack Sequences.java: -------------------------------------------------------------------------------- 1 | //Validate Stack Sequences 2 | //https://leetcode.com/problems/validate-stack-sequences/ 3 | class Solution { 4 | public boolean validateStackSequences(int[] pushed, int[] popped) { 5 | Stack stk = new Stack<>(); 6 | int j = 0 ; 7 | for(int i=0 ; i< pushed.length ; i++){ 8 | stk.push(pushed[i]); 9 | while(stk.size()>0 && stk.peek()==popped[j]){ 10 | j++; 11 | stk.pop(); 12 | } 13 | } 14 | return stk.size()==0; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Level 2/Tree/(Morris )Binary Tree Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | //Binary Tree Inorder Traversal 2 | //https://leetcode.com/problems/binary-tree-inorder-traversal/ 3 | 4 | //Moris traversal (Inorder) 5 | import java.util.*; 6 | class Solution { 7 | public List inorderTraversal(TreeNode root) { 8 | List retVal = new ArrayList<>(); 9 | 10 | TreeNode curr = root; 11 | 12 | while(curr != null){ 13 | if(curr.left == null){ 14 | retVal.add(curr.val); 15 | curr = curr.right; 16 | }else { 17 | TreeNode iop = curr.left; 18 | 19 | while(iop.right != null && iop.right != curr){ 20 | iop = iop.right; 21 | } 22 | 23 | if(iop.right == null){ 24 | iop.right = curr; 25 | curr = curr.left; 26 | }else { 27 | 28 | iop.right = null; 29 | retVal.add(curr.val); 30 | curr = curr.right; 31 | } 32 | } 33 | } 34 | return retVal; 35 | } 36 | } -------------------------------------------------------------------------------- /Level 2/Tree/Binary Tree Maximum Path Sum.java: -------------------------------------------------------------------------------- 1 | //Binary Tree Maximum Path Sum 2 | 3 | //https://leetcode.com/problems/binary-tree-maximum-path-sum/ 4 | 5 | /* class Solution { 6 | static int max= Integer.MIN_VALUE ; 7 | public int maxPathSum(TreeNode root) { 8 | max= Integer.MIN_VALUE ; 9 | 10 | maxPathSum1(root); 11 | return max; 12 | 13 | } 14 | public int maxPathSum1(TreeNode root){ 15 | //code here 16 | if(root == null)return 0; 17 | 18 | int left =maxPathSum1(root.left); 19 | int right = maxPathSum1(root.right); 20 | 21 | int left_dash= Math.max(0 , left); 22 | int right_dash = Math.max(0 , right); 23 | 24 | int sumFromLeftToRight = left_dash + root.val + right_dash ; 25 | 26 | if(max list){ 9 | if(root == null)return ; 10 | 11 | inOrder(root.left , list); 12 | list.add(root.data); 13 | inOrder(root.right , list); 14 | } 15 | public static int countPairs(Node root1, Node root2, int x) 16 | { 17 | // Code here 18 | 19 | ArrayList n1 = new ArrayList<>(); 20 | ArrayList n2 = new ArrayList<>(); 21 | 22 | inOrder(root1 , n1); 23 | inOrder(root2 , n2); 24 | 25 | int i = 0 ; 26 | int j = n2.size()-1; 27 | int count = 0 ; 28 | 29 | while(i=0){ 30 | int sum = n1.get(i) + n2.get(j); 31 | 32 | if(sum == x){ 33 | count++; 34 | i++; 35 | j--; 36 | }else if(sum < x){ 37 | i++; 38 | }else { 39 | j--; 40 | } 41 | } 42 | return count; 43 | } 44 | } -------------------------------------------------------------------------------- /Level 2/Tree/Construct tree from Inorder and LevelOrder.java: -------------------------------------------------------------------------------- 1 | //Construct tree from Inorder and LevelOrder 2 | //https://practice.geeksforgeeks.org/problems/construct-tree-from-inorder-and-levelorder/1/ 3 | 4 | 5 | class GfG 6 | { 7 | Node buildTree(int inord[], int level[]) 8 | { 9 | //your code here 10 | HashMap map = new HashMap<>(); 11 | 12 | for( int i = 0 ; i< level.length ; i++){ 13 | map.put(level[i],i); 14 | } 15 | Node root = helper(inord , map , 0 , inord.length -1 ); 16 | return root; 17 | } 18 | 19 | public Node helper(int [] inord , HashMap map, int lo , int hi){ 20 | if(lo > hi)return null; 21 | 22 | int minidx = lo; 23 | for(int i = lo + 1; i<=hi ; i++){ 24 | if(map.get(inord[i]) O(N^2) 6 | //Space ->O(H) 7 | /* class Solution { 8 | public int height(TreeNode root){ 9 | if(root == null) return 0; 10 | return 1 + Math.max(height(root.left), height(root.right)); 11 | } 12 | 13 | public int diameter(TreeNode root) { 14 | if(root == null) return 0; 15 | 16 | int lh = height(root.left); 17 | int rh = height(root.right); 18 | 19 | int ld = diameter(root.left); 20 | int rd = diameter(root.right); 21 | return Math.max(lh + rh + 1, Math.max(ld, rd)); 22 | } 23 | 24 | public int diameterOfBinaryTree(TreeNode root){ 25 | if(root == null) return 0; 26 | return diameter(root) - 1; 27 | } 28 | } 29 | */ -------------------------------------------------------------------------------- /Level 2/Tree/Distribute Coins in Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Distribute Coins in Binary Tree 2 | 3 | //https://leetcode.com/problems/distribute-coins-in-binary-tree/ 4 | 5 | class Solution { 6 | class pair{ 7 | int nodes ; 8 | int coins; 9 | } 10 | int moves = 0 ; 11 | public int distributeCoins(TreeNode root) { 12 | if(root == null)return 0; 13 | helper(root); 14 | return moves; 15 | } 16 | 17 | public pair helper(TreeNode node){ 18 | if(node == null)return new pair(); 19 | pair lp = helper(node.left); 20 | pair rp = helper(node.right); 21 | 22 | pair mp = new pair(); 23 | 24 | mp.nodes = lp.nodes + rp.nodes + 1; 25 | mp.coins = lp.coins + rp.coins + node.val; 26 | 27 | moves += Math.abs(mp.nodes - mp.coins); 28 | return mp; 29 | } 30 | } -------------------------------------------------------------------------------- /Level 2/Tree/Find the Closest Element in BST .java: -------------------------------------------------------------------------------- 1 | //Find the Closest Element in BST 2 | 3 | //https://practice.geeksforgeeks.org/problems/find-the-closest-element-in-bst/1/ 4 | 5 | /* 6 | class Solution 7 | { 8 | //Function to find the least absolute difference between any node 9 | //value of the BST and the given integer. 10 | static int minDiff(Node root, int K) 11 | { 12 | // Write your code here 13 | int min = Integer.MAX_VALUE; 14 | 15 | while(root != null){ 16 | if(root.data < K){ 17 | min = Math.min(min, Math.abs(K - root.data)); 18 | root = root.right; 19 | } 20 | else if(root.data > K){ 21 | min = Math.min(min, Math.abs(root.data - K)); 22 | root = root.left; 23 | } 24 | else{ 25 | return 0; 26 | } 27 | } 28 | return min; 29 | } 30 | } 31 | */ -------------------------------------------------------------------------------- /Level 2/Tree/Flatten Binary Tree to Linked List.java: -------------------------------------------------------------------------------- 1 | //Flatten Binary Tree to Linked List 2 | //https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ 3 | 4 | // First Approach 5 | 6 | class Solution { 7 | 8 | TreeNode prev = null; 9 | public void flatten(TreeNode root) { 10 | if(root == null)return ; 11 | 12 | flatten(root.right); 13 | flatten(root.left); 14 | 15 | root.left = null; 16 | root.right = prev; 17 | prev = root; 18 | 19 | } 20 | } 21 | 22 | 23 | //Second Approach 24 | -------------------------------------------------------------------------------- /Level 2/Tree/Image Multiplication.java: -------------------------------------------------------------------------------- 1 | //Image Multiplication 2 | 3 | 4 | //https://practice.geeksforgeeks.org/problems/image-multiplication0627/1 5 | 6 | 7 | /* class Solution { 8 | long ans = 0 ; 9 | long MOD = 1000000007; 10 | 11 | public long imgMultiply(Node root) 12 | { 13 | // code here 14 | 15 | ans = (root.data * root.data)%MOD; 16 | 17 | helper(root.left , root.right); 18 | return ans; 19 | } 20 | 21 | public void helper(Node n1 , Node n2){ 22 | 23 | if(n1 == null || n2 == null)return ; 24 | 25 | ans = (ans+n1.data * n2.data)%MOD; 26 | 27 | helper(n1.left , n2.right); 28 | helper(n1.right , n2.left); 29 | } 30 | } */ -------------------------------------------------------------------------------- /Level 2/Tree/Longest Even Sum Path.java: -------------------------------------------------------------------------------- 1 | //Longest Even Sum Path 2 | //https://binarysearch.com/problems/Longest-Even-Sum-Path 3 | 4 | -------------------------------------------------------------------------------- /Level 2/Tree/Lowest Common Ancestor in a Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Lowest Common Ancestor in a Binary Tree 2 | //https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1 3 | 4 | 5 | //Using Recursion 6 | 7 | class Solution 8 | { 9 | //Function to return the lowest common ancestor in a Binary Tree. 10 | Node lca(Node root, int n1,int n2) 11 | { 12 | // Your code here 13 | 14 | if(root==null){ return null;} 15 | 16 | if(root.data==n1||root.data==n2){return root;} 17 | 18 | Node leftLca=lca(root.left,n1,n2); 19 | 20 | Node rightLca=lca(root.right,n1,n2); 21 | 22 | if(leftLca!=null&&rightLca!=null){return root;} 23 | 24 | if(leftLca!=null){return leftLca;} 25 | 26 | else{return rightLca;} 27 | } 28 | } -------------------------------------------------------------------------------- /Level 2/Tree/Lowest Common Ancestor of a Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | //Lowest Common Ancestor of a Binary Search Tree 2 | //https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 3 | 4 | 5 | class Solution { 6 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 7 | if(root == null) 8 | return null; 9 | if(root.val > p.val && root.val > q.val) 10 | return lowestCommonAncestor(root.left, p, q); 11 | if(root.val < p.val && root.val < q.val) 12 | return lowestCommonAncestor(root.right, p, q); 13 | return root; 14 | } 15 | } -------------------------------------------------------------------------------- /Level 2/Tree/Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Maximum Depth of Binary Tree 2 | //https://leetcode.com/problems/maximum-depth-of-binary-tree/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | public int maxDepth(TreeNode root) { 21 | if( root == null) return 0 ; 22 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 23 | } 24 | } -------------------------------------------------------------------------------- /Level 2/Tree/Maximum Path Sum between 2 Leaf Nodes.java: -------------------------------------------------------------------------------- 1 | //Maximum Path Sum between 2 Leaf Nodes 2 | //https://practice.geeksforgeeks.org/problems/maximum-path-sum/1/ 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 2/Tree/Median of BST.java: -------------------------------------------------------------------------------- 1 | //Median of BST 2 | //https://practice.geeksforgeeks.org/problems/median-of-bst/1 3 | 4 | 5 | class Tree 6 | { 7 | public static void inOrder(Node root , ArrayListlist){ 8 | if (root == null)return ; 9 | 10 | inOrder(root.left , list ); 11 | list.add(root.data); 12 | inOrder(root.right , list); 13 | } 14 | public static float findMedian(Node root) 15 | { 16 | // code here. 17 | ArrayList n1 = new ArrayList<>(); 18 | 19 | inOrder(root , n1); 20 | 21 | int n= n1.size(); 22 | 23 | if(n%2==0){ 24 | int a = n1.get(n1.size()/2); 25 | int b = n1.get((n1.size()/2) - 1); 26 | 27 | return (float)(a+b)/2; 28 | 29 | }else { 30 | return n1.get(n1.size()/2); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Level 2/Tree/Minimum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Minimum Depth of Binary Tree 2 | //https://leetcode.com/problems/minimum-depth-of-binary-tree/submissions/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | public int minDepth(TreeNode root) { 21 | if( root == null) return 0 ; 22 | 23 | if(root.left == null && root.right == null){ 24 | return 1 ; 25 | } 26 | if ( root.left == null){ 27 | return 1+ minDepth(root.right); 28 | } 29 | if ( root.right == null){ 30 | return 1+ minDepth(root.left); 31 | } 32 | return 1 + Math.min(minDepth(root.left), minDepth(root.right)); 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Level 2/Tree/Number of Turns in Binary Tree.java: -------------------------------------------------------------------------------- 1 | //Number of Turns in Binary Tree 2 | //https://practice.geeksforgeeks.org/problems/number-of-turns-in-binary-tree/1 3 | 4 | 5 | -------------------------------------------------------------------------------- /Level 2/Tree/Path Sum.java: -------------------------------------------------------------------------------- 1 | //Path Sum 2 | //https://leetcode.com/problems/path-sum/ 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode() {} 11 | * TreeNode(int val) { this.val = val; } 12 | * TreeNode(int val, TreeNode left, TreeNode right) { 13 | * this.val = val; 14 | * this.left = left; 15 | * this.right = right; 16 | * } 17 | * } 18 | */ 19 | class Solution { 20 | 21 | 22 | public boolean hasPathSum(TreeNode root, int targetSum) { 23 | if(root == null) return false; 24 | if(root.left == null && root.right == null){ 25 | // Root to Leaf Path Sum = targetSum 26 | return (targetSum == root.val); 27 | } 28 | 29 | if(hasPathSum(root.left, targetSum - root.val) == true) return true; 30 | if(hasPathSum(root.right, targetSum - root.val) == true) return true; 31 | return false; 32 | } 33 | } -------------------------------------------------------------------------------- /Level 2/Tree/Step-By-Step Directions From a Binary Tree Node to Another.java: -------------------------------------------------------------------------------- 1 | //Step-By-Step Directions From a Binary Tree Node to Another 2 | 3 | //https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/ 4 | 5 | -------------------------------------------------------------------------------- /Level 2/Tree/Subarray Sum Equals K.java: -------------------------------------------------------------------------------- 1 | //Subarray Sum Equals K 2 | //https://leetcode.com/problems/subarray-sum-equals-k/#:~:text=Subarray%20Sum%20Equals%20K%20%2D%20LeetCode&text=Given%20an%20array%20of%20integers,whose%20sum%20equals%20to%20k%20.&text=Constraints%3A,.length%20%3C%3D%202%20*%2010 3 | 4 | 5 | class Solution { 6 | public int subarraySum(int[] arr, int k) { 7 | 8 | int ans = 0 ; 9 | HashMap map = new HashMap<>(); 10 | map.put(0,1); 11 | int sum =0; 12 | for(int i = 0 ; i< arr.length ; i++){ 13 | sum +=arr[i]; 14 | if(map.containsKey(sum - k)){ 15 | ans+=map.get(sum-k); 16 | } 17 | map.put(sum , map.getOrDefault(sum , 0)+1); 18 | } 19 | 20 | return ans ; 21 | } 22 | } -------------------------------------------------------------------------------- /Level 2/Tree/Sum Root to Leaf Numbers.java: -------------------------------------------------------------------------------- 1 | //Sum Root to Leaf Numbers 2 | 3 | //https://leetcode.com/problems/sum-root-to-leaf-numbers/ 4 | 5 | 6 | /* 7 | class Solution { 8 | int max = 0; 9 | public int sumNumbers(TreeNode root) { 10 | dfs(root, 0); 11 | return max; 12 | } 13 | 14 | void dfs(TreeNode root, int sum) { 15 | if(root == null) 16 | return; 17 | if(root.left == null && root.right == null) { 18 | max += (sum * 10 + root.val); 19 | return; 20 | } 21 | 22 | sum = sum*10 + root.val; 23 | 24 | dfs(root.left, sum); 25 | dfs(root.right, sum); 26 | } 27 | } */ -------------------------------------------------------------------------------- /Level 2/Tree/k-th smallest element in BST.java: -------------------------------------------------------------------------------- 1 | //k-th smallest element in BST 2 | //geeksforgeeks.org/kth-smallest-element-in-bst-using-o1-extra-space/ 3 | 4 | class Solution { 5 | // Return the Kth smallest element in the given BST 6 | int ans ; 7 | int count ; 8 | public void inorder(Node root , int k){ 9 | if(root == null)return ; 10 | inorder(root.left , k); 11 | count++; 12 | if(count==k){ 13 | ans = root.data; 14 | return; 15 | } 16 | inorder(root.right , k); 17 | } 18 | public int KthSmallestElement(Node root, int K) { 19 | // Write your code here 20 | 21 | count = 0; 22 | ans =-1; 23 | inorder(root , K); 24 | return ans; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Level 2/Tries/Longest Word in Dictionary.java: -------------------------------------------------------------------------------- 1 | //Longest Word in Dictionary 2 | //https://leetcode.com/problems/longest-word-in-dictionary/ -------------------------------------------------------------------------------- /Level 2/Two Pointer Technique/2Sum/Pairs With Given Sum In Two Sorted Matrices.java: -------------------------------------------------------------------------------- 1 | //Pairs With Given Sum In Two Sorted Matrices 2 | //https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/pairs-with-given-sum-in-two-sorted-matrices-official/ojquestion 3 | 4 | // 5 | 6 | 7 | 8 | 9 | /*1. You are given a number N and two sorted matrices(A and B) of N*N dimensions. 10 | 2. You are also given a number X. 11 | 3. You have to find the count of all valid pairs from matrices whose sum is equal to X. 12 | 4. A pair is called valid if one element of the pair is selected from A and the second element is selected from B. 13 | Input Format 14 | A number N 15 | A1 16 | A2.. N*N numbers 17 | B1 18 | B2.. N*N numbers 19 | Output Format 20 | A number representing the count of all valid pairs.*/ -------------------------------------------------------------------------------- /Level 2/Two Pointer Technique/2Sum/Two Sum - Greater than target.java: -------------------------------------------------------------------------------- 1 | //Two Sum - Greater than target 2 | 3 | 4 | public class Solution { 5 | /** 6 | * @param nums: an array of integer 7 | * @param target: An integer 8 | * @return: an integer 9 | */ 10 | public int twoSum2(int[] nums, int target) { 11 | // write your code here 12 | Arrays.sort(nums); 13 | int left = 0 , right = nums.length-1; 14 | int count = 0 ; 15 | while ( left