├── Python ├── threesum.py ├── .gitignore ├── 1929_concat_arr.py ├── firstUniqChar.py ├── containsDuplicate.py ├── 771_jewels_and_stones.py ├── SearchinRotatedSortedArray.py ├── twoSum.py ├── lengthOfLastWord.py ├── searchInsert.py ├── maxSubArray.py ├── 1328_Break_a_Palindrome.py ├── 7. Reverse Integer.py ├── fibonacci │ ├── README.md │ ├── test.py │ └── algorithm.py ├── PlusOne.py ├── JumpGameII.py ├── Interchangeable_rectangles.py ├── reverseint.py ├── 101.SymetricTree.py ├── 129.SumRootToLeafNumber.py ├── MultiplyStrings.py ├── 104.MaximumDepthofBinaryTree.py ├── LastAndFIrstIndex.py ├── Flipping_ab_Image.py ├── isPalindrome.py ├── MedianofTwoSortedArrays.py ├── findClosestNumber.py ├── ReverseWordsInString.py ├── 108.ConvertSortedArraytoBinarySearchTree.py ├── twosum1.py ├── RemoveDuplicatesFromList.py ├── Integer_To_Roman.py ├── 981_Time_Based_Key-Value_Store.py ├── SotingList.py ├── PostOrderTraversalBinaryTree.py ├── Add Two Numbers.py ├── PreOrderTraversalBinaryTree.py ├── Trapping_Rain_Water.py ├── valid parenthesis.py ├── Binraysearch.py ├── Remove_Duplicates_from_Scorted_Array.py ├── Reverse_Integer.py ├── sort_colors.py ├── Longest_Palindromic_Substring.py ├── Regular_Expression_Matching.py ├── Search_Insert_Position.py ├── 53-Maximum-Subarray.py ├── RomantoInteger.py ├── Queue.py ├── String_to_Integer.py ├── ZigZag_Conversion.py ├── validIPAddress.py ├── Binarytree ├── Number_of_Steps_to_Reduce_a_Number_to_Zero.py ├── 121-Best-Time-to-Buy-and-Sell-Stock.py ├── 15-3sum.py ├── 8 Puzzle Game with BFS (Breadth First Search).py ├── matrix.py ├── 8 Queen problem by genetic algorithm.py └── hangman.py ├── Java ├── ZigZag_Conversion.java ├── Longest_Common_Prefix.java ├── Reverse_Integer.java ├── sqrt(x).java ├── Two_Sum.java ├── Container_With_Most_Water.java ├── Roman_to_Integer.java ├── Longest_Palindromic_Substring.java ├── MajorityElement.java ├── Regular_Expression_Matching.java ├── merge-two-sorted-lists.java ├── CheckForValidParenthesisUsingStack.java ├── smallestmissingnumber.java ├── Letter_Combinations_of_a_Phone_Number.java ├── Find_First_And_Last_Element_In_Sorted_Array.java ├── Add2Numbers.java ├── RansomNote.java └── Find_First_and_Last_Position_of_Element_in_Sorted_Array.java ├── Ruby ├── largest_sum.rb ├── sort_hash_by_key_size.rb ├── largest_sum_of_numbers_subarray.rb ├── remove_duplicates_from_array.rb ├── make_one_hash.rb ├── missing_game_number.rb ├── inventing_multiplication.rb ├── palindrome_number.rb ├── count_consective_numbers.rb ├── count_remaining_brackets.rb ├── count_max_letter_in_array.rb ├── jump_tiles.rb └── fizzbuzz.rb ├── JS ├── patternproblem.png ├── Nextvalue_problem.png ├── sumOfTwoNum.js ├── GroupBykey_problemPNG.PNG ├── Fibonacci.js ├── SearchInRotatedSortedArray.js ├── scss_into_css │ ├── package.json │ └── index.js ├── IsPalindrom.js ├── richestCustomerWealth.js ├── palindromeNumber.js ├── findPivotIndex.js ├── ValidPalindrome.js ├── removeDuplicatesFromSortedArray.js ├── TwoSum.js ├── MedianTwoSortedArrays.js ├── RomanToInt.js ├── commonFactor.js ├── patternsolution.js ├── IntToRoman.js ├── ReverseInt.js ├── Restrained3a3b.js ├── phone_shop.js ├── Nextvalue_Recursive.js ├── Groupbykey.js ├── Groupbykey_Reduce.js ├── NextValue_M2.js └── NextValue.js ├── C++ ├── Addtwoints.cpp ├── Number of 1 Bits.cpp ├── 1929. Concatenation of Array.cpp ├── 1480. Running Sum of 1d Array.cpp ├── sort_colors_bhavya1.cpp ├── Fibnoacci-number.cpp ├── Power of Two.cpp ├── Complement of Base 10 Integer.cpp ├── Reverse Integer.cpp ├── Root Equals Sum of Children.cpp ├── problem1920.cpp ├── trapping_rain_water.cpp ├── Maximum Score From Removing Stones.cpp ├── Single Number problem 136.cpp ├── rotate_image.cpp ├── two sum.cpp ├── Star Pattern.cpp ├── ValidAnagram.cpp ├── CoinChange.cpp ├── next_permutation.cpp ├── Problem #338.cpp ├── ValidParentheses.cpp ├── Design-Browser-History.cpp ├── largevaluesineachlevelbst.cpp ├── InvertBinaryTree.cpp ├── PangramString.cpp ├── delete_middle_node_of_a_linked_list.cpp ├── Problem 199 Binary Tree Right Side View.cpp ├── largest-rectangle-in-histogram.cpp ├── Find-the-Winner-of-the-Circular-Game.cpp ├── put_zeros_at_end_of_array.cpp ├── insertion-in-BST.cpp ├── LC_429_N_ary_Tree_Level_Order_Traversal.cpp ├── Binary Search.cpp ├── Kth-smallest-element-in-BST.cpp ├── RemoveElements.cpp ├── sort_colors.cpp ├── PalindromeLinkedList.cpp ├── Merge-Nodes-in-Between-Zeros.cpp ├── Middle_of_LL.cpp ├── kth-smallest-element-in-a-bst problem#230.cpp ├── Deepest-Leaves-Sum.cpp ├── Merge List .cpp ├── Find First and Last Position of Element in Sorted Array.cpp ├── Basic-Calculator-ii.cpp ├── remove_special_characters_from_aaray.cpp └── valid parenthesis Draw Run program.cpp ├── .vscode └── settings.json ├── MYSQL ├── Duplicate_Emails.sql ├── customers-who-never-order.sql └── user_name_and_count_of_invoices.sql ├── sorting_algos ├── insertion_sort.cpp ├── selection_sort.cpp └── bubble_sort.cpp ├── Rust ├── IsPalindrome.rs ├── Fibonacci.rs ├── PowerOfTwo.rs └── TwoSum.rs ├── CONTRIBUTING.md ├── table_of_content.md └── README.md /Python/threesum.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Java/ZigZag_Conversion.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Python/.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | *.py[cod] 3 | *$py.class 4 | -------------------------------------------------------------------------------- /Ruby/largest_sum.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def largest_sum; end 4 | -------------------------------------------------------------------------------- /JS/patternproblem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saadfareed/Leetcode/HEAD/JS/patternproblem.png -------------------------------------------------------------------------------- /JS/Nextvalue_problem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saadfareed/Leetcode/HEAD/JS/Nextvalue_problem.png -------------------------------------------------------------------------------- /JS/sumOfTwoNum.js: -------------------------------------------------------------------------------- 1 | const a = 10; 2 | const b = 3; 3 | let c = 9; 4 | console.log(a + b+ c); 5 | 6 | 7 | -------------------------------------------------------------------------------- /JS/GroupBykey_problemPNG.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saadfareed/Leetcode/HEAD/JS/GroupBykey_problemPNG.PNG -------------------------------------------------------------------------------- /C++/Addtwoints.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sum(int num1, int num2) { 4 | return num1 + num2; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Python/1929_concat_arr.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getConcatenation(self, nums: List[int]) -> List[int]: 3 | return nums + nums 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "deque": "cpp", 4 | "vector": "cpp", 5 | "xstring": "cpp" 6 | } 7 | } -------------------------------------------------------------------------------- /Ruby/sort_hash_by_key_size.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | hash = { "abcd": 4, "abc": 3, "abcdf": 5, "ab": 2 } 4 | puts Hash[hash.sort_by { |k, _| k.size }] 5 | -------------------------------------------------------------------------------- /Ruby/largest_sum_of_numbers_subarray.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Approach: 6 | def largest_sum(arr) 7 | # code here 8 | end 9 | -------------------------------------------------------------------------------- /Python/firstUniqChar.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstUniqChar(self, s: str) -> int: 3 | for i in range(len(s)): 4 | if s.count(s[i]) == 1: 5 | return i 6 | return -1 7 | -------------------------------------------------------------------------------- /MYSQL/Duplicate_Emails.sql: -------------------------------------------------------------------------------- 1 | Write an SQL query to report all the duplicate emails. 2 | Return the result table in any order. 3 | 4 | # Write your MySQL query statement below 5 | SELECT email from person GROUP BY email HAVING count(email)>1; 6 | -------------------------------------------------------------------------------- /Python/containsDuplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | s=set(nums) 4 | if len(s)==len(nums): 5 | return 0 6 | return 1 7 | Solution.containsDuplicate(Solution, [1,2,3,1]) 8 | -------------------------------------------------------------------------------- /Ruby/remove_duplicates_from_array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Areeb Alam 4 | # Username: AreebAlam99 5 | # Approach: Just used uniq to remove duplicates and returned count :p. 6 | 7 | def remove_duplicates(nums) 8 | nums.uniq! 9 | nums.count 10 | end 11 | -------------------------------------------------------------------------------- /Ruby/make_one_hash.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def make_one_hash(arr) 4 | hash = {} 5 | arr.each do |ele| 6 | hash.merge!(ele) 7 | end 8 | hash 9 | end 10 | 11 | arr = [{ a: 3, b: 2, c: 3, d: 4 }, { e: 3, f: 2 }, { g: 2, h: 3 }] 12 | puts make_one_hash(arr) 13 | -------------------------------------------------------------------------------- /Ruby/missing_game_number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Question: find missing number in array 6 | def missing_game_number(arr) 7 | (1..10).each do |num| 8 | arr << num if arr.exclude?(num) 9 | end 10 | arr.sort 11 | end 12 | -------------------------------------------------------------------------------- /JS/Fibonacci.js: -------------------------------------------------------------------------------- 1 | const number = parseInt(prompt('Enter the number of terms: ')); 2 | let n1 = 0, n2 = 1, nextTerm; 3 | 4 | console.log('Fibonacci Series:'); 5 | 6 | for (let i = 1; i <= number; i++) { 7 | console.log(n1); 8 | nextTerm = n1 + n2; 9 | n1 = n2; 10 | n2 = nextTerm; 11 | } -------------------------------------------------------------------------------- /Python/771_jewels_and_stones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, jewels: str, stones: str) -> int: 3 | res = 0 4 | distinct_jewels = [*jewels] 5 | for stone in stones: 6 | if stone in distinct_jewels: 7 | res += 1 8 | return res 9 | -------------------------------------------------------------------------------- /JS/SearchInRotatedSortedArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | var search = function (nums, target) { 7 | for (let i = 0; i < nums.length; i++) { 8 | if (nums[i] === target) 9 | return i 10 | } 11 | 12 | return -1 13 | }; -------------------------------------------------------------------------------- /MYSQL/customers-who-never-order.sql: -------------------------------------------------------------------------------- 1 | Write an SQL query to report all customers who never order anything. 2 | 3 | Return the result table in any order. 4 | # Write your MySQL query statement below 5 | select customers.name as 'Customers' from customers where customers.id not in (select customerid from orders) 6 | -------------------------------------------------------------------------------- /C++/Number of 1 Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | 5 | int count=0; 6 | while(n!=0){ 7 | if(n&1){ 8 | count++; 9 | } 10 | n=n>>1; 11 | } 12 | return count; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Ruby/inventing_multiplication.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Question: do multiplication without * operator 6 | def inventing_multiplication(num1, num2) 7 | res = 0 8 | num2.times.each do |_num| 9 | res += num1 10 | end 11 | res 12 | end 13 | -------------------------------------------------------------------------------- /Python/SearchinRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | # Name: Muhammd Abdullah 2 | 3 | # Username: muhammadabdullah660 4 | 5 | # Approach: Simply find the index of target. If not found then return -1. 6 | class Solution(object): 7 | def search(self, nums, target): 8 | return nums.index(target) if nums.count(target) > 0 else -1 9 | -------------------------------------------------------------------------------- /Python/twoSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | for i in range(len(nums)): 4 | for j in range(i+1, len(nums)): 5 | if nums[i] + nums[j] == target: 6 | return([i, j]) 7 | Solution.twoSum(Solution, [2, 7, 11, 15], 9) 8 | -------------------------------------------------------------------------------- /Python/lengthOfLastWord.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | a=s.split(" ") 4 | #print(a) 5 | count=0 6 | for i in a: 7 | if(i!=''): 8 | i=str(i) 9 | #print(len(i)) 10 | count=len(i) 11 | return(count) 12 | -------------------------------------------------------------------------------- /Ruby/palindrome_number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Areeb Alam 4 | # Username: AreebAlam99 5 | # Approach: Converted the number into an array of digits and checked if it was equal to its reverse or not. 6 | 7 | def palindrome?(num) 8 | return false if num.negative? 9 | 10 | num.digits == num.digits.reverse 11 | end 12 | -------------------------------------------------------------------------------- /Python/searchInsert.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | j=len(nums) 4 | #print(j) 5 | for i in nums: 6 | if(i int: 3 | if max(nums)<0: 4 | return max(nums) 5 | 6 | curr_sum ,max_sum=0,0 7 | for num in nums: 8 | curr_sum = max(0, curr_sum + num) 9 | max_sum = max(curr_sum, max_sum) 10 | return max_sum 11 | -------------------------------------------------------------------------------- /Java/Longest_Common_Prefix.java: -------------------------------------------------------------------------------- 1 | public class Longest_Common_Prefix { 2 | String r=""; 3 | int n=strs.length; 4 | Arrays.sort(strs); 5 | String s=strs[0]; 6 | String h=strs[n-1]; 7 | for(int i =0;i getConcatenation(vector& nums) { 4 | vectornumber; 5 | 6 | for(auto i:nums) 7 | number.push_back(i); 8 | for(auto i:nums) 9 | number.push_back(i); 10 | return number; 11 | 12 | 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/1480. Running Sum of 1d Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector runningSum(vector& nums) 4 | { 5 | vectorrunsum; 6 | int sum = 1; 7 | 8 | for(auto i:nums) 9 | { 10 | 11 | sum = sum+i; 12 | runsum.push_back(sum); 13 | } 14 | return runsum; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /sorting_algos/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | void insertion_sort(int arr[],int size) 2 | { 3 | for(int i = 1; i < size; i++) 4 | { 5 | int key = arr[i]; 6 | int j = i - 1; 7 | 8 | while( j >= 0 && arr[j] > key) 9 | { 10 | arr[j + 1] = arr[j]; 11 | j = j - 1; 12 | } 13 | arr[j + 1] = key; 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /Java/Reverse_Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | if (x == 0) return 0; 4 | long res = 0; 5 | while (x != 0) { 6 | res = res * 10 + x % 10; 7 | if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) 8 | return 0; 9 | x /= 10; 10 | } 11 | return (int) res; 12 | } 13 | } -------------------------------------------------------------------------------- /Python/1328_Break_a_Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def breakPalindrome(self, palindrome: str) -> str: 3 | n = len(palindrome) 4 | if n == 1: return "" 5 | 6 | for i in range(n//2): 7 | if palindrome [i] != 'a': 8 | return palindrome[:i] + 'a' + palindrome[i+1:] 9 | 10 | return palindrome[:n-1] + 'b' 11 | -------------------------------------------------------------------------------- /Python/7. Reverse Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | if x > 0: 4 | ans = int(str(x)[::-1]) 5 | else: 6 | ans = int(str(x * -1)[::-1]) * -1 7 | 8 | mi = 2 ** 31 * (-1) 9 | ma = 2 ** 31 - 1 10 | 11 | if ans > ma or ans < mi: 12 | return 0 13 | return ans 14 | -------------------------------------------------------------------------------- /C++/sort_colors_bhavya1.cpp: -------------------------------------------------------------------------------- 1 | // #bhavya Agrawal 2 | // #Leetcode - bhavyacodec 3 | // #codeforces - coder_bhavya 4 | class Solution { 5 | public: 6 | void sortColors(vector& nums) { 7 | int n=nums.size(); 8 | for(int i=0;inums[j+1]) swap(nums[j],nums[j+1]); 11 | } 12 | } 13 | } 14 | }; -------------------------------------------------------------------------------- /JS/scss_into_css/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scsstocss", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "globby": "^11.0.3" 14 | } 15 | } -------------------------------------------------------------------------------- /Java/sqrt(x).java: -------------------------------------------------------------------------------- 1 | /* 2 | Name: Mr. Aqib Chattha 3 | 4 | Username: AqibChattha 5 | 6 | Approach: find all the possible numbers whose square is less 7 | or equal to the number then return the largest number. 8 | */ 9 | 10 | class Solution { 11 | public int mySqrt(int x) { 12 | long i = 0; 13 | while(i*i <= x) 14 | i++; 15 | return (int)i-1; 16 | } 17 | } -------------------------------------------------------------------------------- /Ruby/count_consective_numbers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Approach: make hash count as value and number as key then find max value return its key 6 | def count_consective_numbers(arr) 7 | hash_one = {} 8 | arr.each do |val| 9 | hash_one[val] = arr.count(val) 10 | end 11 | hash_one.max_by { |_k, v| v }.first 12 | end 13 | -------------------------------------------------------------------------------- /Python/fibonacci/README.md: -------------------------------------------------------------------------------- 1 | ### Fibonacci 2 | Fibonacci, also known as Leonardo Bonacci, Leonardo of Pisa, or Leonardo Bigollo Pisano, was an Italian mathematician from the Republic of Pisa, considered to be "the most talented Western mathematician of the Middle Ages". 3 | 4 | ### Running 5 | ```sh 6 | $ python algorithm.py 7 | ``` 8 | 9 | ### Testing 10 | ```sh 11 | $ python -m unittest 12 | ``` 13 | -------------------------------------------------------------------------------- /C++/Fibnoacci-number.cpp: -------------------------------------------------------------------------------- 1 | // Name: Hussain Iftikhar 2 | // Username: hussainiftikhar5242 3 | // Approach: Find the fibnoacci-number using recurssion. 4 | class Solution { 5 | public: 6 | int fib(int n) { 7 | if(n>1) 8 | { 9 | return fib(n-1)+fib(n-2); 10 | } 11 | else 12 | { 13 | return n; 14 | } 15 | return 0; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /JS/IsPalindrom.js: -------------------------------------------------------------------------------- 1 | //Name: Raza Mohayyuddin 2 | 3 | //Username: RazaKhan9639 4 | 5 | //Approach:First we use toString method to convert integer to string Then we Convert the string in array by split("") method then reverse array Then join() to merge array. Than compare with original string and return. 6 | 7 | var isPalindrome = function (x) { 8 | return x == x.toString().split("").reverse().join(""); 9 | }; 10 | -------------------------------------------------------------------------------- /Ruby/count_remaining_brackets.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Approach: deduct open from close bracket to get remaining brackets 6 | def count_remaining_brackets(str) 7 | open_brackets = str.count('(') 8 | close_brackets = str.count(')') 9 | remaining = open_brackets - close_brackets 10 | remaining.negative? ? remaining.abs : remaining 11 | end 12 | -------------------------------------------------------------------------------- /C++/Power of Two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | 5 | 6 | 7 | for(int i=0;i<=30;i++){ 8 | int power= pow(2,i); 9 | 10 | if(power==n){ 11 | 12 | return true;} 13 | 14 | } 15 | 16 | 17 | 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Rust/IsPalindrome.rs: -------------------------------------------------------------------------------- 1 | //Name: Muhammad Yousaf 2 | 3 | //Username: yousafsabir 4 | 5 | //Approach: function compares the word with its reversed counterpart and returns boolean based on comparison 6 | 7 | fn main() { 8 | let word: String =String::from("abcaba"); 9 | println!("{}", is_palindrome(word)) 10 | } 11 | 12 | fn is_palindrome(word: String) -> bool { 13 | word == word.chars().rev().collect::() 14 | } -------------------------------------------------------------------------------- /Python/PlusOne.py: -------------------------------------------------------------------------------- 1 | # Name: Muhammd Abdullah 2 | 3 | # Username: muhammadabdullah660 4 | 5 | # Approach: Convert input list to integer using map function and add 1 to it. Then convert it back to list using list function 6 | 7 | class Solution(object): 8 | def plusOne(self, digits): 9 | num = int("".join(list(map(str, digits))))+1 10 | stringify = str(num) 11 | res = list(stringify) 12 | return(res) 13 | -------------------------------------------------------------------------------- /sorting_algos/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | void selection_sort(int arr[],int size) 2 | { 3 | int min_idx; 4 | for(int i = 0; i < size - 1; i++) 5 | { 6 | min_idx = i; 7 | for(int j = i+1; j < size; j++) 8 | { 9 | if(arr[j] < arr[min_idx]) 10 | min_idx = j; 11 | } 12 | int temp = arr[min_idx]; 13 | arr[min_idx] = arr[i]; 14 | arr[i] = temp; 15 | } 16 | } -------------------------------------------------------------------------------- /Python/JumpGameII.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | maxIndex = [10000] * len(nums) 4 | maxIndex[0] = 0 5 | for i in range(0,len(nums)-1): 6 | for j in range(i,i+(nums[i])+1): 7 | if j< len(nums) and maxIndex[j]>maxIndex[i]+1: 8 | maxIndex[j] = maxIndex[i]+1 9 | #print(maxIndex) 10 | return maxIndex[len(maxIndex)-1] 11 | -------------------------------------------------------------------------------- /Python/Interchangeable_rectangles.py: -------------------------------------------------------------------------------- 1 | from fractions import * 2 | from collections import Counter 3 | 4 | class Solution: 5 | def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: 6 | cnt = Counter() 7 | for w, h in rectangles: 8 | cnt[Fraction(w, h)] += 1 9 | ans = 0 10 | for value in cnt.values(): 11 | ans += value * (value - 1) // 2 12 | return ans -------------------------------------------------------------------------------- /Python/reverseint.py: -------------------------------------------------------------------------------- 1 | num=-12 2 | flag=True 3 | if(num<0): 4 | flag=False 5 | num=-num 6 | #print(num) 7 | l=len(str(num)) 8 | z=l 9 | answer=0 10 | #print(l) 11 | for i in range(0,l): 12 | result=num%(10**(i+1)) 13 | num=num-result 14 | #print(result) 15 | z=z-1 16 | powa=10**z 17 | final=(result*(powa))/(10**(i)) 18 | answer=final+answer 19 | if(flag==False): 20 | answer=-answer 21 | print(int(answer)) 22 | -------------------------------------------------------------------------------- /C++/Complement of Base 10 Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bitwiseComplement(int n) { 4 | 5 | int m=n; 6 | int mask=0; 7 | 8 | if(n==0){ 9 | return 1; 10 | } 11 | while(m!=0){ 12 | 13 | mask=(mask << 1)| 1; 14 | m=m>>1; 15 | 16 | } 17 | int ans= (~n)& mask; 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Python/101.SymetricTree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSymmetric(self, root: Optional[TreeNode]) -> bool: 3 | def isMirror(left, right): 4 | if left == None and right == None: 5 | return True 6 | if left == None or right == None: 7 | return False 8 | return (left.val == right.val) and isMirror(left.right, right.left) and isMirror(left.left, right.right) 9 | return isMirror(root, root) -------------------------------------------------------------------------------- /Python/129.SumRootToLeafNumber.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def sumNumbers(self, root: Optional[TreeNode]) -> int: 4 | def dfs(node, current): 5 | if node == None: 6 | return 0 7 | current = current * 10 + node.val 8 | if node.left == None and node.right == None: 9 | return current 10 | return dfs(node.left, current) + dfs(node.right, current) 11 | return dfs(root, 0) -------------------------------------------------------------------------------- /C++/Reverse Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | 5 | int ans=0; 6 | while(x!=0){ 7 | int remainder=x%10; 8 | 9 | if((ans > INT_MAX/10) || (ans < INT_MIN/10)){ 10 | 11 | return 0; 12 | } 13 | ans=(ans*10)+remainder; 14 | x=x/10; 15 | 16 | 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /JS/richestCustomerWealth.js: -------------------------------------------------------------------------------- 1 | 2 | const maximumWealth = function(accounts) { 3 | let max = 0; 4 | for(const customer of accounts) 5 | { 6 | let sum = customer.reduce((a,b) => a+b ,0); 7 | if(sum > max) 8 | { 9 | max = sum; 10 | } 11 | } 12 | 13 | return max; 14 | }; 15 | 16 | /* Test Case */ 17 | const accounts = [[1,2,3],[3,2,1]]; 18 | console.log(maximumWealth(accounts)) 19 | -------------------------------------------------------------------------------- /Python/MultiplyStrings.py: -------------------------------------------------------------------------------- 1 | #Name: Abdullah Yaqub 2 | #Username: AbdullahYaqub72 3 | #Approach: Making Strings Integers and then multiplying them 4 | 5 | 6 | class Solution(object): 7 | def multiply(self, num1, num2): 8 | """ 9 | :type num1: str 10 | :type num2: str 11 | :rtype: str 12 | """ 13 | mul_num1=int(num1) 14 | mul_num2=int(num2) 15 | res=mul_num1*mul_num2 16 | string_res=str(res) 17 | return string_res -------------------------------------------------------------------------------- /Python/104.MaximumDepthofBinaryTree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def maxDepth(self, root: Optional[TreeNode]) -> int: 9 | if root == None: 10 | return 0 11 | else: 12 | return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 13 | -------------------------------------------------------------------------------- /Python/LastAndFIrstIndex.py: -------------------------------------------------------------------------------- 1 | # Name: Muhammd Abdullah 2 | 3 | # Username: muhammadabdullah660 4 | 5 | # Approach: Simply find the index of target. If not found then return -1. then find index in reversed array for end index 6 | class Solution(object): 7 | def searchRange(self, nums, target): 8 | start = nums.index(target) if nums.count(target) > 0 else -1 9 | end = len(nums) - nums[::-1].index(target) - \ 10 | 1 if nums.count(target) > 0 else -1 11 | return [start, end] 12 | -------------------------------------------------------------------------------- /C++/Root Equals Sum of Children.cpp: -------------------------------------------------------------------------------- 1 | // Name: Hussain Iftikhar 2 | // UserName: hussainiftikhar5242 3 | // Approach: first sum the left and right node of tree and then check the parent node is equal to the Parent node 4 | class Solution { 5 | public: 6 | bool checkTree(TreeNode* root) { 7 | int sum=0; 8 | sum = root->left->val + root->right->val; 9 | if(sum == root->val) 10 | { 11 | return true; 12 | } 13 | return false; 14 | 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Ruby/count_max_letter_in_array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Approach: take hash and initialize it with zero run loop over string 6 | # increase count every time in hash key which is character 7 | # then use max_by built in method to find letter with max count 8 | def find_max_frequency_character(str) 9 | hash = Hash.new(0) 10 | str.each_char do |ch| 11 | hash[ch] += 1 12 | end 13 | hash.max_by { |_, v| v }.first 14 | end 15 | -------------------------------------------------------------------------------- /Rust/Fibonacci.rs: -------------------------------------------------------------------------------- 1 | // Name: Muhammad Yousaf 2 | // Username: yousafsabir 3 | // Approach: function loops over and perform arithmatec operations 4 | fn main() { 5 | let number: i32 = 4; 6 | fibonacci_series(number); 7 | } 8 | fn fibonacci_series(number: i32) { 9 | let mut sum: i32; 10 | let mut last: i32 = 0; 11 | let mut current: i32 = 1; 12 | for _ in 0..number { 13 | println!("{}", last); 14 | sum = last + current; 15 | last = current; 16 | current = sum 17 | } 18 | } -------------------------------------------------------------------------------- /Java/Two_Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // example in leetcode book 3 | public int[] twoSum(int[] nums, int target) { 4 | Map map = new HashMap<>(); 5 | for (int i = 0; i < nums.length; i++) { 6 | int x = nums[i]; 7 | if (map.containsKey(target - x)) { 8 | return new int[]{map.get(target - x), i}; 9 | } 10 | map.put(x, i); 11 | } 12 | throw new IllegalArgumentException("No two sum solution"); 13 | } 14 | } -------------------------------------------------------------------------------- /Ruby/jump_tiles.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Question: jump n times where n is current number in array and find did you able to reach to end of array 6 | # Approach: in loop added only those elements on which pointer value is same 7 | # then compare pointer value with size of array 8 | def jump_tiles(arr) 9 | pointer = 0 10 | arr.each_with_index do |_, idx| 11 | pointer += arr[idx] if pointer == idx 12 | end 13 | pointer >= arr.length - 1 14 | end 15 | -------------------------------------------------------------------------------- /Python/Flipping_ab_Image.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def flipAndInvertImage(self, A): 3 | for row in A: 4 | for i in xrange((len(row) + 1) / 2): 5 | """ 6 | In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i] 7 | helps us find the i-th value of the row, counting from the right. 8 | """ 9 | row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 10 | return A 11 | # return [[1 ^ i for i in row[::-1]] for row in A] 12 | -------------------------------------------------------------------------------- /Java/Container_With_Most_Water.java: -------------------------------------------------------------------------------- 1 | public class Container_With_Most_Water { 2 | int maximumArea = Integer.MIN_VALUE; 3 | int left = 0; 4 | int right = height.length - 1; 5 | while (left < right) { 6 | int shorterLine = Math.min(height[left], height[right]); 7 | maximumArea = Math.max(maximumArea, shorterLine * (right - left)); 8 | if (height[left] < height[right]) { 9 | left++; 10 | } else { 11 | right--; 12 | } 13 | } 14 | return maximumArea; 15 | } 16 | -------------------------------------------------------------------------------- /Python/isPalindrome.py: -------------------------------------------------------------------------------- 1 | #Name: Abdullah Yaqub 2 | #Username: AbdullahYaqub72 3 | #Approach: Comparing arrays while traversing in forward and reverse order 4 | 5 | class Solution: 6 | def isPalindrome(self, num: int) -> bool: 7 | isPalind=True 8 | y=str(num) 9 | for i in range(len(y)-1): 10 | ind=len(y)-i-1 11 | if(y[i]!=y[ind]): 12 | isPalind=False 13 | break 14 | else: 15 | isPalind=True 16 | 17 | return isPalind 18 | -------------------------------------------------------------------------------- /Ruby/fizzbuzz.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Name: Shoaib Sabir 4 | # Username: Shoaib019 5 | # Approach: loop runs number times for each element and checks for appropriate conditions 6 | def fizz_buzz(number) 7 | arr = [] 8 | (1..number).each do |num| 9 | arr << if num.modulo(3).zero? && num.modulo(5).zero? then 'FizzBuzz' 10 | elsif num.modulo(3).zero? then 'Fizz' 11 | elsif num.modulo(5).zero? then 'Buzz' 12 | else 13 | num.to_s 14 | end 15 | end 16 | arr 17 | end 18 | -------------------------------------------------------------------------------- /JS/palindromeNumber.js: -------------------------------------------------------------------------------- 1 | 2 | const isPalindromeNumber = function (num) { 3 | num = String(num); 4 | const half = num.length; 5 | for (let i = 0; i < half; i++) { 6 | if (num[i] !== num[num.length - 1 - i]) { 7 | return false; 8 | } 9 | } 10 | return true; 11 | }; 12 | 13 | /* Test Case */ 14 | const numberToTest = [121, 34543, 'KSKS', 131, 489466784 ]; 15 | for(let i = 0 ; i < numberToTest.length ; i++){ 16 | console.log(`Testing ${numberToTest[i]} is Palindrome Number : ${isPalindromeNumber(numberToTest[i])}`); 17 | } 18 | 19 | -------------------------------------------------------------------------------- /C++/problem1920.cpp: -------------------------------------------------------------------------------- 1 | // 1920. Build Array from Permutation 2 | // Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. 3 | 4 | // A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). 5 | class Solution { 6 | public: 7 | vector buildArray(vector& nums) { 8 | vectorv; 9 | for(auto i:nums) 10 | { 11 | v.push_back(nums[i]); 12 | } 13 | return v;} 14 | }; 15 | -------------------------------------------------------------------------------- /Python/MedianofTwoSortedArrays.py: -------------------------------------------------------------------------------- 1 | # Name: Muhammd Abdullah 2 | 3 | # Username: muhammadabdullah660 4 | 5 | # Approach: Simply add both arrays and sort the bigger array and return the middle element if length is odd else add n/2 and n/2 - 1 elements. 6 | class Solution(object): 7 | def findMedianSortedArrays(self, nums1, nums2): 8 | nums3 = nums1+nums2 9 | nums3.sort() 10 | if len(nums3) % 2 == 0: 11 | return (float(nums3[(len(nums3)/2)]+nums3[(len(nums3)/2)-1]))/2 12 | else: 13 | return nums3[int(len(nums3)/2)] 14 | -------------------------------------------------------------------------------- /Python/findClosestNumber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findClosestNumber(self, nums: List[int]) -> int: 3 | result=max(nums) 4 | result1=min(nums) 5 | for i in nums: 6 | if(i==0): 7 | result=0 8 | break 9 | else: 10 | if(i<0 and result10 and result>i): 13 | result=i 14 | if (result<=-result1): 15 | return(result) 16 | else: 17 | return(result1) 18 | -------------------------------------------------------------------------------- /Python/ReverseWordsInString.py: -------------------------------------------------------------------------------- 1 | #Name: Abdullah Yaqub 2 | #Username: AbdullahYaqub72 3 | #Approach: Splits the string and getting it in reverse order using lists. 4 | 5 | class Solution(object): 6 | def reverseWords(self, s): 7 | """ 8 | :type s: str 9 | :rtype: str 10 | """ 11 | list1=[] 12 | splitted=s.split() 13 | ste="" 14 | rev="" 15 | for i in s.split(): 16 | list1.append(i) 17 | list2=list1[::-1] 18 | for i in list2: 19 | rev=rev+" "+i+"" 20 | rev=rev[1:] 21 | return rev -------------------------------------------------------------------------------- /C++/trapping_rain_water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 3 | */ 4 | class Solution { 5 | public: 6 | int trap(vector& height) { 7 | int l=0; 8 | int r=height.size()-1; 9 | int level=0; 10 | int water=0; 11 | while(l bool { 15 | if (num & (num - 1)) != 0 { 16 | return false 17 | } else { 18 | return true 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /C++/Maximum Score From Removing Stones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumScore(int a, int b, int c) { 4 | priority_queue pq; 5 | int ans=0; 6 | pq.push(a); 7 | pq.push(b); 8 | pq.push(c); 9 | while(pq.size()>1){ 10 | int max1=pq.top(); 11 | pq.pop(); 12 | int max2=pq.top(); 13 | pq.pop(); 14 | max1--; 15 | max2--; 16 | if(max1>0)pq.push(max1); 17 | if(max2>0)pq.push(max2); 18 | ans++; 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Python/fibonacci/test.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase, main 2 | from algorithm import Fibo 3 | 4 | 5 | class FiboTestCase(TestCase): 6 | 7 | def setUp(self): 8 | self.fibo = Fibo() 9 | 10 | def test_instance(self): 11 | self.assertIsInstance(self.fibo, Fibo) 12 | 13 | def test_10_series(self): 14 | series = self.fibo.generate(10) 15 | self.assertEqual(sum(series), 88) 16 | 17 | def test_static_method(self): 18 | static_series = Fibo.generate(15) 19 | instance_series = self.fibo.generate(15) 20 | 21 | self.assertEqual(static_series, instance_series) 22 | 23 | 24 | if __name__ == '__main__': main() 25 | -------------------------------------------------------------------------------- /C++/Single Number problem 136.cpp: -------------------------------------------------------------------------------- 1 | //Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 2 | 3 | //You must implement a solution with a linear runtime complexity and use only constant extra space. 4 | 5 | 6 | class Solution { 7 | public: 8 | int singleNumber(vector& nums) { 9 | mapm; 10 | for(auto i: nums) 11 | { 12 | m[i]++; 13 | } 14 | int x; 15 | for(auto i:m) 16 | { 17 | if(i.second==1) 18 | x= i.first; 19 | } 20 | return x; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/rotate_image.cpp: -------------------------------------------------------------------------------- 1 | #You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 2 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. 3 | DO NOT allocate another 2D matrix and do the rotation. 4 | 5 | class Solution { 6 | public: 7 | void rotate(vector>& matrix) { 8 | reverse(matrix.begin(),matrix.end()); 9 | for(int i=0;i pre + cur,0); 13 | const sum2 = p2.reduce((pre,cur) => pre + cur,0); 14 | if(sum1 === sum2) return i; 15 | } 16 | return -1; 17 | }; 18 | 19 | /* Test Case */ 20 | const nums = [1,7,3,6,5,6]; 21 | console.log(pivotIndex(nums)) 22 | -------------------------------------------------------------------------------- /Python/108.ConvertSortedArraytoBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 9 | if len(nums) == 0: 10 | return None 11 | if len(nums) == 1: 12 | return TreeNode(nums[0]) 13 | mid = len(nums) // 2 14 | return TreeNode(nums[mid], self.sortedArrayToBST(nums[:mid]), self.sortedArrayToBST(nums[mid+1:])) 15 | -------------------------------------------------------------------------------- /Java/Roman_to_Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | int[] arr = new int['A' + 26]; 4 | arr['I'] = 1; 5 | arr['V'] = 5; 6 | arr['X'] = 10; 7 | arr['L'] = 50; 8 | arr['C'] = 100; 9 | arr['D'] = 500; 10 | arr['M'] = 1000; 11 | 12 | int result = 0; 13 | int prev = 0; 14 | 15 | for (int i = s.length() - 1; i >= 0; i--) { 16 | int current = arr[s.charAt(i)]; 17 | result += prev > current ? -current : current; 18 | prev = current; 19 | } 20 | 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /JS/ValidPalindrome.js: -------------------------------------------------------------------------------- 1 | // Name: Shoaib Sabir 2 | // Username: Shoaib019 3 | // Approach: first regex will remove whitespace & special characters 4 | // then convert string to lover case run loop and start 5 | // matching element by element from beginning and end 6 | // whenever find not match return false else true 7 | var isPalindrome = function(s) { 8 | 9 | s = s.replaceAll(/\s|[^\w\s]|_/g,'').toLowerCase(); 10 | if(s == "") return true; 11 | for(let i = 0; i < s.length; i ++){ 12 | if(s[i] != s[s.length - i - 1]){ 13 | return false; 14 | } 15 | } 16 | return true; 17 | }; -------------------------------------------------------------------------------- /C++/two sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | //TWO SUM Problem 1ss Solution { 3 | public: 4 | vector twoSum(vector& nums, int target) { 5 | vector sol; 6 | for(int i=0;i generates a series of 10 traily numbers 10 | 11 | or 12 | 13 | Fibo.generate(10) 14 | """ 15 | 16 | @staticmethod 17 | def generate(length: int=5): 18 | """ 19 | generates the fibonacci series 20 | """ 21 | 22 | series = [0, 1] 23 | 24 | if length > 2: 25 | for i in range(2, length): 26 | nextElement = series[i-1] + series[i-2] 27 | series.append(nextElement) 28 | 29 | return series 30 | 31 | 32 | if __name__ == '__main__': 33 | print(Fibo.generate()) 34 | -------------------------------------------------------------------------------- /Python/twosum1.py: -------------------------------------------------------------------------------- 1 | # Name: Ayesha Aslam 2 | 3 | # Username: ch-ayesha 4 | 5 | # Approach: this approach will gives O(n) time complexity and O(n) space complexity 6 | class Solution(object): 7 | def twoSum(self, nums, target): 8 | """ 9 | :type nums: List[int] 10 | :type target: int 11 | :rtype: List[int] 12 | """ 13 | dic={} 14 | for i in range(len(nums)): 15 | otherpair=target-nums[i] 16 | if otherpair in dic: 17 | return [dic[otherpair],i] 18 | dic[nums[i]]=i 19 | if __name__ == '__main__': 20 | s = Solution() 21 | print (s.twoSum( [2, 7, 11, 15], 9)) 22 | 23 | 24 | -------------------------------------------------------------------------------- /C++/Star Pattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int rows, i, j, k; 6 | cout << "Welcome to my program!\n\n"; 7 | cout << "Please enter the number of rows you want. The rows must be in an even number: "; 8 | cin >> rows; 9 | cout << endl; 10 | for (i=1; i<=rows; i++) 11 | { 12 | for (j=1; j<=i; j++) 13 | { 14 | cout << "* "; 15 | } 16 | cout << endl; 17 | } 18 | for (i=1; i<=rows; i++) 19 | { 20 | for (k=i; k<=rows; k++) 21 | { 22 | cout << "* "; 23 | } 24 | cout << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /C++/ValidAnagram.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name: Muhammad Abdullah Uppal 3 | * Username: Abdullah-Uppal 4 | * Approach: Indirectly keeping count of the letters 5 | **/ 6 | class Solution { 7 | public: 8 | bool isAnagram(string s, string t) { 9 | if (s.length() != t.length()) return false; 10 | int* count = new int[26]; 11 | std::memset(count, 0, sizeof(int) * 26); 12 | for (int i = 0; i coins,int amount) 7 | { 8 | memset(dp,-1,sizeof(dp)); 9 | int c =coinChange1(coins,amount); 10 | if (c >= INT_MAX) 11 | return -1; 12 | else 13 | return c; 14 | } 15 | 16 | int coinChange1(vector coins,int amount) 17 | { 18 | if (amount == 0) return 0; 19 | int c = INT_MAX; 20 | if (dp[amount] != -1) return dp[amount]; 21 | for (int i = 0; i < coins.size(); i++) 22 | { 23 | if (amount - coins[i] >= 0) 24 | c = min((ll)c, (ll)coinChange1(coins,amount - coins[i])+1); 25 | } 26 | return dp[amount] = c; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/next_permutation.cpp: -------------------------------------------------------------------------------- 1 | #A permutation of an array of integers is an arrangement of its members into a sequence or linear order. 2 | class Solution { 3 | public: 4 | void nextPermutation(vector& nums) { 5 | int n = nums.size(), k, l; 6 | for (k = n - 2; k >= 0; k--) { 7 | if (nums[k] < nums[k + 1]) { 8 | break; 9 | } 10 | } 11 | if (k < 0) { 12 | reverse(nums.begin(), nums.end()); 13 | } else { 14 | for (l = n - 1; l > k; l--) { 15 | if (nums[l] > nums[k]) { 16 | break; 17 | } 18 | } 19 | swap(nums[k], nums[l]); 20 | reverse(nums.begin() + k + 1, nums.end()); 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /C++/Problem #338.cpp: -------------------------------------------------------------------------------- 1 | 338. Counting Bits 2 | 3 | Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 4 | 5 | class Solution { 6 | public: 7 | 8 | 9 | int count(int n){ 10 | int c=0; 11 | 12 | while(n>0) 13 | { 14 | int r=n%2; 15 | 16 | if(r==1)c++; 17 | n=n/2; 18 | 19 | } 20 | return c; 21 | } 22 | 23 | 24 | vector countBits(int n) { 25 | vectorarr(n+1); 26 | 27 | 28 | for(int i=0;i<=n;i++) 29 | arr[i]=count(i); 30 | 31 | 32 | return arr; 33 | 34 | 35 | } 36 | }; -------------------------------------------------------------------------------- /Python/Integer_To_Roman.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intToRoman(self, num: int) -> str: 3 | values = [1000, 900, 500, 400, 4 | 100, 90, 50, 40, 5 | 10, 9, 5, 4, 1] 6 | symbols = ["M", "CM", "D", "CD", 7 | "C", "XC", "L", "XL", 8 | "X", "IX", "V", "IV", 9 | "I"] 10 | roman = '' 11 | i = 0 12 | while num > 0: 13 | k = num // values[i] 14 | for j in range(k): 15 | roman += symbols[i] 16 | num -= values[i] 17 | i += 1 18 | return roman 19 | 20 | if __name__ == '__main__': 21 | # begin 22 | s = Solution() 23 | print (s.intToRoman(10)) 24 | -------------------------------------------------------------------------------- /C++/ValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name: Muhammad Abdullah Uppal 3 | * Username: Abdullah-Uppal 4 | * Approach: Use stack to push opening brackets and whenever you get closing bracket match it with the most recently pushed opening bracket. 5 | * */ 6 | class Solution { 7 | public: 8 | bool isValid(string s) { 9 | stack st; 10 | for(auto i:s) 11 | { 12 | if(i=='(' or i=='{' or i=='[') st.push(i); 13 | else 14 | { 15 | if(st.empty() || 16 | (st.top()=='(' && i!=')') || 17 | (st.top()=='{' && i!='}') || 18 | (st.top()=='[' && i!=']') 19 | ) return false; 20 | st.pop(); 21 | } 22 | } 23 | return st.empty(); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Python/981_Time_Based_Key-Value_Store.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | class TimeMap: 4 | 5 | def __init__(self): 6 | self.timeMap = collections.defaultdict(list) 7 | self.valueMap = {} 8 | 9 | def set(self, key: str, value: str, timestamp: int) -> None: 10 | bisect.insort(self.timeMap[key], timestamp) 11 | self.valueMap[(key, timestamp)] = value 12 | 13 | def get(self, key: str, timestamp: int) -> str: 14 | 15 | index = bisect.bisect_right(self.timeMap[key], timestamp) 16 | if index == 0: 17 | return "" 18 | return self.valueMap[(key, self.timeMap[key][index-1])] 19 | 20 | 21 | 22 | # Your TimeMap object will be instantiated and called as such: 23 | # obj = TimeMap() 24 | # obj.set(key,value,timestamp) 25 | # param_2 = obj.get(key,timestamp) 26 | -------------------------------------------------------------------------------- /Python/SotingList.py: -------------------------------------------------------------------------------- 1 | #Name: Abdullah Yaqub 2 | #Username: AbdullahYaqub72 3 | #Approach: Sorting List by Comparing Values of Previous and Next Nodes 4 | 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode(object): 8 | # def __init__(self, val=0, next=None): 9 | # self.val = val 10 | # self.next = next 11 | class Solution(object): 12 | def sortList(self, head): 13 | """ 14 | :type head: ListNode 15 | :rtype: ListNode 16 | """ 17 | start_node = head 18 | while start_node: 19 | itr = head 20 | while itr.next: 21 | if itr.val > itr.next.val: 22 | itr.val, itr.next.val = itr.next.val, itr.val 23 | itr = itr.next 24 | start_node = start_node.next 25 | return head 26 | -------------------------------------------------------------------------------- /Python/PostOrderTraversalBinaryTree.py: -------------------------------------------------------------------------------- 1 | #Name: Abdullah Yaqub 2 | #Username: AbdullahYaqub72 3 | #Approach: Recursively getting root node of tree at the end. 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, val=0, left=None, right=None): 8 | # self.val = val 9 | # self.left = left 10 | # self.right = right 11 | class Solution(object): 12 | def postorderTraversal(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: List[int] 16 | """ 17 | return_array=[] 18 | if root is None: 19 | return [] 20 | else: 21 | return_array+=self.postorderTraversal(root.left) 22 | return_array+=self.postorderTraversal(root.right) 23 | return_array.append(root.val) 24 | return return_array -------------------------------------------------------------------------------- /sorting_algos/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | // recursive approach 2 | 3 | void bubble_sort(int arr[],int size) 4 | { 5 | if (size == 0 || size == 1) 6 | return; 7 | for(int i = 0; i < size - 1 ; i++) 8 | { 9 | if(arr[i] > arr[i + 1]) 10 | { 11 | int temp = arr[i]; 12 | arr[i] = arr[i + 1]; 13 | arr[i + 1] = temp; 14 | } 15 | } 16 | bubble_sort(arr, size - 1); 17 | } 18 | 19 | // itrative approach 20 | void bubble_sort(int arr[],int size) 21 | { 22 | for(int i = 0; i < size - 1 ; i++) 23 | { 24 | for(int j = 0; j < size - i - 1; j++) 25 | { 26 | if(arr[j] > arr[j + 1]) 27 | { 28 | int temp = arr[j]; 29 | arr[j] = arr[j + 1]; 30 | arr[j + 1] = temp; 31 | } 32 | 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Python/Add Two Numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: 8 | kumar=ListNode(0) 9 | rum=kumar 10 | 11 | car=0 12 | while l1 or l2 or car: 13 | v1=l1.val if l1 else 0 14 | v2=l2.val if l2 else 0 15 | 16 | val=v1+v2+car 17 | car=val//10 18 | val=val%10 19 | rum.next=ListNode(val) 20 | 21 | rum=rum.next 22 | l1=l1.next if l1 else None 23 | l2=l2.next if l2 else None 24 | 25 | return kumar.next 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Python/PreOrderTraversalBinaryTree.py: -------------------------------------------------------------------------------- 1 | 2 | #Name: Abdullah Yaqub 3 | #Username: AbdullahYaqub72 4 | #Approach: Recursively getting root node of tree at the start of traversal. 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, val=0, left=None, right=None): 8 | # self.val = val 9 | # self.left = left 10 | # self.right = right 11 | class Solution(object): 12 | def preorderTraversal(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: List[int] 16 | """ 17 | return_array=[] 18 | if root is None: 19 | return [] 20 | else: 21 | return_array.append(root.val) 22 | return_array+=self.preorderTraversal(root.left) 23 | return_array+=self.preorderTraversal(root.right) 24 | 25 | return return_array -------------------------------------------------------------------------------- /Java/Longest_Palindromic_Substring.java: -------------------------------------------------------------------------------- 1 | public class Longest_Palindromic_Substring { 2 | private int lo, maxLen; 3 | public String longestPalindrome(String s) { 4 | int len = s.length(); 5 | if (len < 2) 6 | return s; 7 | 8 | for (int i = 0; i < len-1; i++) { 9 | extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible 10 | extendPalindrome(s, i, i+1); //assume even length. 11 | } 12 | return s.substring(lo, lo + maxLen); 13 | } 14 | 15 | private void extendPalindrome(String s, int j, int k) { 16 | while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) { 17 | j--; 18 | k++; 19 | } 20 | if (maxLen < k - j - 1) { 21 | lo = j + 1; 22 | maxLen = k - j - 1; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Python/Trapping_Rain_Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | ans=0 4 | maxl=maxr=0 5 | l=0 6 | r=len(height)-1 7 | while(lmaxl: 10 | maxl=height[l] 11 | else: 12 | ans+=maxl-height[l] 13 | l+=1 14 | else: 15 | if height[r]>maxr: 16 | maxr=height[r] 17 | else: 18 | ans+=maxr-height[r] 19 | r-=1 20 | return ans 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /C++/Design-Browser-History.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name: Abdul Ali Khan 3 | * Username: abdulalikhan 4 | * Problem No. 1472 5 | * Design Browser History 6 | */ 7 | class BrowserHistory { 8 | public: 9 | list history; 10 | list::iterator itr; 11 | 12 | BrowserHistory(string homepage) { 13 | history.push_back(homepage); 14 | itr = history.begin(); 15 | } 16 | 17 | void visit(string url) { 18 | auto temp = itr; 19 | history.erase(++temp, history.end()); 20 | history.push_back(url); 21 | itr++; 22 | } 23 | 24 | string back(int steps) { 25 | while (itr != history.begin() && steps--) 26 | itr--; 27 | return *itr; 28 | } 29 | 30 | string forward(int steps) { 31 | while (itr != (--history.end()) && steps--) 32 | itr++; 33 | return *itr; 34 | } 35 | }; -------------------------------------------------------------------------------- /JS/TwoSum.js: -------------------------------------------------------------------------------- 1 | //Name: Raza Mohayyuddin 2 | 3 | //Username: RazaKhan9639 4 | 5 | //Approach: First create a empty array named sum. After that create map to store elements of array subtracted by target as keys and its indices as values after looping through array. After that loop through the array again and if difference varaibale is in the hashmap then store the current index value in sum array and its associated index value in sum array. 6 | 7 | var twoSum = function (nums, target) { 8 | sum = []; 9 | // Map to store the difference and its index 10 | index_map = new Map(); 11 | // Loop for each element in the array 12 | for (let i = 0; i < nums.length; i++) { 13 | let difference = target - nums[i]; 14 | if (index_map.has(difference)) { 15 | sum[0] = i; 16 | sum[1] = index_map.get(difference); 17 | break; 18 | } else { 19 | index_map.set(nums[i], i); 20 | } 21 | } 22 | return sum; 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /JS/scss_into_css/index.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const globby = require('globby'); 3 | const {writeFileSync,readFileSync} = require('fs'); 4 | 5 | const dir = __dirname.replace(/\\/g, '/'); 6 | const findPath = `${dir}/lib/**/!(*.d).{ts,tsx,js,jsx}` 7 | const files = globby 8 | .sync(findPath, { dot: true }) 9 | .map((x) => path.resolve(x)); 10 | console.log({ files: files.length }); 11 | let changedFileCount = 0; 12 | const transToCSSCount = 0; 13 | const filesLen = files.length; 14 | for (let i = 0; i < filesLen; i += 1) { 15 | const file = files[i]; 16 | const content = readFileSync(file, 'utf-8'); 17 | if (content.includes('scss')) { 18 | const changedValue = content.replace(/scss/g, 'css'); 19 | changedFileCount += 1; 20 | writeFileSync(file, changedValue, 'utf8'); 21 | } 22 | } 23 | console.log( 24 | `Replaced ${transToCSSCount} styles with suffix css in ${changedFileCount} files` 25 | ); -------------------------------------------------------------------------------- /C++/largevaluesineachlevelbst.cpp: -------------------------------------------------------------------------------- 1 | /*Finding largest value in each level of a BST*/ 2 | 3 | class Solution{ 4 | public: 5 | vectorlargestvalueineachlevel(TreeNode*root){ 6 | if(root == NULL) 7 | return {}; 8 | vectormax_vals; 9 | int size; 10 | int max; 11 | TreeNode*temp; 12 | queueq; 13 | q.push(root); 14 | while(!q.empty()){ 15 | size = q.size(); 16 | max = INT_MIN; 17 | while(size--){ 18 | temp = q.front(); 19 | q.pop(); 20 | max = max(max, temp->val); 21 | if(temp->left) 22 | q.push(temp->left); 23 | if(temp->right){ 24 | q.push(temp->right); 25 | } 26 | max_vals.push_back(max); 27 | } 28 | } 29 | return max_vals; 30 | 31 | } 32 | 33 | }; -------------------------------------------------------------------------------- /Python/valid parenthesis.py: -------------------------------------------------------------------------------- 1 | # Name: Ayesha Aslam 2 | 3 | # Username: ch-ayesha 4 | 5 | # Approach: Solve this problem using stack and its time complexity is O(n) 6 | class Solution(object): 7 | def isValid(self, s): 8 | """ 9 | :type s: str 10 | :rtype: bool 11 | """ 12 | pairs = {')' : '(', '}' : '{', ']' : '['} 13 | inputs = ['(', '{', '['] 14 | stack = [] 15 | for char in s: 16 | if char in inputs: 17 | stack.append(char) 18 | else: 19 | check = pairs[char] 20 | 21 | if len(stack) == 0 or check != stack[-1]: 22 | return False 23 | else: 24 | stack.pop() 25 | 26 | if len(stack) == 0: 27 | return True 28 | return False 29 | if __name__ == '__main__': 30 | s = Solution() 31 | print (s.isValid( "()")) 32 | -------------------------------------------------------------------------------- /C++/InvertBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name: Abdullah Uppal 3 | * Username: Abdullah-Uppal 4 | * Approach: Recursively swap the left and right node. 5 | * */ 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 13 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 14 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | TreeNode* invertTree(TreeNode* root) { 20 | // swap two of the children. 21 | if (root == nullptr) return nullptr; 22 | TreeNode* temp = root->left; 23 | root->left = root->right; 24 | root->right = temp; 25 | invertTree(root->left); 26 | invertTree(root->right); 27 | return root; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /JS/MedianTwoSortedArrays.js: -------------------------------------------------------------------------------- 1 | //Name: Gabriele Nakassima 2 | 3 | //Username: gabynk 4 | 5 | //Approach: create a new array and merge the array that comes in the parameters and sort and find the average position of the created array. 6 | // checks whether the array size is even or odd. if odd returns the sum of two positions divided by 2 if not returns the average position value. 7 | 8 | /** 9 | * @param {number[]} nums1 10 | * @param {number[]} nums2 11 | * @return {number} 12 | */ 13 | 14 | var findMedianSortedArrays = function (nums1, nums2) { 15 | let mergedArray = new Array(); 16 | 17 | mergedArray = [...nums1, ...nums2]; 18 | mergedArray.sort(function (a, b) { return a - b }); 19 | 20 | const medianPosition = parseInt(mergedArray.length / 2); 21 | 22 | if (mergedArray.length % 2 === 0) 23 | return (mergedArray[parseInt(medianPosition)] + mergedArray[parseInt(medianPosition) - 1]) / 2; 24 | 25 | return mergedArray[parseInt(medianPosition)]; 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /Rust/TwoSum.rs: -------------------------------------------------------------------------------- 1 | //Name: Muhammad Yousaf 2 | 3 | //Username: yousafsabir 4 | 5 | //Approach: first created a hashmap with key being the value and the value being the index of vector, then check if the difference is available in the vector and the returning two sum 6 | fn main() { 7 | let nums = vec![1,2,3,4,5]; 8 | let target: i32 = 5; 9 | let result = two_sum(nums, target) 10 | println!("{}", "Result"); 11 | println!("{:?}", nums) 12 | } 13 | 14 | fn two_sum (nums: Vec, target:i32) -> Vec { 15 | let mut map: HashMap = HashMap::new(); 16 | 17 | for (i, num) in nums.iter().enumerate() { 18 | map.insert(*num, i as i32) 19 | } 20 | for (i, num) in nums.iter().enumerate() { 21 | let difference = target - num 22 | 23 | if let Some(&index) = map.get(&difference) { 24 | if index != i as i32 { 25 | return vec![i as i32, index] 26 | } 27 | } 28 | } 29 | vec![] 30 | } -------------------------------------------------------------------------------- /C++/PangramString.cpp: -------------------------------------------------------------------------------- 1 | // Name: Shoaib Sabir 2 | // Username: Shoaib019 3 | // Approach: take boolean type array size of 26 then 4 | // loop through string and mark bool arr according 5 | // to letter number at the end check if bool arr if 6 | // all true then all letters present else not 7 | 8 | class Solution { 9 | public: 10 | bool checkIfPangram(string sentence) { 11 | bool abc[26] = {false}; 12 | for(int i = 0; i < sentence.length(); i++) 13 | { 14 | if ((sentence[i] - 97) <= 25) 15 | { 16 | abc[sentence[i] - 97] = true; 17 | } 18 | } 19 | bool flag = true; 20 | int size = sizeof(abc) / sizeof(abc[0]); 21 | for(int i = 0; i < size; i++) 22 | { 23 | if(abc[i] != true) 24 | { 25 | flag = false; 26 | break; 27 | } 28 | } 29 | return (flag == true) ? true : false; 30 | } 31 | }; -------------------------------------------------------------------------------- /JS/RomanToInt.js: -------------------------------------------------------------------------------- 1 | //Name: Raza Mohayyuddin 2 | 3 | //Username: RazaKhan9639 4 | 5 | //Approach: First create a hashmap to store values of each key, this can be optimized to use string array or any other method. After that create a variable named sum to store the sum of the. After that start iterating over the array & check if the character is less than the next character then add the values to sum till checked all characters. After that return the value of the sum variable. 6 | 7 | var ro = new Map(); 8 | ro.set("I", 1); 9 | ro.set("V", 5); 10 | ro.set("X", 10); 11 | ro.set("L", 50); 12 | ro.set("C", 100); 13 | ro.set("D", 500); 14 | ro.set("M", 1000); 15 | var romanToInt = function (s) { 16 | var sum = 0; 17 | var n = s.length; 18 | 19 | for (i = 0; i < n; i++) { 20 | if (i != n - 1 && ro.get(s.charAt(i)) < ro.get(s.charAt(i + 1))) { 21 | sum += ro.get(s.charAt(i + 1)) - ro.get(s.charAt(i)); 22 | i++; 23 | } else { 24 | sum += ro.get(s.charAt(i)); 25 | } 26 | } 27 | return sum; 28 | }; 29 | -------------------------------------------------------------------------------- /Python/Binraysearch.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def binarySearch(arr, targetVal): 5 | min = 0 6 | max = len(arr) - 1 7 | iter = 1 8 | while len(arr): 9 | if max < min: 10 | return -1 11 | guess = int((min + max)/2) 12 | if arr[guess] == targetVal: 13 | print("We are on iter: " + str(iter)) 14 | print("The guess is " + str(arr[guess])) 15 | print("we found it!") 16 | return guess 17 | elif arr[guess] < targetVal: 18 | min = guess + 1 19 | elif arr[guess] > targetVal: 20 | max = guess - 1 21 | 22 | print("We are on iter: " + str(iter)) 23 | print("The guess is " + str(arr[guess])) 24 | iter += 1 25 | 26 | 27 | 28 | 29 | 30 | values = [10, 20, 24, 25, 30, 56, 67, 68, 69, 73, 78, 80, 100, 140, 200, 205] 31 | 32 | # the output will be the index where the target value is found 33 | result = binarySearch(values, 20) 34 | print("the index of target value is: " + str(result)) 35 | -------------------------------------------------------------------------------- /Python/Remove_Duplicates_from_Scorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def removeDuplicates(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: int 6 | # """ 7 | # ls = len(nums) 8 | # if ls <= 1: 9 | # return ls 10 | # last = nums[0] 11 | # pos = 1 12 | # for t in nums[1:]: 13 | # if t == last: 14 | # continue 15 | # else: 16 | # nums[pos] = t 17 | # pos += 1 18 | # last = t 19 | # return pos 20 | 21 | # https://leetcode.com/articles/remove-duplicates-sorted-array/ 22 | def removeDuplicates(self, nums): 23 | if len(nums) == 0: 24 | return 0 25 | left = 0 26 | for i in range(1, len(nums)): 27 | if nums[left] == nums[i]: 28 | continue 29 | else: 30 | left += 1 31 | nums[left] = nums[i] 32 | return left + 1 33 | -------------------------------------------------------------------------------- /JS/commonFactor.js: -------------------------------------------------------------------------------- 1 | const commonFactors = function(a, b) { 2 | if(a === 1 || b === 1) 3 | { 4 | return 1; 5 | } 6 | let commonFactors = 1; 7 | let isSmallerNumberDivisble = false; 8 | const smallerNumber = a > b ? b : a; 9 | const largerNumber = a < b ? b : a; 10 | 11 | const smallerNumberHalf = smallerNumber/ 2; 12 | 13 | 14 | if(largerNumber % smallerNumber === 0){ 15 | commonFactors++; 16 | isSmallerNumberDivisble = true 17 | } 18 | 19 | 20 | 21 | for(let i = 2 ; i <= smallerNumberHalf ; i++){ 22 | if(smallerNumber % i === 0){ 23 | if(isSmallerNumberDivisble){ 24 | commonFactors++; 25 | }else{ 26 | if(largerNumber % i === 0){ 27 | commonFactors++; 28 | } 29 | } 30 | } 31 | 32 | 33 | } 34 | 35 | return commonFactors; 36 | }; 37 | 38 | /* Test Case */ 39 | console.log(commonFactors(12,6)) -------------------------------------------------------------------------------- /C++/delete_middle_node_of_a_linked_list.cpp: -------------------------------------------------------------------------------- 1 | /*Name - Mayank Rastogi 2 | Username - mayxnk 3 | Approach - Using slow and fast pointer to find the middle of linked list and 4 | maintaing a previous pointer to delete the middle one 5 | */ 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode() : val(0), next(nullptr) {} 12 | * ListNode(int x) : val(x), next(nullptr) {} 13 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | ListNode* deleteMiddle(ListNode* head) { 19 | if(!head or !head->next) 20 | return NULL; 21 | ListNode* slow = head,*fast = head,*prev = NULL; 22 | while(slow and fast and fast->next) 23 | { 24 | prev = slow; 25 | slow = slow->next; 26 | fast = fast->next->next; 27 | } 28 | if(prev!=NULL) 29 | prev->next = slow->next; 30 | return head; 31 | } 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /JS/patternsolution.js: -------------------------------------------------------------------------------- 1 | const arr = [ 2 | "AND", 3 | ["<", "a", "b"], 4 | ["OR", ["==", "c", "d"], ["!=", "e", "f"]] 5 | ]; 6 | var result = []; 7 | const operators = ["OR", "AND", "!=", "==", "<", ">"]; 8 | var resultstr = ""; 9 | function StringConvert(temp){ 10 | for(var i in temp){ 11 | if(operators.includes(temp[i])){ 12 | result.push(temp[i]) 13 | } 14 | else if(temp[i].length === 1 && temp[i].match(/[a-z]/i)){ 15 | resultstr=resultstr+temp[i]+" " 16 | if(result.length!=0){ 17 | tempdata=result.pop() 18 | resultstr=resultstr+tempdata+" " 19 | } 20 | } 21 | } 22 | } 23 | function COnvert(arr) { 24 | for(var i in arr){ 25 | var value=arr[i] 26 | var temp=value.toString(); 27 | temp=temp.split(',') 28 | if(value.length===3 &&(value[0]==='AND' || value[0]==='OR')){ 29 | resultstr=resultstr+'(' 30 | StringConvert(temp) 31 | resultstr=resultstr+')' 32 | } 33 | else{ 34 | StringConvert(temp) 35 | } 36 | } 37 | } 38 | COnvert(arr); 39 | console.log(resultstr); 40 | -------------------------------------------------------------------------------- /JS/IntToRoman.js: -------------------------------------------------------------------------------- 1 | //Name: Raza Mohayyuddin 2 | 3 | //Username: RazaKhan9639 4 | 5 | //Approach:First create a map which has each key & value pair in it.After that create a res variable to store output string. Then start looping over the map variable where i checks for remainder has any roman number & this value is stored in res variable, then it does modulo division. After that it checks whether the num variable is equal to zero then it returns the res variable otherwise continues in the loop. 6 | 7 | var intToRoman = function (num) { 8 | const map = { 9 | M: 1000, 10 | CM: 900, 11 | D: 500, 12 | CD: 400, 13 | C: 100, 14 | XC: 90, 15 | L: 50, 16 | XL: 40, 17 | X: 10, 18 | IX: 9, 19 | V: 5, 20 | IV: 4, 21 | I: 1, 22 | }; 23 | 24 | let res = ""; 25 | 26 | for (key in map) { 27 | const rCounter = Math.floor(num / map[key]); 28 | 29 | if (rCounter !== 0) { 30 | res += key.repeat(rCounter); 31 | } 32 | 33 | num %= map[key]; 34 | 35 | if (num === 0) return res; 36 | } 37 | 38 | return res; 39 | }; 40 | -------------------------------------------------------------------------------- /JS/ReverseInt.js: -------------------------------------------------------------------------------- 1 | //Name: Raza Mohayyuddin 2 | 3 | //Username: RazaKhan9639 4 | 5 | //Approach: First check if the number is negative or not. Than take absolute of the number for working further. after that initialize reverse and reminder to zero. Than take a reminder of the last digit and multiply reverse by 10 to get the place of the newly added digit, and after that add the reminder digit. Divide the main number by 10 to remove that last digit with help of reminder value. Than check if the reverse number is greater than the required integer range or not ( 2^31 - 1 ). Than return the value by multiplying it with the flag's sign. 6 | 7 | var reverse = function (x) { 8 | var num = Math.abs(x); 9 | var flag = 1; 10 | var reverse = 0, 11 | reminder = 0; 12 | 13 | if (x < 0) { 14 | flag = -1; 15 | } 16 | 17 | while (num > 0) { 18 | reminder = num % 10; 19 | reverse = reverse * 10 + reminder; 20 | num = (num - reminder) / 10; 21 | } 22 | 23 | if (reverse >= Math.pow(2, 31)) { 24 | return 0; 25 | } 26 | 27 | return reverse * flag; 28 | }; 29 | -------------------------------------------------------------------------------- /Java/MajorityElement.java: -------------------------------------------------------------------------------- 1 | // Name: Shoaib Sabir 2 | // Username: Shoaib019 3 | // Approach: make new hashmap check if key already exists then 4 | // increase by 1 otherwise put 0 after that find maximum value 5 | // and return coresponding key 6 | import java.util.HashMap; 7 | class Solution { 8 | public int majorityElement(int[] nums) { 9 | HashMap keepCount = new HashMap(); 10 | for (int i = 0; i < nums.length; i++) 11 | { 12 | if(keepCount.containsKey(nums[i])){ 13 | keepCount.put(nums[i], keepCount.get(nums[i]) + 1); 14 | } 15 | else{ 16 | keepCount.put(nums[i], 0); 17 | } 18 | } 19 | int majorityVar = 0; 20 | int maxValue = (Collections.max(keepCount.values())); 21 | for (Map.Entry countMap : keepCount.entrySet()) { 22 | if (countMap.getValue() == maxValue) { 23 | majorityVar = countMap.getKey(); 24 | } 25 | } 26 | return majorityVar; 27 | } 28 | } -------------------------------------------------------------------------------- /C++/Problem 199 Binary Tree Right Side View.cpp: -------------------------------------------------------------------------------- 1 | 2 | 199 - Binary Tree Right Side View 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * struct TreeNode { 7 | * int val; 8 | * TreeNode *left; 9 | * TreeNode *right; 10 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | 18 | void rightv(TreeNode* root , vector&ans,int level){ 19 | if(root==NULL)return; 20 | cout<val); 22 | 23 | rightv(root->right,ans,level+1); 24 | rightv(root->left,ans,level+1); 25 | 26 | cout<<1; 27 | 28 | } 29 | 30 | vector rightSideView(TreeNode* root) { 31 | vector v; 32 | rightv(root,v,1); 33 | return v; 34 | 35 | 36 | 37 | 38 | } 39 | }; -------------------------------------------------------------------------------- /Java/Regular_Expression_Matching.java: -------------------------------------------------------------------------------- 1 | public boolean isMatch(String s, String p) { 2 | 3 | if (s == null || p == null) { 4 | return false; 5 | } 6 | boolean[][] dp = new boolean[s.length()+1][p.length()+1]; 7 | dp[0][0] = true; 8 | for (int i = 0; i < p.length(); i++) { 9 | if (p.charAt(i) == '*' && dp[0][i-1]) { 10 | dp[0][i+1] = true; 11 | } 12 | } 13 | for (int i = 0 ; i < s.length(); i++) { 14 | for (int j = 0; j < p.length(); j++) { 15 | if (p.charAt(j) == '.') { 16 | dp[i+1][j+1] = dp[i][j]; 17 | } 18 | if (p.charAt(j) == s.charAt(i)) { 19 | dp[i+1][j+1] = dp[i][j]; 20 | } 21 | if (p.charAt(j) == '*') { 22 | if (p.charAt(j-1) != s.charAt(i) && p.charAt(j-1) != '.') { 23 | dp[i+1][j+1] = dp[i+1][j-1]; 24 | } else { 25 | dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]); 26 | } 27 | } 28 | } 29 | } 30 | return dp[s.length()][p.length()]; 31 | } -------------------------------------------------------------------------------- /Python/Reverse_Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @return an integer 3 | 4 | # def reverse(self, x): 5 | # max_int = 2147483647 6 | # if x == 0: 7 | # return 0 8 | # isPos = True 9 | # if x < 0: 10 | # x *= (-1) 11 | # isPos = False 12 | # ltemp = [] 13 | # while x != 0: 14 | # temp = x % 10 15 | # ltemp.append(temp) 16 | # x /= 10 17 | # result = 0 18 | # # the main solution 19 | # for t in ltemp: 20 | # result = result * 10 + t 21 | # if result > max_int: 22 | # result = 0 23 | # if isPos: 24 | # return result 25 | # else: 26 | # return -1 * result 27 | 28 | def reverse(self, x): 29 | # Note that in Python -1 / 10 = -1 30 | res, isPos = 0, 1 31 | if x < 0: 32 | isPos = -1 33 | x = -1 * x 34 | while x != 0: 35 | res = res * 10 + x % 10 36 | if res > 2147483647: 37 | return 0 38 | x /= 10 39 | return res * isPos 40 | -------------------------------------------------------------------------------- /C++/largest-rectangle-in-histogram.cpp: -------------------------------------------------------------------------------- 1 | // Name: Sumit Chakraborty 2 | 3 | // Username: chakraborty9569 4 | #include 5 | #include 6 | class Solution { 7 | public: 8 | int largestRectangleArea(vector& heights) { 9 | stack s; 10 | int max_area=0; 11 | int tp; 12 | int area_with_tp; 13 | int i=0; 14 | while(i player; 8 | for(int i=1;i<=n;i++) 9 | { 10 | player.push_back(i); 11 | } 12 | int value; 13 | while(true) 14 | { 15 | if(player.size() == 1) 16 | { 17 | break; 18 | } 19 | for(int i=1;ival > val) 25 | { 26 | node=node->left; 27 | } 28 | else 29 | { 30 | node=node->right; 31 | } 32 | } 33 | if(node == NULL) 34 | { 35 | temp->left=new TreeNode(val); 36 | } 37 | return node; 38 | 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Java/merge-two-sorted-lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Name: Sumit Chakraborty 3 | * 4 | * Username: chakraborty9569 5 | * 6 | * Approach: Create new linked list. Traverse the given two lists in sorted order. Insert new nodes accordingliy in the new list. 7 | * 8 | * } 9 | */ 10 | /** 11 | * Definition for singly-linked list. 12 | * public class ListNode { 13 | * int val; 14 | * ListNode next; 15 | * ListNode() {} 16 | * ListNode(int val) { this.val = val; } 17 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 18 | * } 19 | */ 20 | class Solution { 21 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 22 | ListNode dummy=new ListNode(0); 23 | ListNode curr=dummy; 24 | while(l1!=null && l2!=null) 25 | { 26 | if(l1.val<=l2.val) 27 | { 28 | curr.next=l1; 29 | l1=l1.next; 30 | } 31 | else 32 | { 33 | curr.next=l2; 34 | l2=l2.next; 35 | } 36 | curr=curr.next; 37 | } 38 | curr.next=l1!=null?l1:l2; 39 | return dummy.next; 40 | } 41 | } -------------------------------------------------------------------------------- /C++/LC_429_N_ary_Tree_Level_Order_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | vector children; 7 | 8 | Node() {} 9 | 10 | Node(int _val) { 11 | val = _val; 12 | } 13 | 14 | Node(int _val, vector _children) { 15 | val = _val; 16 | children = _children; 17 | } 18 | }; 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | vector> levelOrder(Node *root) 25 | { 26 | if (root == NULL) 27 | return {}; 28 | vector> ans; 29 | queue q; 30 | q.push(root); 31 | 32 | while (!q.empty()) 33 | { 34 | int size = q.size(); 35 | vector v; 36 | while (size--) 37 | { 38 | Node *temp = q.front(); 39 | q.pop(); 40 | v.push_back(temp->val); 41 | 42 | for (int i = 0; i < temp->children.size(); i++) 43 | { 44 | q.push(temp->children[i]); 45 | } 46 | } 47 | ans.push_back(v); 48 | } 49 | return ans; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /C++/Binary Search.cpp: -------------------------------------------------------------------------------- 1 | // Name: Samsor Rahman 2 | 3 | // Username: samsorrahman 4 | 5 | // Approach: Binary Search using Recusive approuch and easy solution 6 | 7 | class Solution { 8 | public: 9 | int binary(vectorv,int l, int r, int key) 10 | { 11 | // till l doesn't exceed r 12 | if(r >= l) 13 | { 14 | int mid = (l+r)/2; 15 | 16 | // if key equals mid return mid 17 | if(key == v[mid]) 18 | return mid; 19 | 20 | // if key is less than mid 21 | // recursive call for left half 22 | else if(key < v[mid]) 23 | return binary(v,l,mid-1,key); 24 | 25 | // key is greater than mid 26 | // recursive call for right half 27 | else 28 | return binary(v,mid+1,r,key); 29 | } 30 | 31 | // if key not found 32 | return -1; 33 | } 34 | int search(vector& nums, int target) { 35 | int result = binary(nums,0,nums.size()-1,target); 36 | 37 | // if func returns -1 key doesn't exists 38 | if (result == -1) 39 | return -1; 40 | 41 | // return index of key 42 | else 43 | return result; 44 | } 45 | 46 | }; 47 | -------------------------------------------------------------------------------- /Python/sort_colors.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def sortColors(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: void Do not return anything, modify nums in-place instead. 6 | # """ 7 | # # simple counting sort 8 | # count = [0] * 3 9 | # for num in nums: 10 | # count[num] += 1 11 | # pos = 0 12 | # for index in range(3): 13 | # while count[index] > 0: 14 | # nums[pos] = index 15 | # pos += 1 16 | # count[index] -= 1 17 | # return 18 | 19 | def sortColors(self, nums): 20 | # https://leetcode.com/discuss/85658/sharing-c-solution-with-good-explanation 21 | low, mid, high = 0, 0, len(nums) - 1 22 | while mid <= high: 23 | if nums[mid] == 0: 24 | # swap low mid 25 | nums[low], nums[mid] = nums[mid], nums[low] 26 | low += 1 27 | mid += 1 28 | elif nums[mid] == 1: 29 | mid += 1 30 | else: 31 | # swap mid high 32 | nums[high], nums[mid] = nums[mid], nums[high] 33 | high -= 1 34 | return 35 | -------------------------------------------------------------------------------- /Java/CheckForValidParenthesisUsingStack.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Name: Muhammad Khuzaima Umair 4 | * 5 | * Username: mkhuzaima 6 | * 7 | * Approach: Check for the validity using stacks 8 | * 9 | * Problem Link: https://leetcode.com/problems/valid-parentheses/submissions/ 10 | */ 11 | 12 | import java.util.Stack; 13 | 14 | class Solution { 15 | public boolean isValid(String s) { 16 | Stack stack = new Stack(); 17 | 18 | for (int i = 0; i < s.length(); i++) { 19 | char c = s.charAt(i); 20 | 21 | if (c == '(' || c == '[' || c == '{') { 22 | stack.push(c); 23 | } 24 | // if no matching bracket, then not valid 25 | else if (stack.isEmpty()) { 26 | return false; 27 | 28 | // check for matching bracket 29 | } else { 30 | char lastElement = stack.pop(); 31 | 32 | if ((c == ']' && lastElement != '[') || 33 | (c == ')' && lastElement != '(') || 34 | (c == '}' && lastElement != '{')) { 35 | return false; 36 | } 37 | } 38 | } 39 | 40 | return stack.isEmpty(); 41 | 42 | } 43 | } -------------------------------------------------------------------------------- /C++/Kth-smallest-element-in-BST.cpp: -------------------------------------------------------------------------------- 1 | // Name: Hussain Iftikhar 2 | // Username: hussainiftikhar5242 3 | // Approach: First store all node in vector and then sort the vector, after sorting the vector return the kth-1 index 4 | /** 5 | * Definition for a binary tree node. 6 | * struct TreeNode { 7 | * int val; 8 | * TreeNode *left; 9 | * TreeNode *right; 10 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | int kthSmallest(TreeNode* root, int k) { 18 | vector temp; 19 | TreeNode* node; 20 | stack s1; 21 | s1.push(root); 22 | while(!s1.empty()) 23 | { 24 | TreeNode * curr = s1.top(); 25 | int val=curr->val; 26 | temp.push_back(val); 27 | s1.pop(); 28 | if(curr->left != NULL) 29 | s1.push(curr->left); 30 | if(curr->right != NULL) 31 | s1.push(curr->right); 32 | } 33 | sort(temp.begin(),temp.end()); 34 | return temp.at(k-1); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /JS/Restrained3a3b.js: -------------------------------------------------------------------------------- 1 | //Name: Raza Mohayyuddin 2 | 3 | //Username: RazaKhan9639 4 | 5 | //Approach: First create a variable rt to store the required string. After that use if else conditions to to compare the numbers of 'a' and 'b' in a usual order of counting and store the string in rt by appending 2b then a or 2a then b. Time complexity : n, where n is the count of a or b , and space complexity is normal O(1). 6 | 7 | var strWithout3a3b = function (a, b) { 8 | let rt = ""; //Required String 9 | while (a > 0 || b > 0) { 10 | // More 'b', append "bba" 11 | if (a < b) { 12 | if (b-- > 0) { 13 | rt += "b"; 14 | } 15 | if (b-- > 0) { 16 | rt += "b"; 17 | } 18 | if (a-- > 0) { 19 | rt += "a"; 20 | } 21 | } 22 | 23 | // More 'a', append "aab" 24 | else if (b < a) { 25 | if (a-- > 0) { 26 | rt += "a"; 27 | } 28 | if (a-- > 0) { 29 | rt += "a"; 30 | } 31 | if (b-- > 0) { 32 | rt += "b"; 33 | } 34 | } 35 | 36 | // Equal number of 'a' and 'b' 37 | // append "ab" 38 | else { 39 | if (a-- > 0) { 40 | rt += "a"; 41 | } 42 | if (b-- > 0) { 43 | rt += "b"; 44 | } 45 | } 46 | } 47 | return rt; 48 | }; 49 | -------------------------------------------------------------------------------- /Java/smallestmissingnumber.java: -------------------------------------------------------------------------------- 1 | import java.util.arrayays; 2 | 3 | class smallestmissingnumber { 4 | static int function(int array[], int n) 5 | { 6 | int temp = 0; 7 | 8 | // Checking if 1 is present in array or not 9 | for (int i = 0; i < n; i++) { 10 | if (array[i] == 1) { 11 | temp = 1; 12 | break; 13 | } 14 | } 15 | 16 | // 1 not present 17 | if (temp == 0) 18 | return (1); 19 | for (int i = 0; i < n; i++) 20 | if (array[i] <= 0 || array[i] > n) 21 | {array[i] = 1;} 22 | 23 | // Updating indices according to values 24 | for (int i = 0; i < n; i++) 25 | array[(array[i] - 1) % n] += n; 26 | 27 | // Finding which index has value less than n 28 | for (int i = 0; i < n; i++) 29 | if (array[i] <= n) 30 | return (i + 1); 31 | 32 | // If array has values from 1 to n 33 | return (n + 1); 34 | } 35 | 36 | public static void main(String[] args) 37 | { 38 | int array[] = { 5, 3, -10, 0, -2 }; 39 | int len = array.length; 40 | int num = function(array, len); 41 | 42 | System.out.println(num); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Python/Longest_Palindromic_Substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> str: 3 | longest_palindrom = '' 4 | dp = [[0]*len(s) for _ in range(len(s))] 5 | #filling out the diagonal by 1 6 | for i in range(len(s)): 7 | dp[i][i] = True 8 | longest_palindrom = s[i] 9 | 10 | # filling the dp table 11 | for i in range(len(s)-1,-1,-1): 12 | # j starts from the i location : to only work on the upper side of the diagonal 13 | for j in range(i+1,len(s)): 14 | if s[i] == s[j]: #if the chars mathces 15 | # if len slicied sub_string is just one letter if the characters are equal, we can say they are palindomr dp[i][j] =True 16 | #if the slicied sub_string is longer than 1, then we should check if the inner string is also palindrom (check dp[i+1][j-1] is True) 17 | if j-i ==1 or dp[i+1][j-1] is True: 18 | dp[i][j] = True 19 | # we also need to keep track of the maximum palindrom sequence 20 | if len(longest_palindrom) < len(s[i:j+1]): 21 | longest_palindrom = s[i:j+1] 22 | 23 | return longest_palindrom -------------------------------------------------------------------------------- /Python/Regular_Expression_Matching.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isMatch(self, s, p): 3 | """ 4 | :type s: str 5 | :type p: str 6 | :rtype: bool 7 | """ 8 | # bottom up o(m*n) 9 | # https://leetcode.com/discuss/93024/easy-dp-java-solution-with-detailed-explanation 10 | if s == p: 11 | return True 12 | m, n = len(s), len(p) 13 | dp = [[False] * (n + 1) for _ in range(m + 1)] 14 | dp[0][0] = True 15 | for j in range(1, n): 16 | if p[j] == '*' and dp[0][j - 1]: 17 | dp[0][j + 1] = True 18 | # print dp 19 | for i in range(m): 20 | for j in range(n): 21 | if p[j] == '.' or p[j] == s[i]: 22 | dp[i + 1][j + 1] = dp[i][j] 23 | elif p[j] == '*': 24 | if p[j - 1] != s[i] and p[j - 1] != '.': 25 | dp[i + 1][j + 1] = dp[i + 1][j - 1] 26 | else: 27 | dp[i + 1][j + 1] = dp[i + 28 | 1][j] or dp[i][j + 1] or dp[i + 1][j - 1] 29 | return dp[m][n] 30 | 31 | 32 | if __name__ == '__main__': 33 | # begin 34 | s = Solution() 35 | print s.isMatch("", ".*") 36 | -------------------------------------------------------------------------------- /MYSQL/user_name_and_count_of_invoices.sql: -------------------------------------------------------------------------------- 1 | -- Write an SQL query to find username and count of invoices from user and invoice table. 2 | 3 | -- Return the result table in any order. 4 | -- Write your MySQL query statement below 5 | -- create a table 6 | CREATE TABLE user ( 7 | id INTEGER PRIMARY KEY, 8 | name TEXT NOT NULL, 9 | gender TEXT NOT NULL 10 | ); 11 | 12 | CREATE TABLE invoice ( 13 | id INTEGER PRIMARY KEY, 14 | name TEXT NOT NULL, 15 | total INTEGER NOT NULL, 16 | user_id INTEGER, 17 | FOREIGN KEY (user_id) REFERENCES user(id) 18 | ); 19 | -- insert some values 20 | INSERT INTO user VALUES (1, 'Ryan', 'M'); 21 | INSERT INTO user VALUES (2, 'Joanna', 'F'); 22 | INSERT INTO user VALUES (3, 'Saul', 'M'); 23 | INSERT INTO user VALUES (4, 'Norma', 'F'); 24 | 25 | INSERT INTO invoice VALUES (1, 'backery', 99,1); 26 | INSERT INTO invoice VALUES (2, 'meat', 88,1); 27 | INSERT INTO invoice VALUES (3, 'candy', 77,3); 28 | INSERT INTO invoice VALUES (4, 'soaps', 66,4); 29 | INSERT INTO invoice VALUES (5, 'meat', 55,2); 30 | INSERT INTO invoice VALUES (6, 'candy', 44,2); 31 | INSERT INTO invoice VALUES (7, 'soaps', 33,2); 32 | -- fetch some values 33 | SELECT user.name , COUNT(*) as count 34 | FROM user 35 | INNER JOIN invoice ON user.id = invoice.user_id 36 | GROUP BY user.id 37 | HAVING COUNT(*) > 1; -------------------------------------------------------------------------------- /C++/RemoveElements.cpp: -------------------------------------------------------------------------------- 1 | 2 | /*Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val.*/ 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * struct ListNode { 7 | * int val; 8 | * ListNode *next; 9 | * ListNode() : val(0), next(nullptr) {} 10 | * ListNode(int x) : val(x), next(nullptr) {} 11 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | ListNode* removeElements(ListNode* head, int val) { 17 | 18 | 19 | while(head!=NULL) 20 | { 21 | if(head->val==val)head=head->next; 22 | else break; 23 | } 24 | ListNode* curr= head; 25 | ListNode* prev= NULL; 26 | if(head==NULL)return head; 27 | while(curr!=NULL) 28 | { 29 | if(curr->val==val) 30 | { 31 | 32 | prev->next=curr->next; 33 | curr=curr->next; 34 | 35 | } 36 | else{ 37 | 38 | prev=curr; 39 | curr=curr->next; 40 | } 41 | 42 | } 43 | 44 | return head; 45 | } 46 | }; -------------------------------------------------------------------------------- /JS/phone_shop.js: -------------------------------------------------------------------------------- 1 | // Name: Shoaib Sabir 2 | // Username: Shoaib019 3 | // Question: find out you can afford phone or not by calculating 4 | // phone price with accessories also add tax 5 | 6 | // DATA 7 | TAX_RATE = 0.08; 8 | PHONE_PRICE = 99.99; 9 | ACCESSORY_PRICE = 9.99; 10 | SPENDING_THRESHOLD = 200; 11 | var bank_account_balance = 303.91; 12 | 13 | console.log(calculatePurchaseAmount()); // this is starting point 14 | 15 | function calculatePurchaseAmount() { 16 | totalSpent = calculateTotalPhonePrice(); 17 | totalAmount = totalSpent + calculatingTax(totalSpent); 18 | return formatThePrice(totalAmount); 19 | } 20 | 21 | function canBuy(spent){ // this function keeps some amount in bank account 22 | remaining_bal = bank_account_balance - spent; 23 | return remaining_bal > ACCESSORY_PRICE ? true : false; 24 | } 25 | 26 | function calculateTotalPhonePrice(){ 27 | let spent = 0; 28 | while (canBuy(spent)){ 29 | spent += PHONE_PRICE; 30 | 31 | if(spent < SPENDING_THRESHOLD){ 32 | spent += ACCESSORY_PRICE; 33 | } 34 | } 35 | return spent; 36 | } 37 | 38 | 39 | function calculatingTax(totalSpent){ 40 | return totalSpent * TAX_RATE; 41 | } 42 | 43 | function formatThePrice(totalAmount){ 44 | return "Total Price: $" + String(totalAmount.toFixed(2)); 45 | } -------------------------------------------------------------------------------- /C++/sort_colors.cpp: -------------------------------------------------------------------------------- 1 | #Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. 2 | 3 | We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. 4 | 5 | You must solve this problem without using the library's sort function. 6 | 7 | class Solution { 8 | public: 9 | void sortColors(vector& nums) { 10 | int i=0,j=1,k=2,count0=0,count1=0,count2=0; 11 | for(int l=0;l target: 16 | # max = pos - 1 17 | # else: 18 | # min = pos + 1 19 | # if min > pos: 20 | # # this means that target is great than pos, and target 21 | # # is not in nums 22 | # return pos + 1 23 | # return pos 24 | 25 | def searchInsert(self, nums, target): 26 | l, r = int(0), len(nums) - 1 27 | while l < r: 28 | mid = int((l + r) / 2) 29 | if nums[mid] < target: 30 | l = mid + 1 31 | else: 32 | r = mid 33 | if nums[l] < target: 34 | return l + 1 35 | return l 36 | 37 | 38 | 39 | if __name__ == '__main__': 40 | # begin 41 | s = Solution() 42 | print (s.searchInsert([1,3,5,6],5)) 43 | 44 | -------------------------------------------------------------------------------- /C++/PalindromeLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Name: Muhammad Khuzaima Umair 3 | 4 | Username: mkhuzaima 5 | 6 | Approach: Convert the LinkedList to the array, and then check whether the array is palindrome or not 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode() : val(0), next(nullptr) {} 15 | * ListNode(int x) : val(x), next(nullptr) {} 16 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool isPalindrome(ListNode* head) { 22 | int size = 0; 23 | ListNode *node = head; 24 | while (node != NULL) { 25 | size++; 26 | node = node->next; 27 | } 28 | 29 | 30 | 31 | // create an array of size 32 | int array[size]; 33 | 34 | // copy list to array 35 | for(int i = 0; i < size; i++){ 36 | array[i] = head->val; 37 | head = head->next; 38 | } 39 | 40 | int half = size/2; 41 | // check for palindrome 42 | for(int i = 0; i< half; i++){ 43 | if (array[i] != array[size-1-i]){ 44 | return false; 45 | } 46 | } 47 | 48 | return true; 49 | } 50 | }; -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Sync Forked Repo from Upstream Repo 2 | 3 | 4 | 1. Add the original repository as an upstream repository 5 | ```javascript 6 | $ git remote add upstream https://github.com/[Original Owner Username]/[Original Repository].git 7 | ``` 8 | Hence, in this repository it would be 9 | ```javascript 10 | $ git remote add upstream https://github.com/saadfareed/Leetcode.git 11 | ``` 12 | 13 | 2. Fetch all the changes from the repository. Note that commits to the original repository will be stored in a local branch called, upstream/master 14 | ```javascript 15 | $ git fetch upstream 16 | ``` 17 | 18 | 3. Make sure that you are on your fork's master or working branch 19 | ```javascript 20 | $ git checkout [working branch] 21 | ``` 22 | For example, 23 | ```javascript 24 | $ git checkout master 25 | ``` 26 | 27 | 4. Merge the changes from the upstream/master into your local master or working branch. This will sync the fork's master branch with the upstream repository without losing your local changes. If you have made any changes that create conflict, you will have to resolve the conflict before you can complete the merge 28 | ```javascript 29 | $ git merge upstream/master 30 | ``` 31 | 32 | 5. At this point, your local branch is synced with the upstream/master branch. In order to update the remote branch in Github, you need to push your changes 33 | -------------------------------------------------------------------------------- /C++/Merge-Nodes-in-Between-Zeros.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Name: Abdul Ali Khan 3 | * Username: abdulalikhan 4 | * Problem No. 2181 5 | * Merge Nodes in Between Zeros 6 | */ 7 | class Solution { 8 | public: 9 | ListNode* mergeNodes(ListNode* head) { 10 | ListNode* temp = head; 11 | ListNode* headNew = new ListNode(); 12 | ListNode* temp2 = headNew; 13 | int sum = 0; 14 | bool firstZero = false; 15 | while (temp != NULL){ 16 | if (!firstZero && temp->val == 0) 17 | firstZero = true; 18 | else if (firstZero && temp->val != 0) 19 | sum += temp->val; 20 | else if (firstZero && temp->val == 0 && sum == 0) 21 | sum += temp->val; 22 | else if (firstZero && temp->val == 0 && sum > 0){ 23 | if (temp2->val == 0) 24 | temp2->val = sum; 25 | else{ 26 | ListNode* newNode = new ListNode(sum); 27 | temp2->next = newNode; 28 | temp2 = temp2->next; 29 | } 30 | sum = 0; 31 | } 32 | temp = temp->next; 33 | } 34 | if (sum > 0){ 35 | ListNode* newNode = new ListNode(sum); 36 | temp2->next = newNode; 37 | } 38 | return headNew; 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/Middle_of_LL.cpp: -------------------------------------------------------------------------------- 1 | /*Given the head of a singly linked list, return the middle node of the linked list.If there are two middle nodes, return the second middle node. 2 | */ 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode* middleNode(ListNode* head) { 16 | ListNode* fast; 17 | ListNode* tmp; 18 | ListNode* slow; 19 | fast=head; 20 | tmp=head; 21 | slow=head; 22 | int count=0; 23 | while(tmp!=NULL) 24 | { 25 | tmp=tmp->next; 26 | count++; 27 | } 28 | 29 | 30 | if(count%2==0) 31 | { 32 | while(fast->next->next!=tmp) 33 | { 34 | fast=fast->next->next; 35 | slow=slow->next; 36 | } 37 | return slow->next; 38 | } 39 | else 40 | { 41 | while(fast->next!=tmp) 42 | { 43 | fast=fast->next->next; 44 | slow=slow->next; 45 | } 46 | return slow; 47 | } 48 | 49 | return head; 50 | } 51 | }; -------------------------------------------------------------------------------- /C++/kth-smallest-element-in-a-bst problem#230.cpp: -------------------------------------------------------------------------------- 1 | Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. 2 | 3 | 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * struct TreeNode { 8 | * int val; 9 | * TreeNode *left; 10 | * TreeNode *right; 11 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 12 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 13 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | 19 | vector inorder(TreeNode* root) 20 | { 21 | 22 | vector v; 23 | if(root==NULL)return v; 24 | 25 | vectorleft=inorder(root->left); 26 | v.insert(v.end(),left.begin(),left.end()); 27 | v.push_back(root->val); 28 | vectorright=inorder(root->right); 29 | v.insert(v.end(),right.begin(),right.end()); 30 | 31 | return v; 32 | 33 | 34 | 35 | } 36 | 37 | 38 | int kthSmallest(TreeNode* root, int k) { 39 | 40 | vectorv=inorder(root); 41 | 42 | return v[k-1]; 43 | 44 | 45 | 46 | 47 | } 48 | }; -------------------------------------------------------------------------------- /JS/Nextvalue_Recursive.js: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD 2 | const array=[ 3 | {id:'one',next:"two", value:null}, 4 | {id:'two',next:"three", value:null}, 5 | {id:'three',next: "four", value:null}, 6 | {id:'four',next: null, value:null} 7 | ]; 8 | var nextindex=0 9 | function updatearray(array){ 10 | updatevalue(array,0) 11 | function updatevalue(array,index){ 12 | if(array[index].next==null){ 13 | return array[index] 14 | } 15 | else{ 16 | array[index].value=updatevalue(array,index+1) 17 | return array[index] 18 | } 19 | } 20 | } 21 | 22 | updatearray(array) 23 | var arr=array 24 | arr=JSON.stringify(array) 25 | ======= 26 | const array=[ 27 | {id:'one',next:"two", value:null}, 28 | {id:'two',next:"three", value:null}, 29 | {id:'three',next: "four", value:null}, 30 | {id:'four',next: null, value:null} 31 | ]; 32 | var nextindex=0 33 | function updatearray(array){ 34 | updatevalue(array,0) 35 | function updatevalue(array,index){ 36 | if(array[index].next==null){ 37 | return array[index] 38 | } 39 | else{ 40 | array[index].value=updatevalue(array,index+1) 41 | return array[index] 42 | } 43 | } 44 | } 45 | 46 | updatearray(array) 47 | var arr=array 48 | arr=JSON.stringify(array) 49 | >>>>>>> 218d06a5590b574fc3a6c257200b997baa9ad88e 50 | console.log(arr) -------------------------------------------------------------------------------- /Python/53-Maximum-Subarray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Q: Given an integer array nums, find the contiguous subarray 3 | (containing at least one number) which has the largest sum 4 | and return its sum. 5 | 6 | A subarray is a contiguous part of the array. 7 | 8 | Ex: Input: [2,1,3,-1,2,1,-5,4] -> Output: 6 because [4,-1,2,1] 9 | 10 | Solution 1: DP + Kadane’s Algorithm 11 | Time: O(n) 12 | Space: O(1) 13 | Initialize two variables and set them equal to first value in array 14 | ‘currentSubarray’ will keep returning the count of the current subarray we are currently on 15 | ‘maxSubarray’ will be our final return value, continuously update it whenever we find a bigger subarray 16 | Iterate through array, starting on the 2nd element 17 | for each number, add it to the ‘currentSubarray’ we are building 18 | if ‘currentSubarray’ becomes negative, we know it isn’t worth keeping, so throw it away 19 | currentSubarray = max(i, currentSubarray + i) 20 | update ‘maxSubarray’ everytime we find a new max 21 | maxSubarray = max(maxSubarray, currentSubarray) 22 | return ‘maxSubarray’ 23 | 24 | Notes: 25 | When you see ‘max’ or ‘min’ consider DP. 26 | ''' 27 | 28 | class Solution: 29 | 30 | def maxSubArray(self, nums: List[int]) -> int: 31 | res = nums[0] 32 | 33 | total = 0 34 | for n in nums: 35 | total += n 36 | res = max(res, total) 37 | if total < 0: 38 | total = 0 39 | return res -------------------------------------------------------------------------------- /C++/Deepest-Leaves-Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name: Abdul Ali Khan 3 | * Username: abdulalikhan 4 | * Problem No. 1302 5 | * Deepest Leaves Sum 6 | */ 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 | * }; 17 | */ 18 | class Solution { 19 | private: 20 | int height; 21 | int sum = 0; 22 | public: 23 | int getHeight(TreeNode* root) { 24 | if (root == NULL) 25 | return 0; 26 | int leftHeight = getHeight(root->left); 27 | int rightHeight = getHeight(root->right); 28 | return max(leftHeight, rightHeight)+1; 29 | } 30 | 31 | void sumCalculator(TreeNode* root, int current = 1) { 32 | if (root == NULL) 33 | return; 34 | if (!root->left && !root->right && height == current) 35 | sum += root->val; 36 | sumCalculator(root->left, current+1); 37 | sumCalculator(root->right, current+1); 38 | } 39 | 40 | int deepestLeavesSum(TreeNode* root) { 41 | if (root == NULL) 42 | return 0; 43 | height = getHeight(root); 44 | sumCalculator(root); 45 | return sum; 46 | } 47 | }; -------------------------------------------------------------------------------- /Java/Letter_Combinations_of_a_Phone_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // make list for return. 3 | public ArrayList list = new ArrayList<>(); 4 | // make array for get phone number's characters. 5 | public char[][] arr = { 6 | {'0', '0', '0', '-'}, 7 | {'0', '0', '0', '-'}, 8 | {'a', 'b', 'c', '-'}, 9 | {'d', 'e', 'f', '-'}, 10 | {'g', 'h', 'i', '-'}, 11 | {'j', 'k', 'l', '-'}, 12 | {'m', 'n', 'o', '-'}, 13 | {'p', 'q', 'r', 's'}, 14 | {'t', 'u', 'v', '-'}, 15 | {'w', 'x', 'y', 'z'}, 16 | }; 17 | 18 | // main function 19 | public List letterCombinations(String digits) { 20 | addString(digits, 0, ""); 21 | return list; 22 | } 23 | 24 | // axiom : if input == "", return [] 25 | // if index == digits.length(), add str in list 26 | // else do loop number's character, and function recursion. 27 | public void addString(String digits, int index, String str) { 28 | if(digits.equals("")) return; 29 | if(index == digits.length()) { 30 | list.add(str); 31 | } 32 | else { 33 | for(int i = 0; i < 4; i++) { 34 | int number = Integer.parseInt(digits.charAt(index) + ""); 35 | if(arr[number][i] == '-') continue; 36 | addString(digits, index + 1, str + arr[number][i]); 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Java/Find_First_And_Last_Element_In_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | public static int[] searchRange_bs(int[] nums, int target) { 2 | int[] ans = {-1, -1}; 3 | 4 | if (nums == null || nums.length <= 0) { 5 | return ans; 6 | } 7 | 8 | ans[0] = binarySearchLeft(nums, target); 9 | ans[1] = binarySearchRight(nums, target); 10 | 11 | return ans; 12 | } 13 | 14 | public static int binarySearchLeft(int[] arr, int target) { 15 | if (arr[arr.length - 1] < target) { 16 | return -1; 17 | } 18 | 19 | int left = 0; 20 | int right = arr.length - 1; 21 | while (left < right) { 22 | int mid = left + (right - left) / 2; 23 | if (arr[mid] < target) { 24 | left = mid + 1; 25 | } else { 26 | right = mid; 27 | } 28 | } 29 | 30 | return arr[left] == target ? left : -1; 31 | } 32 | 33 | public static int binarySearchRight(int[] arr, int target) { 34 | if (arr[0] > target) { 35 | return -1; 36 | } 37 | 38 | int left = 0; 39 | int right = arr.length - 1; 40 | while (left < right) { 41 | int mid = left + (right - left + 1) / 2; 42 | if (arr[mid] > target) { 43 | right = mid - 1; 44 | } else { 45 | left = mid; 46 | } 47 | } 48 | 49 | return arr[left] == target ? left : -1; 50 | } 51 | -------------------------------------------------------------------------------- /JS/Groupbykey.js: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD 2 | function GroupByKey(array,key) 3 | { 4 | const tempData = {}; 5 | 6 | for ( var index=0; index>>>>>> 218d06a5590b574fc3a6c257200b997baa9ad88e 62 | console.log(GroupByKey(array,key)) -------------------------------------------------------------------------------- /Python/RomantoInteger.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(s: str) -> int: 3 | result=0 4 | for i in range (0 , len(s)): 5 | #print(i) 6 | if(s[i]=="I"): 7 | result=result+1 8 | elif(s[i]=="V"): 9 | if(s[i-1]=="I" and i!=0): 10 | result=result+3 11 | else: 12 | result=result+5 13 | elif(s[i]=="X"): 14 | if(s[i-1]=="I" and i!=0): 15 | result=result+8 16 | else: 17 | result=result+10 18 | 19 | elif(s[i]=="L"): 20 | if(s[i-1]=="X" and i!=0): 21 | result=result+30 22 | else: 23 | result=result+50 24 | 25 | elif(s[i]=="C"): 26 | if(s[i-1]=="X" and i!=0): 27 | result=result+80 28 | else: 29 | result=result+100 30 | 31 | 32 | elif(s[i]=="D"): 33 | if(s[i-1]=="C" and i!=0): 34 | result=result+300 35 | else: 36 | result=result+500 37 | 38 | elif(s[i]=="M"): 39 | if(s[i-1]=="C" and i!=0): 40 | result=result+800 41 | else: 42 | result=result+1000 43 | return result 44 | 45 | print(Solution.romanToInt("MMMCDXC")) -------------------------------------------------------------------------------- /C++/Merge List .cpp: -------------------------------------------------------------------------------- 1 | // Name: Samsor Rahman 2 | 3 | // Username: samsorrahman 4 | 5 | // Approach: How to merge two linkedlist in iterative way? here is the solution for it. 6 | 7 | class Solution { 8 | public: 9 | ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 10 | 11 | // if list1 happen to be NULL 12 | // we will simply return list2. 13 | if(list1 == NULL) 14 | return list2; 15 | 16 | // if list2 happen to be NULL 17 | // we will simply return list1. 18 | if(list2 == NULL) 19 | return list1; 20 | 21 | ListNode * ptr = list1; 22 | if(list1 -> val > list2 -> val) 23 | { 24 | ptr = list2; 25 | list2 = list2 -> next; 26 | } 27 | else 28 | { 29 | list1 = list1 -> next; 30 | } 31 | ListNode *curr = ptr; 32 | 33 | // till one of the list doesn't reaches NULL 34 | while(list1 && list2) 35 | { 36 | if(list1 -> val < list2 -> val){ 37 | curr->next = list1; 38 | list1 = list1 -> next; 39 | } 40 | else{ 41 | curr->next = list2; 42 | list2 = list2 -> next; 43 | } 44 | curr = curr -> next; 45 | 46 | } 47 | 48 | // adding remaining elements of bigger list. 49 | if(!list1) 50 | curr -> next = list2; 51 | else 52 | curr -> next = list1; 53 | 54 | return ptr; 55 | 56 | } 57 | }; -------------------------------------------------------------------------------- /C++/Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | //Name: Nurshat Fateh Ali 2 | 3 | //Username: nurshatfateh 4 | 5 | //Approach: Simple solution using modified version of binary search 6 | 7 | class Solution { 8 | public: 9 | vector searchRange(vector& nums, int target) { 10 | vectorv; 11 | int s=0; 12 | int e=nums.size()-1; 13 | int m; 14 | int f=-1,l=-1; 15 | while(s<=e) 16 | { 17 | 18 | m=(s+e)/2; 19 | if(target==nums[m]) 20 | { 21 | f=m; 22 | e=m-1; 23 | 24 | 25 | } 26 | else if(target>nums[m]) 27 | { 28 | s=m+1; 29 | } 30 | else if(targetnums[m]) 52 | { 53 | s=m+1; 54 | } 55 | else if(target num; 8 | s.erase(std::remove(s.begin(), s.end(), ' '), s.end()); 9 | char op='+'; 10 | long currentValue=0; 11 | int sum=0,last=0; 12 | if(s.length() == 0) 13 | { 14 | return 0; 15 | } 16 | for(int i=0;i= ord('0') and ord(str[pos]) <= ord('9'): 19 | num = ord(str[pos]) - ord('0') 20 | if result > max_int / 10 or ( result == max_int / 10 and num >= 8): 21 | if sign == -1: 22 | return min_int 23 | return max_int 24 | result = result * 10 + num 25 | pos += 1 26 | return sign * result 27 | 28 | # def myAtoi(self, s): 29 | # #https://leetcode.com/discuss/83626/line-python-solution-eafp-instead-lbyl-easier-logic-beats-24%25 30 | # try: 31 | # s = s.lstrip() + '$' # remove leading spaces and append an end mark 32 | # for i, ch in enumerate(s): 33 | # if not (ch in '+-' or '0' <= ch <= '9'): 34 | # result = int(s[:i]) 35 | # return -2 ** 31 if result < -2 ** 31 else 2 ** 31 - 1 if result > 2 ** 31 - 1 else result 36 | # except: 37 | # return 0 38 | 39 | 40 | if __name__ == '__main__': 41 | # begin 42 | s = Solution() 43 | print s.myAtoi("+-2") 44 | -------------------------------------------------------------------------------- /JS/Groupbykey_Reduce.js: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD 2 | const array=[ 3 | {id:1,name:"Bilal", city:"Lahore"}, 4 | {id:1,name:"Bilal", city:"Lahore"}, 5 | {id:3,name:"Hafsa", city:"Karachi"}, 6 | {id:4,name:"Rehan", city:"Lahore"}, 7 | {id:5,name:"Saqib", city:"Karachi"}, 8 | {id:6,name:"Farhan", city:"Islamabad"} 9 | ]; 10 | const key='city'; 11 | 12 | function GroupByKey(arr,key) { 13 | var tempobj=[]; 14 | arr.reduce((accumulator,currentvalue)=>{ 15 | if(!accumulator[currentvalue[key]]){ 16 | accumulator[currentvalue[key]]=[] 17 | } 18 | accumulator[currentvalue[key]].push(currentvalue) 19 | tempobj=accumulator 20 | return accumulator 21 | },{}); 22 | return tempobj 23 | 24 | } 25 | 26 | console.log(GroupByKey(array,key)) 27 | ======= 28 | const array=[ 29 | {id:1,name:"Bilal", city:"Lahore"}, 30 | {id:1,name:"Bilal", city:"Lahore"}, 31 | {id:3,name:"Hafsa", city:"Karachi"}, 32 | {id:4,name:"Rehan", city:"Lahore"}, 33 | {id:5,name:"Saqib", city:"Karachi"}, 34 | {id:6,name:"Farhan", city:"Islamabad"} 35 | ]; 36 | const key='city'; 37 | 38 | function GroupByKey(arr,key) { 39 | var tempobj=[]; 40 | arr.reduce((accumulator,currentvalue)=>{ 41 | if(!accumulator[currentvalue[key]]){ 42 | accumulator[currentvalue[key]]=[] 43 | } 44 | accumulator[currentvalue[key]].push(currentvalue) 45 | tempobj=accumulator 46 | return accumulator 47 | },{}); 48 | return tempobj 49 | 50 | } 51 | 52 | console.log(GroupByKey(array,key)) 53 | >>>>>>> 218d06a5590b574fc3a6c257200b997baa9ad88e 54 | -------------------------------------------------------------------------------- /Java/RansomNote.java: -------------------------------------------------------------------------------- 1 | // #383 Ransome Note 2 | // https://leetcode.com/problems/ransom-note/description/ 3 | 4 | // Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. 5 | // Each letter in magazine can only be used once in ransomNote. 6 | 7 | // Example 1: 8 | // Input: ransomNote = "a", magazine = "b" 9 | // Output: false 10 | 11 | // Example 2: 12 | // Input: ransomNote = "aa", magazine = "ab" 13 | // Output: false 14 | 15 | // Example 3: 16 | // Input: ransomNote = "aa", magazine = "aab" 17 | // Output: true 18 | 19 | class Solution { 20 | public boolean canConstruct(String ransomNote, String magazine) { 21 | ArrayList al = new ArrayList<>(); 22 | char[] mag = magazine.toCharArray(); 23 | HashMap hm = new HashMap<>(); 24 | for(int i=0;i= p//2: 43 | floor = p - floor 44 | result[floor] += s[i] 45 | return "".join(result) 46 | 47 | 48 | if __name__ == '__main__': 49 | # begin 50 | s = Solution() 51 | print s.convert("PAYPALISHIRING", 3) 52 | -------------------------------------------------------------------------------- /Python/validIPAddress.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validIPAddress(self, queryIP: str) -> str: 3 | com=queryIP.split(".") 4 | com2=queryIP.split(":") 5 | def IPV4(com): 6 | flag=False 7 | for i in com: 8 | if(i.isdigit() and int(i)>=0 and int(i)<=255): 9 | flag=True 10 | if(i=="0" and len(i)>1): 11 | flag=False 12 | break 13 | 14 | else: 15 | flag=False 16 | break 17 | 18 | if(flag==True): 19 | print("IPV4") 20 | else: 21 | print("Neither") 22 | 23 | def IPV6(com): 24 | flag=True 25 | for i in com: 26 | if(len(i)<=4 and len(i)>0): 27 | for j in i: 28 | if(j not in "0123456789abcdefABCDEF"): 29 | flag=False 30 | break 31 | else: 32 | flag=True 33 | else: 34 | print("Neither") 35 | flag=False 36 | break 37 | if(flag==True): 38 | print("IPV6") 39 | else: 40 | print("Neither") 41 | 42 | if(len(com)==4): 43 | return(IPV4(com)) 44 | elif(len(com2)==8): 45 | return(IPV6(com2)) 46 | else: 47 | print("Neither") 48 | 49 | Solution().validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7331") 50 | -------------------------------------------------------------------------------- /C++/remove_special_characters_from_aaray.cpp: -------------------------------------------------------------------------------- 1 | // Name: Shoaib Sabir 2 | // Username: Shoaib019 3 | // Question: remove all special characters from characters array 4 | // Approach: remove_character shifts array to let by one character 5 | // is_special_character checks whether character is special or not 6 | // remove_special_charactes reduce size if last character is special 7 | // and runs loop whenever special character finds in the array it removes 8 | // find special character using is_special_character method and remove 9 | // special charactes using remove_character method 10 | class Solution { 11 | public: 12 | int remove_character(char arr [], char ch, int size){ 13 | int i; 14 | for(i=0; i< size; i++) 15 | { 16 | if(arr[i] == ch) 17 | break; 18 | } 19 | if(i < size) 20 | { 21 | size--; 22 | for(int j=i; j < size; j++) 23 | { 24 | arr[j] = arr[j + 1]; 25 | } 26 | arr[size + 1] = 0; 27 | } 28 | return size; 29 | } 30 | 31 | bool is_special_character(char ch){ 32 | if((!(ch >= 97 && ch <= 122) && !(ch >= 65 && ch <= 90) )) 33 | return true; 34 | else 35 | return false; 36 | } 37 | 38 | int remove_special_charactes(char arr [],int size) { 39 | if(is_special_character(arr[size - 1])) 40 | { 41 | size--; 42 | } 43 | for(int i=0; i< size; i++) 44 | { 45 | if(is_special_character(arr[i])) 46 | { 47 | size = remove_character(arr,arr[i],size); 48 | i--; 49 | } 50 | } 51 | return size; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /JS/NextValue_M2.js: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD 2 | const array=[ 3 | {id:'one',next:"two", value:null}, 4 | {id:'two',next:"three", value:null}, 5 | {id:'three',next: null, value:null} 6 | ]; 7 | var result=[] 8 | function updatevalue(array){ 9 | if(result.length==0){ 10 | for(var i in array){ 11 | if(array[i].next==null){ 12 | result.unshift(array[i]) 13 | array.splice(array[i],1) 14 | } 15 | } 16 | } 17 | for(var j in array){ 18 | if(result[0].id==array[j].next){ 19 | array[j].value=result[0] 20 | result.unshift(array[j]) 21 | array.splice(array[j],1) 22 | updatevalue(array) 23 | break 24 | } 25 | } 26 | 27 | } 28 | updatevalue(array.reverse()) 29 | 30 | ======= 31 | const array=[ 32 | {id:'one',next:"two", value:null}, 33 | {id:'two',next:"three", value:null}, 34 | {id:'three',next: null, value:null} 35 | ]; 36 | var result=[] 37 | function updatevalue(array){ 38 | if(result.length==0){ 39 | for(var i in array){ 40 | if(array[i].next==null){ 41 | result.unshift(array[i]) 42 | array.splice(array[i],1) 43 | } 44 | } 45 | } 46 | for(var j in array){ 47 | if(result[0].id==array[j].next){ 48 | array[j].value=result[0] 49 | result.unshift(array[j]) 50 | array.splice(array[j],1) 51 | updatevalue(array) 52 | break 53 | } 54 | } 55 | 56 | } 57 | updatevalue(array.reverse()) 58 | 59 | >>>>>>> 218d06a5590b574fc3a6c257200b997baa9ad88e 60 | console.log(result) -------------------------------------------------------------------------------- /Python/Binarytree: -------------------------------------------------------------------------------- 1 | class Binarytree: 2 | def _init_(self,data): 3 | self.data = data 4 | self.left = None 5 | self.right = None 6 | 7 | def addChild(self, data): 8 | if data == self.data: 9 | return 10 | 11 | if data < self.data: 12 | if self.left: 13 | self.left.addChild(data) 14 | else: 15 | self.left = Binarytree(data) 16 | else: 17 | if self.right: 18 | self.right.addChild(data) 19 | else: 20 | self.right = Binarytree(data) 21 | 22 | def inorder(self): 23 | element = [ ] 24 | 25 | if self.left: 26 | element += self.left.inorder() 27 | 28 | element.append(self.data) 29 | 30 | if self.right: 31 | element += self.right.inorder() 32 | 33 | return element 34 | 35 | def search(self,val): 36 | if val == self.data: 37 | return True 38 | if val < self.data: 39 | if self.left: 40 | return self.left.search(val) 41 | else: 42 | return False 43 | else: 44 | if self.right: 45 | return self.right.search(val) 46 | else: 47 | return False 48 | 49 | def buildtree(element): 50 | root = Binarytree(element[0]) 51 | for i in range(1,len(element)): 52 | root.addChild(element[i]) 53 | return root 54 | 55 | if _name_ == '_main_': 56 | element = [39, 87, 21, 42, 95, 52, 12] 57 | tree = buildtree(element) 58 | print(tree.inorder()) 59 | print(tree.search(38)) 60 | -------------------------------------------------------------------------------- /Python/Number_of_Steps_to_Reduce_a_Number_to_Zero.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative integer num, return the number of steps to reduce it to zero. 3 | If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. 4 | Example 1: 5 | Input: num = 14 6 | Output: 6 7 | Explanation: 8 | Step 1) 14 is even; divide by 2 and obtain 7. 9 | Step 2) 7 is odd; subtract 1 and obtain 6. 10 | Step 3) 6 is even; divide by 2 and obtain 3. 11 | Step 4) 3 is odd; subtract 1 and obtain 2. 12 | Step 5) 2 is even; divide by 2 and obtain 1. 13 | Step 6) 1 is odd; subtract 1 and obtain 0. 14 | Example 2: 15 | Input: num = 8 16 | Output: 4 17 | Explanation: 18 | Step 1) 8 is even; divide by 2 and obtain 4. 19 | Step 2) 4 is even; divide by 2 and obtain 2. 20 | Step 3) 2 is even; divide by 2 and obtain 1. 21 | Step 4) 1 is odd; subtract 1 and obtain 0. 22 | Example 3: 23 | Input: num = 123 24 | Output: 12 25 | Constraints: 26 | 0 <= num <= 10^6 27 | ''' 28 | 29 | class Solution: 30 | def numberOfSteps (self, num: int) -> int: 31 | steps = 0 32 | while(num > 0): 33 | if(num % 2 == 0): 34 | num = num / 2 35 | steps + =1 36 | else: 37 | num = num - 1 38 | steps += 1 39 | return steps 40 | 41 | # def numberOfSteps (self, num: int) -> int: 42 | # ans = 0 43 | # # check the number of 1 44 | # while num: 45 | # ans += (num & 1) + 1 46 | # num >>= 1 47 | # return ans - 1 48 | 49 | # def numberOfSteps (self, num: int) -> int: 50 | # ones, zeros = self.bitCount(num) 51 | # if ones == 0: 52 | # return 0 53 | # else: 54 | # return 2 * ones + zeros - 1 55 | -------------------------------------------------------------------------------- /table_of_content.md: -------------------------------------------------------------------------------- 1 | LeetCode 2 | ======== 3 | 4 | ### LeetCode Algorithm 5 | 6 | (Notes: "🔒" means you need to 1 to 1 mentorship for Algorithm and Analysis) 7 | 8 | | # | Title | Solution | Difficulty | Method#1 | Method#2 | 9 | |---| ----- | -------- | ---------- | -------- | -------- | 10 | |2239|[Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Python](/Python/reverseint.py)|Medium| ✔️ | ✔️| 11 | |468|[Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [Python](./validIPAddress.py)|Medium| ✔️ | ✔️| 12 | |1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](./algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp), [Java](./algorithms/java/src/LargestNumberAfterMutatingSubtring/largestNumberAfterMutatingSubstring.java)|Medium|✔️ | ❌| 13 | |1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](./algorithms/cpp/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy|✔️ | ❌| 14 | 15 |

16 | 17 | 18 | 19 | 20 |

21 | -------------------------------------------------------------------------------- /JS/NextValue.js: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD 2 | const array=[ 3 | {id:'one',next:"two", value:null}, 4 | {id:'two',next:"three", value:null}, 5 | {id:'three',next: "four", value:null}, 6 | {id:'four',next: null, value:null} 7 | ]; 8 | var result=[] 9 | 10 | function updatearray(arr){ 11 | for(var i=arr.length-1; i>-1;i--){ 12 | updatevalue(arr[i]) 13 | } 14 | } 15 | 16 | function updatevalue(element){ 17 | if(element.next==null){ 18 | return (result.unshift(element)) 19 | } 20 | else{ 21 | for(var j in array){ 22 | if(result[0].id==array[j].next){ 23 | array[j].value=result[0] 24 | result.unshift(array[j]) 25 | break 26 | } 27 | } 28 | } 29 | } 30 | updatearray(array) 31 | result=JSON.stringify(result); 32 | console.log(result) 33 | ======= 34 | const array=[ 35 | {id:'one',next:"two", value:null}, 36 | {id:'two',next:"three", value:null}, 37 | {id:'three',next: "four", value:null}, 38 | {id:'four',next: null, value:null} 39 | ]; 40 | var result=[] 41 | 42 | function updatearray(arr){ 43 | for(var i=arr.length-1; i>-1;i--){ 44 | updatevalue(arr[i]) 45 | } 46 | } 47 | 48 | function updatevalue(element){ 49 | if(element.next==null){ 50 | return (result.unshift(element)) 51 | } 52 | else{ 53 | for(var j in array){ 54 | if(result[0].id==array[j].next){ 55 | array[j].value=result[0] 56 | result.unshift(array[j]) 57 | break 58 | } 59 | } 60 | } 61 | } 62 | updatearray(array) 63 | result=JSON.stringify(result); 64 | console.log(result) 65 | >>>>>>> 218d06a5590b574fc3a6c257200b997baa9ad88e 66 | // console.log(result[0].value) -------------------------------------------------------------------------------- /C++/valid parenthesis Draw Run program.cpp: -------------------------------------------------------------------------------- 1 | Name: Samsor Rahman 2 | username: samsorrahman 3 | Approach: at the very first step traverse the all stack and push the opening brackets into the stack 4 | and then check it the closing bracket is comming then check if the top is matching(opening bracket) 5 | pop the stack. 6 | 7 | 8 | #include 9 | using namespace std; 10 | bool isValid(string s){ 11 | int n = s.size(); 12 | stack st; 13 | bool ans= true; 14 | for(int i=0; i maximum integer, arr[1] -> minimum integer 13 | int[] arr = {100001, -10}; 14 | int s = 0; 15 | int e = nums.length - 1; 16 | 17 | // find minimum index in nums with Binary Search alogorithm 18 | while (s <= e) { 19 | 20 | int mid = (s + e) / 2; 21 | 22 | if(nums[mid] > target) { 23 | e = mid - 1; 24 | } 25 | else if(nums[mid] <= target) { 26 | if(nums[mid] == target) { 27 | arr[0] = Math.min(arr[0], mid); 28 | arr[1] = Math.max(arr[1], mid); 29 | } 30 | s = mid + 1; 31 | } 32 | } 33 | 34 | s = 0; 35 | e = nums.length - 1; 36 | 37 | // find maximum index in nums with Binary Search alogorithm 38 | while(s <= e) { 39 | int mid = (s + e) / 2; 40 | 41 | if(nums[mid] >= target) { 42 | if(nums[mid] == target) { 43 | arr[0] = Math.min(arr[0], mid); 44 | arr[1] = Math.max(arr[1], mid); 45 | } 46 | e = mid - 1; 47 | } 48 | else if(nums[mid] < target) { 49 | s = mid + 1; 50 | } 51 | } 52 | 53 | // if arr data is initial data, set -1. 54 | if(arr[0] == 100001) arr[0] = -1; 55 | if(arr[1] == -10) arr[1] = -1; 56 | 57 | return arr; 58 | } 59 | } -------------------------------------------------------------------------------- /Python/121-Best-Time-to-Buy-and-Sell-Stock.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Q: You are given an array of prices where prices[i] is the 3 | price of a given stock on the ith day. 4 | 5 | You want to maximize your profit by choosing a single day to buy 6 | one stock and choosing a different day in the future to sell that stock. 7 | 8 | Return the maximum profit you can achieve from this transaction. 9 | If you cannot achieve any profit, return 0. 10 | 11 | Ex: Input: prices = [7,1,5,3,6,4] -> Output: 5 12 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 13 | 14 | Solution 1: One Pass/Track buy_index 15 | Time: O(n) 16 | Space: O(1) 17 | Initialize two variables and set them to 0 18 | buy_index -> track the day we’re going to buy on (smallest cost) 19 | profit -> profit = buy - sell 20 | Iterate through the array either using enumerate or in range 21 | We need the index 22 | for i, p in enumerate(prices) 23 | If currentPrice is less than the prices[buy_index], update this to be our lowest price 24 | if p < prices[buy_index] 25 | buy_index = i 26 | Update profit 27 | profit = max(p - prices[buy_index], profit) 28 | return profit 29 | ''' 30 | class Solution: 31 | # solution 1: track buy index 32 | def maxProfit(self, prices: List[int]) -> int: 33 | buy_day = 0 34 | profit = 0 35 | for day, price in enumerate(prices): 36 | if prices[buy_day] > prices[day]: 37 | buy_day = day 38 | 39 | profit = max(prices[day] - prices[buy_day], profit) 40 | return profit 41 | 42 | # solution 2: sliding window 43 | def maxProfit(self, prices: List[int]) -> int: 44 | # l = buy_index, r = sell_index basically 45 | l, r = 0, 1 46 | maxP = 0 47 | 48 | while r < len(prices): 49 | # if our buy_index price is less than our sell_index price, we have profit 50 | if prices[l] < prices[r]: 51 | profit = prices[r] - prices[l] 52 | maxP = max(maxP, profit) 53 | # no profit, update left so we know at this index, everything before was not profit 54 | else: 55 | l = r 56 | r += 1 57 | return maxP -------------------------------------------------------------------------------- /Python/15-3sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 15. 3Sum 3 | Q: Given an integer array nums, 4 | return all the triplets [nums[i], nums[j], nums[k]] such 5 | that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 6 | 7 | Notice that the solution set must not contain duplicate triplets. 8 | 9 | Ex: Input: nums = [-1,0,1,2,-1,-4] -> Output: [[-1,-1,2],[-1,0,1]] 10 | nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. 11 | nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. 12 | nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. 13 | The distinct triplets are [-1,0,1] and [-1,-1,2]. 14 | Notice that the order of the output and the order of the triplets does not matter. 15 | 16 | 17 | Solution 1 [Optimal]: Two Pointers 18 | Time: O(n^2) 19 | Space: O(logn) or O(n) -> depends on sort 20 | ''' 21 | class Solution: 22 | def threeSum(self, nums: List[int]) -> List[List[int]]: 23 | res = [] 24 | nums.sort() 25 | for i in range(len(nums)): 26 | if nums[i] > 0: 27 | break 28 | if i == 0 or nums[i - 1] != nums[i]: 29 | self.twoSumII(nums, i, res) 30 | return res 31 | 32 | def twoSumII(self, nums: List[int], i: int, res: List[List[int]]): 33 | lo, hi = i + 1, len(nums) - 1 34 | while (lo < hi): 35 | sum = nums[i] + nums[lo] + nums[hi] 36 | if sum < 0: 37 | lo += 1 38 | elif sum > 0: 39 | hi -= 1 40 | else: 41 | res.append([nums[i], nums[lo], nums[hi]]) 42 | lo += 1 43 | hi -= 1 44 | while lo < hi and nums[lo] == nums[lo - 1]: 45 | lo += 1 46 | 47 | 48 | class Solution: 49 | def threeSum(self, nums: List[int]) -> List[List[int]]: 50 | res = [] 51 | nums.sort() 52 | for i in range(len(nums)): 53 | if nums[i] > 0: 54 | break 55 | if i == 0 or nums[i - 1] != nums[i]: 56 | self.twoSum(nums, i, res) 57 | return res 58 | 59 | def twoSum(self, nums: List[int], i: int, res: List[List[int]]): 60 | seen = set() 61 | j = i + 1 62 | while j < len(nums): 63 | complement = -nums[i] - nums[j] 64 | if complement in seen: 65 | res.append([nums[i], nums[j], complement]) 66 | while j + 1 < len(nums) and nums[j] == nums[j + 1]: 67 | j += 1 68 | seen.add(nums[j]) 69 | j += 1 -------------------------------------------------------------------------------- /Python/8 Puzzle Game with BFS (Breadth First Search).py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | # Required Goal 4 | Goal = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] 5 | Row, Col = (3, 3) 6 | # Initialize Empty Board 7 | Box = [[0]*Col]*Row 8 | 9 | # Enter Your Board Shape 10 | Board = [[1, 2, 3], [0, 5, 6], [4,7,8]] 11 | Sign = [] 12 | 13 | # ==================================== 14 | 15 | 16 | def FreeSlot(TempBoard): 17 | for i in range(Row): 18 | for j in range(Col): 19 | if (TempBoard[i][j] == 0): 20 | return i, j 21 | 22 | 23 | def MoveUp(TempBoard): 24 | I1, I2 = FreeSlot(TempBoard) 25 | 26 | I3 = I1-1 27 | I4 = I2-0 28 | 29 | if I3 >= 0 and I4 >= 0: 30 | NewBoard = copy.deepcopy(TempBoard) 31 | NewBoard[I1][I2] = TempBoard[I3][I4] 32 | NewBoard[I3][I4] = 0 33 | 34 | return NewBoard 35 | else: 36 | return False 37 | 38 | 39 | def MoveDown(TempBoard): 40 | I1, I2 = FreeSlot(TempBoard) 41 | 42 | I3 = I1+1 43 | I4 = I2+0 44 | 45 | if I3 < 3 and I4 < 3: 46 | NewBoard = copy.deepcopy(TempBoard) 47 | NewBoard[I1][I2] = TempBoard[I3][I4] 48 | NewBoard[I3][I4] = 0 49 | 50 | return NewBoard 51 | else: 52 | return False 53 | 54 | 55 | def MoveLeft(TempBoard): 56 | I1, I2 = FreeSlot(TempBoard) 57 | 58 | I3 = I1-0 59 | I4 = I2-1 60 | 61 | if I3 >= 0 and I4 >= 0: 62 | NewBoard = copy.deepcopy(TempBoard) 63 | NewBoard[I1][I2] = TempBoard[I3][I4] 64 | NewBoard[I3][I4] = 0 65 | 66 | return NewBoard 67 | else: 68 | return False 69 | 70 | 71 | def MoveRight(TempBoard): 72 | I1, I2 = FreeSlot(TempBoard) 73 | 74 | I3 = I1+0 75 | I4 = I2+1 76 | 77 | if I3 < 3 and I4 < 3: 78 | NewBoard = copy.deepcopy(TempBoard) 79 | NewBoard[I1][I2] = TempBoard[I3][I4] 80 | NewBoard[I3][I4] = 0 81 | 82 | return NewBoard 83 | else: 84 | return False 85 | 86 | 87 | # Game Start Here 88 | 89 | def StartGame(Board): 90 | 91 | Sign.append(Board) 92 | 93 | while Goal not in Sign: 94 | for I in range(len(Sign)): 95 | Beetle = MoveUp(Sign[I]) 96 | if (Beetle): 97 | if Beetle not in Sign: 98 | Sign.append(Beetle) 99 | if Goal in Sign: 100 | break 101 | 102 | Beetle2 = MoveDown(Sign[I]) 103 | if (Beetle2): 104 | if Beetle2 not in Sign: 105 | Sign.append(Beetle2) 106 | if Goal in Sign: 107 | break 108 | 109 | Beetle3 = MoveLeft(Sign[I]) 110 | if (Beetle3): 111 | if Beetle3 not in Sign: 112 | Sign.append(Beetle3) 113 | if Goal in Sign: 114 | break 115 | Beetle4 = MoveRight(Sign[I]) 116 | if (Beetle4): 117 | if Beetle4 not in Sign: 118 | Sign.append(Beetle4) 119 | if Goal in Sign: 120 | break 121 | # Sign.append(Goal) 122 | 123 | 124 | StartGame(Board) 125 | 126 | for I in Sign: 127 | print(I) 128 | print("=========") 129 | -------------------------------------------------------------------------------- /Python/matrix.py: -------------------------------------------------------------------------------- 1 | # Time: O(m * n) 2 | # Space: O(1) 3 | 4 | # dp solution 5 | class Solution(object): 6 | def updateMatrix(self, matrix): 7 | """ 8 | :type matrix: List[List[int]] 9 | :rtype: List[List[int]] 10 | """ 11 | for i in xrange(len(matrix)): 12 | for j in xrange(len(matrix[i])): 13 | if not matrix[i][j]: 14 | continue 15 | matrix[i][j] = float("inf") 16 | if i > 0: 17 | matrix[i][j] = min(matrix[i][j], matrix[i-1][j]+1) 18 | if j > 0: 19 | matrix[i][j] = min(matrix[i][j], matrix[i][j-1]+1) 20 | for i in reversed(xrange(len(matrix))): 21 | for j in reversed(xrange(len(matrix[i]))): 22 | if not matrix[i][j]: 23 | continue 24 | if i < len(matrix)-1: 25 | matrix[i][j] = min(matrix[i][j], matrix[i+1][j]+1) 26 | if j < len(matrix[i])-1: 27 | matrix[i][j] = min(matrix[i][j], matrix[i][j+1]+1) 28 | return matrix 29 | 30 | 31 | # Time: O(m * n) 32 | # Space: O(m * n) 33 | # dp solution 34 | class Solution2(object): 35 | def updateMatrix(self, matrix): 36 | """ 37 | :type matrix: List[List[int]] 38 | :rtype: List[List[int]] 39 | """ 40 | dp = [[float("inf")]*len(matrix[0]) for _ in xrange(len(matrix))] 41 | for i in xrange(len(matrix)): 42 | for j in xrange(len(matrix[i])): 43 | if matrix[i][j] == 0: 44 | dp[i][j] = 0 45 | else: 46 | if i > 0: 47 | dp[i][j] = min(dp[i][j], dp[i-1][j]+1) 48 | if j > 0: 49 | dp[i][j] = min(dp[i][j], dp[i][j-1]+1) 50 | for i in reversed(xrange(len(matrix))): 51 | for j in reversed(xrange(len(matrix[i]))): 52 | if matrix[i][j] == 0: 53 | dp[i][j] = 0 54 | else: 55 | if i < len(matrix)-1: 56 | dp[i][j] = min(dp[i][j], dp[i+1][j]+1) 57 | if j < len(matrix[i])-1: 58 | dp[i][j] = min(dp[i][j], dp[i][j+1]+1) 59 | return dp 60 | 61 | 62 | # Time: O(m * n) 63 | # Space: O(m * n) 64 | import collections 65 | 66 | 67 | class Solution3(object): 68 | def updateMatrix(self, matrix): 69 | """ 70 | :type matrix: List[List[int]] 71 | :rtype: List[List[int]] 72 | """ 73 | queue = collections.deque() 74 | for i in xrange(len(matrix)): 75 | for j in xrange(len(matrix[0])): 76 | if matrix[i][j] == 0: 77 | queue.append((i, j)) 78 | else: 79 | matrix[i][j] = float("inf") 80 | 81 | dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] 82 | while queue: 83 | cell = queue.popleft() 84 | for dir in dirs: 85 | i, j = cell[0]+dir[0], cell[1]+dir[1] 86 | if not (0 <= i < len(matrix) and 87 | 0 <= j < len(matrix[0]) and 88 | matrix[i][j] > matrix[cell[0]][cell[1]]+1): 89 | continue 90 | queue.append((i, j)) 91 | matrix[i][j] = matrix[cell[0]][cell[1]]+1 92 | 93 | return matrix 94 | -------------------------------------------------------------------------------- /Python/8 Queen problem by genetic algorithm.py: -------------------------------------------------------------------------------- 1 | import random 2 | list1=[4,3,1,4] 3 | list2=[3,2,1,2] 4 | list3=[1,2,3,4] 5 | list4=[2,2,1,2] 6 | board1=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] 7 | board2=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] 8 | board3=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] 9 | board4=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] 10 | indexes=[] 11 | sort=[] 12 | pairs=[] 13 | qno=0 14 | def Board(board): 15 | 16 | print("8 queen problem") 17 | for i in range(len(board)): 18 | for j in range(len(board)): 19 | print(board[i][j],end=" ") 20 | print("\n") 21 | def fitness(board,list1): 22 | for i in range(0,4): 23 | x=list1[i] 24 | board[x-1][i]=i+1 25 | for i in range(len(board)): 26 | for j in range(len(board)): 27 | print(board[i][j],end=" ") 28 | print("\n") 29 | for i in range(0,4): 30 | indexes.append((list1[i]-1,i)) 31 | print(indexes[i]) 32 | def IsAttack(indexes,qno, board): 33 | attack=0 34 | count=0 35 | n=0 36 | m=0 37 | i,j=indexes[qno] 38 | n=i 39 | m=0 40 | while m<4: 41 | if (n,m) in indexes and sorted((qno,board[n][m])) not in pairs: 42 | count=count+1 43 | pairs.append(sorted((qno,board[n][m]))) 44 | m=m+1 45 | 46 | n=i+1 47 | m=j+1 48 | while n<4 and m<4: #lower right 49 | if (n,m) in indexes and sorted((qno,board[n][m])) not in pairs: 50 | count=count+1 51 | pairs.append(sorted((qno,board[n][m]))) 52 | n+=1 53 | m+=1 54 | n=i-1 55 | m=j+1 56 | while m<4 and n>=0: #upper right 57 | if (n,m) in indexes and sorted((qno,board[n][m])) not in pairs: 58 | count=count+1 59 | pairs.append(sorted((qno,board[n][m]))) 60 | n-=1 61 | m+=1 62 | if count!=0: 63 | count=count-1 64 | print("count= ",count) 65 | attack=count 66 | return attack 67 | def crossover(list1, list2): 68 | 69 | newl1=list1[:] 70 | list1[2]=list2[2] 71 | list1[3]=list2[3] 72 | list2[2]=newl1[2] 73 | list2[3]=newl1[3] 74 | print("list1= ",list1) 75 | print("list2= ",list2) 76 | 77 | 78 | 79 | 80 | def mutate(list1): 81 | n=len(list1) 82 | c=random.randint(0,n-1) 83 | m=random.randint(0, n-1) 84 | list1[c]=m 85 | print("After mutation list is: ", list1) 86 | 87 | 88 | 89 | 90 | 91 | 92 | Board(board1) 93 | while 1: 94 | fitness(board1,list1) 95 | a=IsAttack(indexes,0,board1) 96 | b=IsAttack(indexes,1,board1) 97 | c=IsAttack(indexes,2,board1) 98 | d=IsAttack(indexes,3,board1) 99 | no_attack=6-(a+b+c+d) 100 | if no_attack==6: 101 | break 102 | print("non_attack= ",no_attack) 103 | print("\n") 104 | no_attack=0 105 | indexes=[] 106 | pairs=[] 107 | fitness(board2,list2) 108 | a=IsAttack(indexes,0,board2) 109 | b=IsAttack(indexes,1,board2) 110 | c=IsAttack(indexes,2,board2) 111 | d=IsAttack(indexes,3,board3) 112 | no_attack=6-(a+b+c+d) 113 | if no_attack==6: 114 | break 115 | print("non_attack= ",no_attack) 116 | print("\n") 117 | no_attack=0 118 | indexes=[] 119 | pairs=[] 120 | fitness(board3,list3) 121 | a=IsAttack(indexes,0,board3) 122 | b=IsAttack(indexes,1,board3) 123 | c=IsAttack(indexes,2,board3) 124 | d=IsAttack(indexes,3,board3) 125 | no_attack=6-(a+b+c+d) 126 | if no_attack==6: 127 | break 128 | print("non_attack= ",no_attack) 129 | print("\n") 130 | no_attack=0 131 | indexes=[] 132 | pairs=[] 133 | fitness(board4,list4) 134 | a=IsAttack(indexes,0,board4) 135 | b=IsAttack(indexes,1,board4) 136 | c=IsAttack(indexes,2,board4) 137 | d=IsAttack(indexes,3,board4) 138 | no_attack=6-(a+b+c+d) 139 | if no_attack==6: 140 | break 141 | print("non_attack= ",no_attack) 142 | print("\n") 143 | no_attack=0 144 | crossover(list1, list2) 145 | crossover(list3, list4) 146 | mutate(list1) 147 | mutate(list2) 148 | mutate(list3) 149 | mutate(list4) 150 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | 4 | 5 |

6 | 7 |

Hacktoberfest 2022 🎉

8 | 9 | # Note 10 | ```py 11 | ''' 12 | Always try to make more then 4 pull requests. 13 | Let's assume you have made only 4 pull request to different projects. 14 | but one project is excluded from hackoctoberfest event. 15 | Then your pull request will not be counted and you will just have 3 valid pull requests. 16 | If this happens then you will not get any swags or t-shirt. 17 | ''' 18 | ``` 19 | 20 | ### 🗣 Let's COntribute to Open Sourse 🔥. 21 | 📢 **This repository aims to help beginners 🤔 with their first successful Pull Request and Open Source Contribution.** 22 | 23 |
24 | 25 | ## ⏳ Steps to Follow : 26 | 27 | - [X] **Register for [Hacktoberfest](https://hacktoberfest.digitalocean.com/) and get started to make your first PR.** 28 | - [X] **Make 4 valid PRs during the period of (1st - 31st) October to earn cool swags.** 29 | 30 |
31 | 32 | ## ❗ Contribution Rules : 33 | 34 | * **You can Solve any Leetcode problem in any programming languages in the related Folder's,If language folder not exist then first create it and add your code in it but your program must be unique.** 35 | * **The pull requests must contain commits made by yourself.** 36 | * **The Commit message must contain Leetcode problem number** 37 | * **Repeated codes will not be merged.** 38 |
39 | 40 | ## 🌎 Steps to contribute: 41 | 1. (Optional) If git is not install in your Laptop/PC: 42 | 1. Download Git from [here](https://git-scm.com/downloads) and then Install it. 43 | 2. Run your Git Bash, then copy and write the following Commands to Configure your git with your Github Account. (Required) 44 | ```sh 45 | git config --global user.name "your_username" 46 | ``` 47 | 3. Then Copy and paste the following command with your Github Email and run. 48 | ```sh 49 | git config --global user.email "your_email_address" 50 | ``` 51 | 4. You are Good to go👌👍. 52 | 2. Fork this repository by clicking on the top right corner where it is written `Fork`. 53 | 3. Now for Cloning the repository into you PC, copy the URL in the address bar and use the following command. 54 | ```sh 55 | git clone url_you_just_copied 56 | ``` 57 | 4. Now again open git bash in the directory you just clone the repository and execute the following commands replacing username with your GitHub username. 58 | ```sh 59 | git checkout -b username 60 | ``` 61 | 5. Open this cloned repository in your preferred code editor. 62 | 6. Go to the related Language Folder. Copy and paste following comments at the Top of your program and fill the information✌. 63 | ```md 64 | Name: Here goes your name 65 | 66 | Username: Here goes your GitHub username 67 | 68 | Approach: It should be concise your solution approach to solve the problem 69 | ``` 70 | 7. Once you have done all this, commit your changes to GitHub. You can do this with the following commands. Make sure you execute them in the precise order one after another in your terminal. 71 | ```sh 72 | # copy and paste the following in the terminal 73 | git add . 74 | # copy and paste the following in the terminal after you have executed the previous command 75 | git commit -m "hacktoberfest contribution" 76 | # copy and paste the following in the terminal after you have executed the previous command 77 | git push -u origin your_github_username 78 | ``` 79 | 8. Now open the forked repository on your GitHub. You will see a yellow box at the top telling you that some changes are pushed. You will also see a button called Compare & pull request. Click on it. (Note: if yellow box doesn't appear then wait for Half an hour, it will appear.) 80 | 9. Now add a title, some description and you have opened a pull request in this repository💖. 81 | 82 | ---------------------------------------------------------- 83 | 84 | ###

Show some ❤ by hitting the ⭐ button

85 | 86 | ---------------------------------------------------------- 87 | 88 | ## Contributors ✨ 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /Python/hangman.py: -------------------------------------------------------------------------------- 1 | # This is a word game 2 | import random 3 | 4 | 5 | def print_scaffold(guesses, wd): # prints the scaffold 6 | if (guesses == 0): 7 | print "_________" 8 | print "| |" 9 | print "|" 10 | print "|" 11 | print "|" 12 | print "|" 13 | print "|________" 14 | elif (guesses == 1): 15 | print "_________" 16 | print "| |" 17 | print "| O" 18 | print "|" 19 | print "|" 20 | print "|" 21 | print "|________" 22 | elif (guesses == 2): 23 | print "_________" 24 | print "| |" 25 | print "| O" 26 | print "| |" 27 | print "| |" 28 | print "|" 29 | print "|________" 30 | elif (guesses == 3): 31 | print "_________" 32 | print "| |" 33 | print "| O" 34 | print "| \|" 35 | print "| |" 36 | print "|" 37 | print "|________" 38 | elif (guesses == 4): 39 | print "_________" 40 | print "| |" 41 | print "| O" 42 | print "| \|/" 43 | print "| |" 44 | print "|" 45 | print "|________" 46 | elif (guesses == 5): 47 | print "_________" 48 | print "| |" 49 | print "| O" 50 | print "| \|/" 51 | print "| |" 52 | print "| / " 53 | print "|________" 54 | elif (guesses == 6): 55 | print "_________" 56 | print "| |" 57 | print "| O" 58 | print "| \|/" 59 | print "| |" 60 | print "| / \ " 61 | print "|________" 62 | print "\n" 63 | print "The word was %s." %wd 64 | print "\n" 65 | print "\nYOU LOSE! TRY AGAIN!" 66 | print "\nWould you like to play again, type 1 for yes or 2 for no?" 67 | again = str(raw_input("> ")) 68 | again = again.lower() 69 | if again == "1": 70 | hangMan() 71 | return 72 | 73 | def selectWord(): 74 | file = open('FREQ') 75 | words = file.readlines() 76 | myword = 'a' 77 | while len(myword) < 4: # makes sure word is at least 4 letters long 78 | myword = random.choice(words) 79 | myword = str(myword).strip('[]') 80 | myword = str(myword).strip("''") 81 | myword = str(myword).strip("\n") 82 | myword = str(myword).strip("\r") 83 | myword = myword.lower() 84 | return myword 85 | 86 | 87 | def hangMan(): 88 | guesses = 0 89 | word = selectWord() 90 | word_list = list(word) 91 | blanks = "_"*len(word) 92 | blanks_list = list(blanks) 93 | new_blanks_list = list(blanks) 94 | guess_list = [] 95 | 96 | print "Let's play hangman!\n" 97 | print_scaffold(guesses, word) 98 | print "\n" 99 | print "" + ' '.join(blanks_list) 100 | print "\n" 101 | print "Guess a letter.\n" 102 | 103 | while guesses < 6: 104 | 105 | guess = str(raw_input("> ")) 106 | guess = guess.lower() 107 | 108 | if len(guess) > 1: 109 | print "Stop cheating! Enter one letter at time." 110 | elif guess == "": 111 | print "Don't you want to play? Enter one letter at a time." 112 | elif guess in guess_list: 113 | print "You already guessed that letter! Here is what you've guessed:" 114 | print ' '.join(guess_list) 115 | else: 116 | guess_list.append(guess) 117 | i = 0 118 | while i < len(word): 119 | if guess == word[i]: 120 | new_blanks_list[i] = word_list[i] 121 | i = i+1 122 | 123 | if new_blanks_list == blanks_list: 124 | print "Your letter isn't here." 125 | guesses = guesses + 1 126 | print_scaffold(guesses, word) 127 | 128 | if guesses < 6: 129 | print "Guess again." 130 | print ' '.join(blanks_list) 131 | 132 | elif word_list != blanks_list: 133 | 134 | blanks_list = new_blanks_list[:] 135 | print ' '.join(blanks_list) 136 | 137 | if word_list == blanks_list: 138 | print "\nYOU WIN! Here is your prize:" 139 | print "\n" 140 | print "Would you like to play again?" 141 | print "Type 1 for yes or 2 for no." 142 | again = str(raw_input("> ")) 143 | if again == "1": 144 | hangMan() 145 | quit() 146 | 147 | else: 148 | print "Great guess! Guess another!" 149 | 150 | hangMan() 151 | --------------------------------------------------------------------------------