diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..adea12c --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/PYTHON +output.exe \ No newline at end of file diff --git a/ARRAYS/2d_array.py b/ARRAYS/2d_array.py new file mode 100644 index 0000000..b1535c3 --- /dev/null +++ b/ARRAYS/2d_array.py @@ -0,0 +1,38 @@ +# Binary Search in 2D array +arr = [[1,4,8,13],[16,19,20,25],[28,30,33,37]] +target = 370 + +## optimized approach = O(log(m*n)) +def binary_search_2d(arr,target): + # number of rows + m = len(arr) + if m==0: + return False + # number of colmns + n = len(arr[0]) + left,right=0,(m*n)-1 + # binary search implementation + while left <= right: + mid = left + (right-left)//2 + # row_number = mid // n + # col_number = mid % n + mid_element = arr[mid//n][mid%n] + if target==mid_element: + return True + elif target < mid_element: + right = mid - 1 + else: + left = mid + 1 + return False +print(binary_search_2d(arr,target)) + +## brute force approach = O(m*n) +def linear_search_2d(arr,target): + if len(arr)==0: + return False + for row in range(len(arr)): + for col in range(len(arr[0])): + if arr[row][col] == target: + return True + return False +print(linear_search_2d(arr,target)) diff --git a/ARRAYS/all_subarray.py b/ARRAYS/all_subarray.py new file mode 100644 index 0000000..5c01311 --- /dev/null +++ b/ARRAYS/all_subarray.py @@ -0,0 +1,5 @@ +# print all sub arrays of give array + +arr = [89,34,12,9,3,42,99] +def print_subarray(arr): + pass \ No newline at end of file diff --git a/ARRAYS/bad_version.py b/ARRAYS/bad_version.py new file mode 100644 index 0000000..63d5b69 --- /dev/null +++ b/ARRAYS/bad_version.py @@ -0,0 +1,30 @@ +''' +You are a product manager and currently leading a team to develop a new product. +Unfortunately, the latest version of your product fails the quality check. Since each +version is developed based on the previous version, all the versions after a bad version +are also bad. Suppose you have n version and you want to find out the first bad one, +which causes all the following ones to be bad. Also, talk about the time complexity of +your code. +Test Cases: +Input: [0,0,0,1,1,1,1,1,1] +Output: 3 +Explanation: 0 indicates a good version and 1 indicates a bad version. So, the index of +the first 1 is at 3. Thus, the output is 3 +''' +arr = [0,0,0,0,1,1,1,1,1] + +left,right=0,len(arr)-1 +def first_bad_version(arr,left,right): + mid = left + (right-left)//2 + while left <= right: + if arr[mid]==1: + if arr[mid-1]==1: + return first_bad_version(arr,left,mid-1) + return mid + elif arr[mid]!=1: + if arr[mid+1]!=1: + return first_bad_version(arr,mid+1,right) + return mid+1 + return -1 + +print(first_bad_version(arr,left,right)) diff --git a/ARRAYS/buy_and_sell.py b/ARRAYS/buy_and_sell.py new file mode 100644 index 0000000..84b605e --- /dev/null +++ b/ARRAYS/buy_and_sell.py @@ -0,0 +1,19 @@ + +# Best time to buy and sell the stocks + +prices = [7,1,4,6,2,8,10] + +def find_max_profit(prices): + if not prices: + return 0 + min_price = float('inf') + max_profit = 0 + for price in prices: + if price < min_price: + min_price = price + elif price - min_price > max_profit: + max_profit = price - min_price + return max_profit + + +print(find_max_profit(prices)) \ No newline at end of file diff --git a/ARRAYS/count_most_repeated.py b/ARRAYS/count_most_repeated.py new file mode 100644 index 0000000..abdaa5c --- /dev/null +++ b/ARRAYS/count_most_repeated.py @@ -0,0 +1,25 @@ +from collections import Counter + +nums = [1, 2, 3, 4, 1, 2, 2, 3, 42, 3, 4, 2, 3, 3] +def count_most_repeated(nums): + hash = {} + for item in nums: + if item in hash: + hash[item] += 1 + else: + hash[item] = 1 + + ans, max_count = 0, 0 + for key, value in hash.items(): + if value > max_count: + max_count = value + ans = key + return [ans, max_count] + +def count_most_repeated2(nums): + count = Counter(nums) + most_common = count.most_common(1)[0] + return [most_common[0], most_common[1]] + +print(count_most_repeated(nums)) +print(count_most_repeated2(nums)) diff --git a/ARRAYS/find_student.py b/ARRAYS/find_student.py new file mode 100644 index 0000000..1fa4803 --- /dev/null +++ b/ARRAYS/find_student.py @@ -0,0 +1,8 @@ +students = ["Abhi", "Ankit", "Aman", "Rohan"] +def find_student(students, name): + if name in students: + return f"Student {name} is present in the list" + else: + return f"Student {name} is not present in the list" + +print(find_student(students, "Rahul")) diff --git a/ARRAYS/half_zero.py b/ARRAYS/half_zero.py new file mode 100644 index 0000000..f9f2089 --- /dev/null +++ b/ARRAYS/half_zero.py @@ -0,0 +1,29 @@ +# Find the first occurrence of zero. Size of array is given. (Facebook Technical Round) +arr = [1,90,23,14,45,76,88,0,0,0,0,0,0,0,0,0,0] +n=len(arr) # 17 + +# First Approach = O(n) +def first_zero_serach1(arr): + for i in range(len(arr)): + if arr[i] == 0: + return i + return -1 +# print(first_zero_serach1(arr)) + +# Second Approach = O(logn) +start,end=0,n-1 +def first_zero_serach2(arr,start,end): + mid = start + (end - start)//2 + while start <= end: + if arr[mid] == 0: + if arr[mid-1]==0: + return first_zero_serach2(arr,start,mid-1) + return mid + elif arr[mid] != 0: + if arr[mid+1]==0: + return mid+1 + return first_zero_serach2(arr,mid+1,end) + return -1 +print(first_zero_serach2(arr,start,end)) + + diff --git a/ARRAYS/min_and_max.cpp b/ARRAYS/min_and_max.cpp new file mode 100644 index 0000000..551e088 --- /dev/null +++ b/ARRAYS/min_and_max.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; +int min_value(int arr[], int n){ + int ans=INT_MAX; + for (int i = 0; i < n; i++) + { + if(arr[i]ans){ + ans=arr[i]; + } + } + return(ans); +} +int main(){ + int arr[5] = {3,10,2,45,76}; + + cout< max_elem: + max_elem = elem + min_elem = float('inf') + for elem in arr: + if elem < min_elem: + min_elem=elem + return min_elem,max_elem + +## method definition = O(n) +def find_max_min(arr,i,j): + ## small problem + # single element + if i == j: + max_val=arr[i] + min_val=arr[i] + # two element + elif i == j-1: + if arr[i] < arr[j]: + max_val=arr[j] + min_val=arr[i] + else: + max_val=arr[i] + min_val=arr[j] + ## big problem + else: + # divide and conquer approach + mid = i + (j-i)//2 + # recursion : conquer + max1,min1=find_max_min(arr,i,mid) + max2,min2=find_max_min(arr,mid+1,j) + # combine + ## to find the final maxima + if max1 > max2: + max_val=max1 + else: + max_val=max2 + ## to find the final minima + if min1 < min2: + min_val=min1 + else: + min_val=min2 + return max_val,min_val + +max,min = find_max_min(arr,i,j) +print(f"Max value: {max} and Min value: {min}") + + diff --git a/ARRAYS/misbehave.py b/ARRAYS/misbehave.py new file mode 100644 index 0000000..e69de29 diff --git a/ARRAYS/no_of_occurrence.c b/ARRAYS/no_of_occurrence.c new file mode 100644 index 0000000..0113d63 --- /dev/null +++ b/ARRAYS/no_of_occurrence.c @@ -0,0 +1,19 @@ +#include +#include +#include +int getOccurrence(int arr[], int n, int key){ + int count; + for (int i = 0; i < n; i++) + { + if(arr[0] == key){ + count++; + } + } + +} +int main(int argc, char *argv[]){ + int arr[] = {1,2,3,1,2,4,6,8}; + int n = sizeof(arr)/sizeof(arr[0]); + printf("%d\n",getOccurrence(arr,n,1)); + return 0; +} \ No newline at end of file diff --git a/ARRAYS/power.py b/ARRAYS/power.py new file mode 100644 index 0000000..62599b8 --- /dev/null +++ b/ARRAYS/power.py @@ -0,0 +1,18 @@ +# Amazon Interview Question : Find the power of a number +# Time Complexity = O(logn) +def power(a,n): + # base case + if n==0: + return 1 + if n==1: + return a + # body + result = power(a,n//2) + if n%2==0: + return result * result + else: + return result * result * a + + +print(power(2,10)) +# print(power(2,11)) \ No newline at end of file diff --git a/ARRAYS/prefix_sum.py b/ARRAYS/prefix_sum.py new file mode 100644 index 0000000..07ef73f --- /dev/null +++ b/ARRAYS/prefix_sum.py @@ -0,0 +1,11 @@ +arr = [3,5,20,45,2,-5,9] + +def prefix_sum(arr): + ans=[0]*len(arr) + ans[0]=arr[0] + for i in range(1,len(arr)): + ans[i]=ans[i-1]+arr[i] + return ans + +print("Orginal Array: ", arr) +print("Prefix Sum Array: ", prefix_sum(arr)) \ No newline at end of file diff --git a/ARRAYS/readme.md b/ARRAYS/readme.md new file mode 100644 index 0000000..4c57e54 --- /dev/null +++ b/ARRAYS/readme.md @@ -0,0 +1,18 @@ +1. Find First and Last Position of Element in Sorted Array https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ +2. Find the Peaks https://leetcode.com/problems/find-the-peaks/description/ +3. Remove One Element to Make the Array Strictly Increasing https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/description/ +4. Move Zeroes https://leetcode.com/problems/move-zeroes/description/ +5. Apply Operations to an Array https://leetcode.com/problems/apply-operations-to-an-array/description/ +5. Find if Digit Game Can Be Won https://leetcode.com/problems/find-if-digit-game-can-be-won/description/ +6. Find Minimum Operations to Make All Elements Divisible by Three https://leetcode.com/problems/find-minimum-operations-to-make-all-elements-divisible-by-three/description/ +7. Richest Customer Wealth https://leetcode.com/problems/richest-customer-wealth/description/ +8. Number of Employees Who Met the Target https://leetcode.com/problems/number-of-employees-who-met-the-target/description/ +9. Kids With the Greatest Number of Candies https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/description/ +10. Count Pairs Whose Sum is Less than Target https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target/description/ +11. Running Sum of 1d Array https://leetcode.com/problems/running-sum-of-1d-array/description/ +12. Maximum Subarray https://leetcode.com/problems/maximum-subarray/description/ +13. Kadane's Algorithm https://www.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1 +14. Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ +15. Height Checker https://leetcode.com/problems/height-checker/submissions/1370271025/ +16. Find Indices of Stable Mountains https://leetcode.com/problems/find-indices-of-stable-mountains/description/ +17. Sort Colors https://leetcode.com/problems/sort-colors/description/ \ No newline at end of file diff --git a/ARRAYS/square_number.py b/ARRAYS/square_number.py new file mode 100644 index 0000000..145ca94 --- /dev/null +++ b/ARRAYS/square_number.py @@ -0,0 +1,18 @@ +''' +Given a positive integer num, write a program that returns True if num is a perfect +square else return False. Do not use built-in functions like sqrt. Also, talk about the time +complexity of your code. +Test Cases: +Input: 16 +Output: True +Input: 14 +Output: False +''' +import math + +def check_perfect_number(n): + if int(math.sqrt(n)) * int(math.sqrt(n))== n: + return True + return False + +print(check_perfect_number(64)) diff --git a/ARRAYS/subarray.c b/ARRAYS/subarray.c new file mode 100644 index 0000000..c556aef --- /dev/null +++ b/ARRAYS/subarray.c @@ -0,0 +1,31 @@ +#include +#include +#include +void getSubarray(int nums[], int length){ + int total_subarray = 0; + for (int i = 0; i < length; i++) + { + int start = i; + for (int j = i; j < length; j++) + { + int end = j; + for (int k = start; k <= end; k++) + { + printf("%d ", nums[k]); + } + total_subarray+=1; + printf("\n"); + + } + printf("\n"); + + } + printf("Total no. of subarray is = %d", total_subarray); + +} +int main(int argc, char *argv[]){ + int nums[] = {1,4,5,7,10}; + int length = sizeof(nums)/sizeof(nums[0]); + getSubarray(nums, length); + return 0; +} \ No newline at end of file diff --git a/ARRAYS/suffix_sum.py b/ARRAYS/suffix_sum.py new file mode 100644 index 0000000..74b030b --- /dev/null +++ b/ARRAYS/suffix_sum.py @@ -0,0 +1,13 @@ +arr = [3,5,20,45,2,-5,9] + +def suffix_sum(arr): + n = len(arr) + ans=[0]*n + ans[n-1]=arr[n-1] + # print(ans) + for i in range(n-2,-1,-1): + ans[i]=ans[i+1]+arr[i] + return ans + +print("Orginal Array: ", arr) +print(suffix_sum(arr)) \ No newline at end of file diff --git a/ARRAYS/sum_2_subarray.py b/ARRAYS/sum_2_subarray.py new file mode 100644 index 0000000..2c3f01f --- /dev/null +++ b/ARRAYS/sum_2_subarray.py @@ -0,0 +1,21 @@ +# Divid array in 2 subarray with equal sum +arr = [2,3,4,6,9,6] + +# O(n^2) +def equal_sum(arr): + n=len(arr) + for i in range(n): + j=0 + sum1,sum2=0,0 + while j<=i: + sum1+=arr[j] + j+=1 + k=i+1 + while k arr[mid2]: + return ternary_search(arr,mid2+1,right,key) + else: + return ternary_search(arr,mid1+1,mid2-1,key) + return -1 + +print(ternary_search(arr,0,len(arr)-1,key)) \ No newline at end of file diff --git a/ARRAYS/trapped_rain_water.py b/ARRAYS/trapped_rain_water.py new file mode 100644 index 0000000..ec05c70 --- /dev/null +++ b/ARRAYS/trapped_rain_water.py @@ -0,0 +1,26 @@ +h = [4,2,0,6,3,2,5] +def trapped_water(height): + n=len(height) + if len(height)>2: + # leftMax boundry - array + leftMax=list() + leftMax.insert(0,height[0]) + for i in range(1,n): + leftMax.insert(i,max(height[i],leftMax[i-1])) + + # rightMax boundry - array + rightMax=list() + rightMax.insert(n-1,height[n-1]) + for i in range(n-2,-1): + rightMax.insert(i,max(height[i],rightMax[i+1])) + # loop + trappedWater = 0 + for i in range(0,n-1): + # waterLevel = min(leftMax,rightMax) + waterLevel = min(leftMax[i], rightMax[i]) + # trappedWater = waterLevel - height[i] + trappedWater+=waterLevel-height[i] + return trappedWater + return 0 + +print(trapped_water(h)) \ No newline at end of file diff --git a/ARRAYS/trapped_water.cpp b/ARRAYS/trapped_water.cpp new file mode 100644 index 0000000..37a5a90 --- /dev/null +++ b/ARRAYS/trapped_water.cpp @@ -0,0 +1,29 @@ +#include +#include + +using namespace std; +int trappedWater(int height[], int n){ + int leftMax[n]; + leftMax[0]=height[0]; + for(int i=1; i=0; i--){ + rightMax[i]=max(height[i], rightMax[i+1]); + } + int waterLevel = 0; + int trappedWater = 0; + for(int i=0; i target: + r=r-1 + else: + l=l+1 + return (-1,-1) + +print(two_sum3(arr,target)) diff --git a/BACKTRACKING/nQueen.c b/BACKTRACKING/nQueen.c new file mode 100644 index 0000000..ed81998 --- /dev/null +++ b/BACKTRACKING/nQueen.c @@ -0,0 +1,76 @@ +#include +#include +#include +int n=4; // board size nxn + +void displayBoard(char board[][n], int size){ + for (int i = 0; i < size; i++) + { + for (int j = 0; j < size; j++) + { + printf("%c ", board[i][j]); + } + printf("\n"); + + } +} + +void initialize(char board[][n], int size){ + for (int i = 0; i < size; i++) + { + for (int j = 0; j < size; j++) + { + board[i][j] = 'X'; + } + } +} +int isSafe(char board[][n], int size, int row, int col){ + // vertical up + for(int i=row-1; i >= 0; i--){ + if(board[i][col] == 'Q'){ + return 0; + } + } + + // diagonal left up + for (int i = row-1, j=col-1; i>=0 && j>=0; i--,j--) + { + if(board[i][j] == 'Q'){ + return 0; + } + } + + + // diagonal right up + for (int i = row-1, j = col+1; i>=0 && j +using namespace std; +int main(){ + vector s = {"d","b","c","b","c","a"}; + int k=2; + unordered_map hash; + for(int i=s.size()-1;i>=0;i--){ + if(!hash[s[i]]){ + hash[s[i]] = 1; + } + else{ + hash[s[i]]+=1; + } + } + for(auto item : hash){ + cout< +#include + +void main() { + int i=0,n,x,s=0; + printf("Enter the number of elements: "); + scanf("%d",&n); + while(n!=0){ + x = n%2; // 1 + n = n/2; // 1 + s = s + pow(10,i)*x; // 1 + 10^2*1 = 101 + printf("x: %d\n",x); + printf("n: %d\n",n); + printf("s: %d\n",s); + i++; // 2 + } + printf("Binary equivalent: %d",s); +} \ No newline at end of file diff --git a/C/main.exe b/C/main.exe new file mode 100644 index 0000000..07f2197 Binary files /dev/null and b/C/main.exe differ diff --git a/CPP/main.cpp b/CPP/main.cpp new file mode 100644 index 0000000..1e2e820 --- /dev/null +++ b/CPP/main.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; +int majorityElement(vector& nums) { + unordered_map hash; + int n = nums.size(); + int majorityElem; + for(int e : nums){ + if(hash[e]){ + hash[e]++; + } + else{ + hash[e]=1; + } + } + for(auto [e,c] : hash){ + if(c > n/2){ + majorityElem = e; + break; + } + } + return majorityElem; + } +int main(){ + vector nums = {3,2,3}; + cout< +using namespace std; +class Edge{ + public: + int v; + int wt; + Edge(int v,int wt){ + this->v=v; + this->wt=wt; + } +}; + + +void bellman_ford(vector> graph, int V, int src){ + vector dist(V,INT_MAX); + dist[src]=0; + + for(int i=0; i dist[u] + e.wt){ + dist[e.v] = dist[u] + e.wt; + } + } + } + } + + for(int b : dist){ + cout<> graph; + int V=5; + + graph[0].push_back(Edge(1,2)); + graph[0].push_back(Edge(2,4)); + + graph[1].push_back(Edge(2,-4)); + graph[2].push_back(Edge(3,2)); + graph[3].push_back(Edge(4,4)); + graph[4].push_back(Edge(-1,-1)); + bellman_ford(graph,V,0); + + return 0; +} \ No newline at end of file diff --git a/GRAPHS/dijkstra_algo.cpp b/GRAPHS/dijkstra_algo.cpp new file mode 100644 index 0000000..a179129 --- /dev/null +++ b/GRAPHS/dijkstra_algo.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; +class Edge{ + public: + int v; + int wt; + Edge(int v, int wt){ + this->v = v; + this->wt = wt; + } +}; + +void dijkstra(int src, vector> graph, int V){ + priority_queue, vector>, greater>> pq; // min heap + vector dist(V, INT_MAX); + pq.push(make_pair(0,src)); + dist[src]=0; + + while(pq.size() > 0){ + int u = pq.top().second; + pq.pop(); + for(Edge e : graph[u]){ + if(dist[e.v] > dist[u] + e.wt){ + dist[e.v] = dist[u] + e.wt; + pq.push(make_pair(dist[e.v], e.v)); + } + } + } + + for(int d : dist){ + cout<> graph(V); + + graph[0].push_back(Edge(1,2)); + graph[0].push_back(Edge(2,4)); + + graph[1].push_back(Edge(2,1)); + graph[1].push_back(Edge(3,7)); + + graph[2].push_back(Edge(4,3)); + + graph[3].push_back(Edge(5,1)); + + graph[4].push_back(Edge(3,2)); + graph[4].push_back(Edge(5,5)); + + dijkstra(0,graph,V); + + return 0; +} \ No newline at end of file diff --git a/GRAPHS/graph.cpp b/GRAPHS/graph.cpp new file mode 100644 index 0000000..0afdf9d --- /dev/null +++ b/GRAPHS/graph.cpp @@ -0,0 +1,117 @@ +#include +#include +#include +#include +#include +using namespace std; +class Graph{ + int V; + list *l; + bool isUndir; + public: + Graph(int V, bool isUndir = true){ + this->V=V; + l = new list [V]; + this->isUndir=isUndir; + } + void addEdge(int u, int v){ + l[u].push_back(v); + if(isUndir) + l[v].push_back(u); + } + void print(){ + for(int u=0; u neighbour = l[u]; + cout< q; + vector visited(V,false); + q.push(0); + visited[0]=true; + while(!q.empty()){ + int u = q.front(); + q.pop(); + cout< &visited){ + visited[u]=1; + cout< &visited, string &path){ + if(src==dest){ + cout< visited(V,false); + string path=""; + pathHelper(src,dest,visited,path); + } + void topoHelper(int i, vector&visted, stack st){ + visted[i]=true; + for(auto nbr : l[i]){ + if(!visted[nbr]){ + topoHelper(nbr,visted,st); + } + } + st.push(i); + } + void topoSort(){ + vector visited(V,false); + stack st; + for(int i=0; i=item: + n-=item # n = n-item + ans.append(item) + return ans +def min_coin2(coins,n): + ans=[] + notes,i=0,0 + while (n): + notes = n//coins[i] + while(notes): + ans.append(coins[i]) + notes-=1 + n%=coins[i] + i+=1 + return ans + +print(min_coin2(coins,143)) diff --git a/GREEDY ALGO/readme.md b/GREEDY ALGO/readme.md new file mode 100644 index 0000000..162f5d8 --- /dev/null +++ b/GREEDY ALGO/readme.md @@ -0,0 +1 @@ +It is a problem solving approach that make a sequence of choice, each of which looks best at that moment. This method aims to find global optimal solution by making series of locally optimal choice. diff --git a/HASHING/hash.py b/HASHING/hash.py new file mode 100644 index 0000000..e69de29 diff --git a/HASHING/main.cpp b/HASHING/main.cpp new file mode 100644 index 0000000..9ae71ae --- /dev/null +++ b/HASHING/main.cpp @@ -0,0 +1,9 @@ +#include +using namespace std; + +int main(){ + cout<<"Hello"; + + + return 0; +} \ No newline at end of file diff --git a/HASHING/problems.md b/HASHING/problems.md new file mode 100644 index 0000000..50e77a8 --- /dev/null +++ b/HASHING/problems.md @@ -0,0 +1,10 @@ +1. Number of Good Pairs https://leetcode.com/problems/number-of-good-pairs/description/ +2. Find the Number of Good Pairs I https://leetcode.com/problems/find-the-number-of-good-pairs-i/description/ +3. First Unique Character in a String https://leetcode.com/problems/first-unique-character-in-a-string/description/ +4. Sum of Unique Elements https://leetcode.com/problems/sum-of-unique-elements/submissions/1345110438/ +5. Check If N and Its Double Exist https://leetcode.com/problems/check-if-n-and-its-double-exist/description/ +6. Valid Anagram https://leetcode.com/problems/valid-anagram/description/ +7. Missing Number https://leetcode.com/problems/missing-number/description/ +8. Unique Number of Occurrences https://leetcode.com/problems/unique-number-of-occurrences/ +10. X of a Kind in a Deck of Cards https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/ +11. Majority Element https://leetcode.com/problems/majority-element/description/ \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/build_heap.cpp b/HEAP (PRIORITY QUEUE)/build_heap.cpp new file mode 100644 index 0000000..7e4641b --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/build_heap.cpp @@ -0,0 +1,56 @@ +#include +#include +using namespace std; + +void heapify(int arr[], int index, int n) +{ + int largest = index; + int left = 2 * index + 1; + int right = 2 * index + 2; + + if (left < n && arr[left] > arr[largest]) + { + largest = left; + } + if (right < n && arr[right] > arr[largest]) + { + largest = right; + } + if (largest != index) + { + swap(arr[largest], arr[index]); + heapify(arr, largest, n); + } +} +void BuildMaxHeap(int arr[], int n) +{ + // step down + for (int i = n / 2 - 1; i >= 0; i--) + { + heapify(arr, i, n); + } +} +void printHeap(int arr[], int n) +{ + for (int i = 0; i < n; i++) + { + cout << arr[i] << " "; + } + cout << endl; +} + +void heapSort(int arr[],int n){ + for(int i=n-1; i>0; i--){ + swap(arr[0],arr[i]); + heapify(arr,0,i); + } +} +int main() +{ + int arr[] = {5,1,1,2,0,0}; + BuildMaxHeap(arr, 6); // TC = O(n) + heapSort(arr,6); // TC = O(nlogn) + printHeap(arr, 6); + + return 0; +} \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/build_heap.exe b/HEAP (PRIORITY QUEUE)/build_heap.exe new file mode 100644 index 0000000..b56d17a Binary files /dev/null and b/HEAP (PRIORITY QUEUE)/build_heap.exe differ diff --git a/HEAP (PRIORITY QUEUE)/build_heap.js b/HEAP (PRIORITY QUEUE)/build_heap.js new file mode 100644 index 0000000..0de8424 --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/build_heap.js @@ -0,0 +1,33 @@ + +const heapify = (arr, index ,n)=>{ + largest = index + left = 2*index+1 + right= 2*index+2 + + if(left < n && arr[left] > arr[largest]){ + largest = left + } + if(right < n && arr[right] > arr[largest]){ + largest = right + } + if(largest != index){ + let temp = arr[largest] + arr[largest]=arr[index] + arr[index] = temp + heapify(arr,largest,n) + } + +} +const buildMaxHeap = (arr,n)=>{ + for(let i=(n/2)-1; i>=0; i--){ + heapify(arr,i,n) + } +} +function printHeap(arr){ + arr.map((item)=>{ + console.log(item) + }) +} +arr = [10, 3, 8, 9, 5, 13, 18, 14, 11, 70] +buildMaxHeap(arr,arr.length) +printHeap(arr) \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/build_heap.py b/HEAP (PRIORITY QUEUE)/build_heap.py new file mode 100644 index 0000000..e4a776c --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/build_heap.py @@ -0,0 +1,27 @@ +# step down + +def heapify(arr, index,n): + largest = index + left,right=2*index + 1, 2*index + 2 + + if left < n and arr[left] > arr[largest]: + largest = left + if right < n and arr[right] > arr[largest]: + largest = right + if largest != index: + arr[largest], arr[index]= arr[index], arr[largest] + heapify(arr,largest,n) + +def buildMaxHeap(arr,n): + i=(n//2)-1 + while(i>=0): + heapify(arr,i,n) + i-=1 + +def printHeap(arr): + for elem in arr: + print(elem,end=' ') + +arr = [10, 3, 8, 9, 5, 13, 18, 14, 11, 70] +buildMaxHeap(arr,len(arr)) +printHeap(arr) \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/heap.js b/HEAP (PRIORITY QUEUE)/heap.js new file mode 100644 index 0000000..2bd5ae0 --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/heap.js @@ -0,0 +1,7 @@ +class MaxHeap{ + constructor(n){ + this.arr = [] + this.size=0 + this.total_size=n + } +} \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/heap.py b/HEAP (PRIORITY QUEUE)/heap.py new file mode 100644 index 0000000..f61b485 --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/heap.py @@ -0,0 +1,99 @@ +class MaxHeap: + def __init__(self,n): + self.arr=[None] * n + self.size=0 + self.totol_size=n + + def push(self,val): + if self.size==self.totol_size: + print("Heap Overflow\n") + return + self.arr[self.size]=val + index = self.size + self.size+=1 + while index>0 and self.arr[(index-1)//2] < self.arr[index]: + self.arr[(index-1)//2],self.arr[index]=self.arr[index],self.arr[(index-1)//2] + index=(index-1)//2 + def heapify(self,index): + largest = index + left = 2*index+1 + right = 2*index+2 + if leftself.arr[largest]: + largest = left + if rightself.arr[largest]: + largest = right + if largest!=index: + self.arr[index],self.arr[largest]=self.arr[largest],self.arr[index] + self.heapify(largest) + def remove(self): + if self.size == 0: + print("Heap Underflow\n") + return + self.arr[0]=self.arr.pop(self.size-1) + self.size-=1 + index=0 + self.heapify(index) + + def show(self): + for item in self.arr: + if item is not None: + print(item,end=" ") + print() + +# heap = MaxHeap(6) +# heap.push(4) +# heap.push(14) +# heap.push(2) +# heap.push(20) +# heap.push(90) +# heap.remove() +# heap.show() + +class MinHeap: + def __init__(self,n): + self.arr = [None] * n + self.size = 0 + self.total_size = n + def push(self, val): + if self.size==self.total_size: + print("Heap Overflow\n") + return + self.arr[self.size]=val + index = self.size + self.size+=1 + while index>0 and self.arr[(index-1)//2] > self.arr[index]: + self.arr[(index-1)//2], self.arr[index]=self.arr[index],self.arr[(index-1)//2] + index = (index-1)//2 + def show(self): + for item in self.arr: + if item is not None: + print(item,end=" ") + print() + def heapify(self,index): + smallest = index + left = 2*index+1 + right = 2*index+2 + if left +using namespace std; + +void heapify(int arr[], int index, int n) +{ + int largest = index; + int left = 2 * index + 1; + int right = 2 * index + 2; + + if (left < n && arr[left] > arr[largest]) + { + largest = left; + } + if (right < n && arr[right] > arr[largest]) + { + largest = right; + } + if (largest != index) + { + swap(arr[largest], arr[index]); + heapify(arr, largest, n); + } +} +void heapSort(int arr[], int n) +{ + // step down + for (int i = n / 2 - 1; i >= 0; i--) + { + heapify(arr, i, n); + } +} +void printHeap(int arr[], int n) +{ + for (int i = 0; i < n; i++) + { + cout << arr[i] << " "; + } + cout << endl; +} +int main(){ + int arr[] = {98,2,1,43,65,8,10}; + int n = 7; + heapSort(arr,n); + printHeap(arr,n); + return 0; +} \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/height_of_heap.cpp b/HEAP (PRIORITY QUEUE)/height_of_heap.cpp new file mode 100644 index 0000000..ffc3224 --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/height_of_heap.cpp @@ -0,0 +1,10 @@ +#include +#include +using namespace std; + +int main(){ + int arr[] = {1,3,6,5,9,8}; + int n = sizeof(arr)/sizeof(arr[0]); + priority_queue, greater> pq; + return 0; +}; diff --git a/HEAP (PRIORITY QUEUE)/height_of_heap.exe b/HEAP (PRIORITY QUEUE)/height_of_heap.exe new file mode 100644 index 0000000..d4fe0f6 Binary files /dev/null and b/HEAP (PRIORITY QUEUE)/height_of_heap.exe differ diff --git a/HEAP (PRIORITY QUEUE)/main.cpp b/HEAP (PRIORITY QUEUE)/main.cpp new file mode 100644 index 0000000..f1f5d3b --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/main.cpp @@ -0,0 +1,9 @@ +#include + +using namespace std; +int main() +{ + + + return 0; +}; \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/main.exe b/HEAP (PRIORITY QUEUE)/main.exe new file mode 100644 index 0000000..2b9018c Binary files /dev/null and b/HEAP (PRIORITY QUEUE)/main.exe differ diff --git a/HEAP (PRIORITY QUEUE)/max_heap.cpp b/HEAP (PRIORITY QUEUE)/max_heap.cpp new file mode 100644 index 0000000..44a98a0 --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/max_heap.cpp @@ -0,0 +1,90 @@ +#include +using namespace std; +class MaxHeap +{ + int *arr; + int size; // total element in heap + int total_size; // total size of array + + public: + MaxHeap(int n) + { + arr = new int[n]; + size = 0; + total_size = n; + } + void insert(int value){ + if(size == total_size){ + cout<<"Heap Overflow\n"; + return; + } + arr[size]=value; + int index = size; + size++; + + // Compare it with its parent + while(index>0 && arr[(index-1)/2] < arr[index]){ + swap(arr[(index-1)/2],arr[index]); + index = (index-1)/2; + } + cout<arr[largest]){ + largest=left; + } + if(rightarr[largest]){ + largest=right; + } + + if(largest!=index){ + swap(arr[index],arr[largest]); + heapify(largest); + } + } + +}; +int main() +{ + + MaxHeap h1(6); + h1.insert(4); + h1.insert(14); + h1.insert(11); + h1.print(); + h1.insert(45); + h1.insert(90); + h1.insert(1); + h1.print(); + h1.delete_one(); + h1.print(); + + return 0; +} \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/max_heap.js b/HEAP (PRIORITY QUEUE)/max_heap.js new file mode 100644 index 0000000..3c94f5a --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/max_heap.js @@ -0,0 +1,72 @@ +class MaxHeap{ + constructor(n){ + this.size = 0 + this.total_size = n + this.arr = new Array(n) + } + insert(value){ + if(this.size==this.total_size){ + console.log("Heap Overflow\n") + return + } + this.arr[this.size]=value + let index = this.size + this.size+=1 + + // compare it with its parent + while(index>0 && this.arr[Math.floor((index-1)/2)] < this.arr[index]){ + let temp = this.arr[Math.floor((index-1)/2)] + this.arr[Math.floor((index-1)/2)] = this.arr[index] + this.arr[index] = temp + } + } + print(){ + this.arr.map((item)=>{ + console.log(item) + }) + } + heapify(index){ + let largest = index + let left = 2*index + 1 + let right = 2*index + 2 + + if(left < this.size && this.arr[left] > this.arr[largest]){ + largest = left + } + if(right < this.size && this.arr[right] > this.arr[largest]){ + largest = right + } + if(largest != index){ + let temp = this.arr[largest] + this.arr[largest]= this.arr[index] + this.arr[index]=temp + this.heapify(largest) + } + } + delete(){ + if(this.size==0){ + console.log("Heap Underflow\n") + return + } + this.arr[0]=this.arr[this.size-1] + this.arr.pop() + this.size-=1 + + if(this.size==0){ + return + } + + this.heapify(0) + } +} + +const h = new MaxHeap(6) +h.insert(90) +h.insert(45) +h.insert(11) +h.insert(4) +h.insert(14) +h.insert(1) +h.print() +h.delete() +h.print() \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/max_heap.py b/HEAP (PRIORITY QUEUE)/max_heap.py new file mode 100644 index 0000000..db24ddf --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/max_heap.py @@ -0,0 +1,63 @@ +class MaxHeap: + def __init__(self,n): + self.arr = [] + self.size = 0 + self.total_size=n + + def insert(self,value): + if self.size==self.total_size: + print("Heap Overflow\n") + return + self.arr.append(value) + index = self.size + self.size+=1 + + # compare it with its parent + while index>0 and self.arr[(index-1)//2] < self.arr[index]: + self.arr[(index-1)//2],self.arr[index]=aself.rr[index],self.arr[(index-1)//2] + print(f"{self.arr[index]} is inserted.") + + def show(self): + for i in self.arr: + print(i,end=" ") + + def heapify(self,index): + largest = index + left = 2*index + 1 + right = 2*index + 2 + + if(left < self.size and self.arr[left]>self.arr[largest]): + largest = left + if(right < self.size and self.arr[right]>self.arr[largest]): + largest = right + if(largest!=index): + self.arr[index],self.arr[largest]=self.arr[largest],self.arr[index] + self.heapify(largest) + + + def delete(self): + if self.size==0: + print("Heap Underflow\n") + return + + self.arr[0]=self.arr[-1] + self.arr.pop(-1) + self.size-=1 + + if self.size==0: + return + + self.heapify(0) + + +h = MaxHeap(6) +h.insert(90) +h.insert(45) +h.insert(11) +h.insert(4) +h.insert(14) +h.insert(1) +h.show() +h.delete() +print("\n") +h.show() \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/max_heap_class.cpp b/HEAP (PRIORITY QUEUE)/max_heap_class.cpp new file mode 100644 index 0000000..fa3410a --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/max_heap_class.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +class MaxHeap{ + int * arr; + int size; + int total_size; + public: + MaxHeap(int n){ + arr = new int[n]; + size=0; + total_size=n; + } + void insert(int val){ + if(size ==total_size){ + cout<<"Heap Overflow\n"; + return; + } + arr[size]=val; + int index = size; + size++; + while(size>0 && arr[(index-1)/2] < arr[index]){ + swap(arr[(index-1)/2],arr[index]); + index = (index-1)/2; + } + } + void print(){ + for(int i=0; i +using namespace std; +class MinHeap +{ + int *arr; + int size; + int capacity; + +public: + MinHeap(int n) + { + arr = new int[n]; + size = 0; + capacity = n; + } + void heapify(int index) + { + int smallest = index; + int left = 2 * index + 1; + int right = 2 * index + 2; + + if (left < size && arr[left] < arr[smallest]) + { + smallest = left; + } + if (right < size && arr[right] < arr[smallest]) + { + smallest = right; + } + + if (smallest == index) + { + return; + } + swap(arr[index], arr[smallest]); + heapify(smallest); + } + void insert(int value) + { + if (size == capacity) + { + cout << "Heap Overflow" << endl; + return; + } + arr[size] = value; + int index = size; + size++; + + while (index > 0 && arr[(index - 1) / 2] > value) + { + swap(arr[index], arr[(index - 1) / 2]); + index = (index - 1) / 2; + } + cout << value << " inserted into heap" << endl; + } + void print() + { + for (int i = 0; i < size; i++) + cout << arr[i] << " "; + cout << endl; + } + void remove() + { + if (size == 0) + { + cout << "Heap Underflow..." << endl; + return; + } + arr[0]=arr[size-1]; + size--; + if(size==0){ + return; + } + + heapify(0); + } +}; + +int main() +{ + MinHeap h(5); + h.insert(90); + h.insert(100); + h.insert(40); + h.insert(20); + h.print(); + + return 0; +} \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/min_heap.py b/HEAP (PRIORITY QUEUE)/min_heap.py new file mode 100644 index 0000000..740b9aa --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/min_heap.py @@ -0,0 +1,58 @@ +class MinHeap: + def __init__(self,n): + self.size = 0 + self.totol_size = n + self.arr = [] + + def heapify(self,index): + smallest = index + left = 2*index + 1 + right = 2*index + 2 + + if(left < self.size and self.arr[left] < smallest): + smallest = left + if(right < self.size and self.arr[right] < smallest): + smallest = right + + if(smallest == index): + return + self.arr[index],self.arr[smallest]=self.arr[smallest],self.arr[index] + self.heapify(smallest) + + def insert(self,value): + if(self.size == self.totol_size): + print("Heap Overflow\n") + return + self.arr.append(value) + index = self.size + self.size+=1 + + # compare it with its parent + while index > 0 and self.arr[(index-1)//2] > value: + self.arr[index],self.arr[(index-1)//2]=self.arr[(index-1)//2],self.arr[index] + index = (index-1)//2 + print(f"{value} inserted into heap") + def show(self): + for item in self.arr: + print(item, end=" ") + + def delete(self): + if(self.size==0): + print("Heap Underflow") + return + self.arr[0]=self.arr[-1] + self.arr.pop() + self.size-=1 + + if(self.size==0): + return + + self.heapify(0) + +h = MinHeap(5) +h.insert(90) +h.insert(100) +h.insert(40) +h.insert(20) +h.show() + \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/pq_using_list.py b/HEAP (PRIORITY QUEUE)/pq_using_list.py new file mode 100644 index 0000000..835e826 --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/pq_using_list.py @@ -0,0 +1,36 @@ +class PriorityQueue: + def __init__(self): + self.items=[] + + def is_empty(self): + return len(self.items) == 0 + def push(self,data,priority): + index=0 + while index < len(self.items) and self.items[index][1] <= priority: + index+=1 + self.items.insert(index,(data,priority)) + + def pop(self): + if self.is_empty(): + raise IndexError("PQ is empty") + else: + return self.items.pop(0)[0] + def size(self): + return len(self.items) + +pq = PriorityQueue() + +pq.push("Abhi",4) +pq.push("Yogesh",2) +pq.push("Devesh",12) +pq.push("Saurabh",5) +pq.push("Twinkle",9) +print(pq.size()) +# print(pq.pop()) + +while not pq.is_empty(): + print(pq.pop()) + + + + \ No newline at end of file diff --git a/HEAP (PRIORITY QUEUE)/pq_using_ll.py b/HEAP (PRIORITY QUEUE)/pq_using_ll.py new file mode 100644 index 0000000..1b5496d --- /dev/null +++ b/HEAP (PRIORITY QUEUE)/pq_using_ll.py @@ -0,0 +1,48 @@ +class Node: + def __init__(self,item=None,priority=None,next=None): + self.item=item + self.priority=priority + self.next=next + +class PriorityQueue: + def __init__(self): + self.start=None + self.item_count=0 + def is_empty(self): + return self.item_count==0 + def push(self,data,priority): + n=Node(data,priority) + if not self.start or priority +using namespace std; +class Node{ + int val; + Node*prev,*next; + public: + Node(int data){ + this->val=data; + prev=next=nullptr; + } + void insert_at_first(Node* head,int data){ + if(head==nullptr){ + head->val=data; + return; + } + Node* n = new Node(data); + n->next=head; + head->prev=n; + head=n; + } + void print(Node* head){ + if(head==nullptr) return; + Node* temp = head; + while(temp!=nullptr){ + cout<val<<" "; + temp=temp->next; + } + } +}; +int main(){ + Node * head= new Node(2); + head->insert_at_first(head,4); + head->print(head); + return 0; +} \ No newline at end of file diff --git a/LINKED LISTS/main.py b/LINKED LISTS/main.py new file mode 100644 index 0000000..4f765c9 --- /dev/null +++ b/LINKED LISTS/main.py @@ -0,0 +1,33 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def removeElements(self, head, val): + + dummy = ListNode(next=head) + current = dummy + print("Dummy", dummy.next) + while current.next: + if current.next.val == val: + current.next = current.next.next + else: + current = current.next + + return dummy.next + +# Time complexity: O(n) +# Space complexity: O(1) +linked_list = ListNode(7) +linked_list.next = ListNode(7) +linked_list.next.next = ListNode(7) +linked_list.next.next.next = ListNode(7) +linked_list.next.next.next.next = ListNode(7) +linked_list.next.next.next.next.next = None + +sol = Solution() +sol.removeElements(linked_list, 6) +while(linked_list): + print(linked_list.val) + linked_list = linked_list.next \ No newline at end of file diff --git a/LINKED LISTS/problems.md b/LINKED LISTS/problems.md new file mode 100644 index 0000000..bf62654 --- /dev/null +++ b/LINKED LISTS/problems.md @@ -0,0 +1,17 @@ +1. Middle of the Linked List https://leetcode.com/problems/middle-of-the-linked-list/description/ +2. Linked List Cycle https://leetcode.com/problems/linked-list-cycle/description/ +3. Remove Duplicates from Sorted List https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ +4. Remove Linked List Elements https://leetcode.com/problems/remove-linked-list-elements/description/ +5. Delete Node in a Linked List https://leetcode.com/problems/delete-node-in-a-linked-list/description/ +6. Remove Nth Node From End of List https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ +7. +8. Remove every kth node https://www.geeksforgeeks.org/problems/remove-every-kth-node/1 +9. Merge Nodes in Between Zeros https://leetcode.com/problems/merge-nodes-in-between-zeros/description/ +10. Left View of Binary Tree https://www.geeksforgeeks.org/problems/left-view-of-binary-tree/1 +11. Binary Tree Right Side View https://leetcode.com/problems/binary-tree-right-side-view/description/ +12. Right View of Binary Tree https://www.geeksforgeeks.org/problems/right-view-of-binary-tree/1 +13. Top View of Binary Tree https://www.geeksforgeeks.org/problems/top-view-of-binary-tree/1 +14. Merge two sorted linked lists https://www.geeksforgeeks.org/problems/merge-two-sorted-linked-lists/1 +15. Merge Two Sorted Lists https://leetcode.com/problems/merge-two-sorted-lists/description/ +16. Flattening a Linked List https://www.geeksforgeeks.org/problems/flattening-a-linked-list/1 +17. \ No newline at end of file diff --git a/LINKED LISTS/singly_ll.c b/LINKED LISTS/singly_ll.c new file mode 100644 index 0000000..e761215 --- /dev/null +++ b/LINKED LISTS/singly_ll.c @@ -0,0 +1,51 @@ +#include +#include +#include +struct node{ + int item; + struct node * next; +}; +void addFirst(struct node **head, int data){ + struct node * n = (struct node *)malloc(sizeof(struct node)); + n->item = data; + if(head != NULL){ + n->next = *head; + *head = n; + }else{ + *head = n; + n->next = NULL; + } +} + +void print(struct node *head){ + struct node * temp = head; + while(temp != NULL){ + printf("%d->",temp->item); + temp = temp->next; + } + printf("NULL\n"); +} +void addLast(struct node *head,int data){ + struct node * n = (struct node *)malloc(sizeof(struct node)); + if(head != NULL){ + struct node *temp = head; + while(temp->next != NULL){ + temp = temp->next; + } + temp->next = n; + n->next = NULL; + } + else{ + head = n; + n->next = NULL; + } +} +int main(int argc, char *argv[]){ + struct node * head = NULL; + addFirst(&head,30); + addFirst(&head, 20); + addFirst(&head, 10); + addLast(head, 40); + print(head); + return 0; +} \ No newline at end of file diff --git a/LINKED LISTS/singly_ll.py b/LINKED LISTS/singly_ll.py new file mode 100644 index 0000000..fbcd53d --- /dev/null +++ b/LINKED LISTS/singly_ll.py @@ -0,0 +1,131 @@ +class Node: + def __init__(self, data=None,next=None): + self.data = data + self.next = next +class SinglyLL: + def __init__(self,start=None): + self.start=start + # O(1) + def is_empty(self): + return self.start==None + # O(1) + def insert_at_start(self,data): + n=Node(data, self.start) + self.start = n + + def insert_at_last(self,data): + n=Node(data, None) + if not self.is_empty(): + temp = self.start + while temp.next is not None: + temp = temp.next + temp.next = n + else: + self.start = n + + def search(self, data): + temp = self.start + while temp is not None: + if temp.data == data: + return temp + temp = temp.next + return None + def insert_after(self,temp, data): + if temp is not None: + n = Node(data, temp.next) + temp.next = n + + def print_list(self): + temp = self.start + while temp is not None: + print(temp.data,end="-> ") + temp = temp.next + print("None") + + def delete_first(self): + if self.start is not None: + self.start = self.start.next + def delete_last(self): + if self.start is None: + pass + elif self.start.next is None: + self.start = None + else: + temp=self.start + while temp.next.next is not None: + temp = temp.next + temp.next = None + def delete_item(self, data): + if self.start is None: + pass + elif self.start.next is None: + if self.start.data == data: + self.start = None + else: + temp = self.start + if temp.data == data: + self.start = temp.next + else: + while temp.next is not None: + if temp.next.data == data: + temp.next = temp.next.next + break + temp = temp.next + def __iter__(self): + return SLLIterator(self.start) + def reverse(self): + if self.start == None: + return + else: + prev=None + curr=self.start + nextptr = None + while curr != None: + nextptr = curr.next + curr.next = prev + prev=curr + curr=nextptr + self.start=prev + def rreverse_util(self,start): + if start is None or start.next is None: + return start + head = self.rreverse(start.next) + self.start.next.next=self.start + self.start=None + return head + def rreverse(self): + self.start = self.rreverse_util(self.start) + def middle(self): + if self.start!=None: + fast=slow=self.start + while(fast!=None): + slow=slow.next + fast=fast.next.next + return slow + return self.start +class SLLIterator: + def __init__(self,start): + self.current=start + def __iter__(self): + return self + def __next__(self): + if not self.current: + raise StopIteration + data = self.current.data + self.current=self.current.next + return data + +mylist = SinglyLL() +mylist.insert_at_start(5) +mylist.insert_at_start(4) +mylist.insert_at_start(2) +# mylist.insert_at_start(5) +# mylist.insert_at_start(6) +# mylist.insert_at_start(1) +# mylist.insert_at_start(4) +r = mylist.middle() +print(r.data) +mylist.print_list() + + + diff --git a/LINKED LISTS/singly_ll_c++.cpp b/LINKED LISTS/singly_ll_c++.cpp new file mode 100644 index 0000000..7118909 --- /dev/null +++ b/LINKED LISTS/singly_ll_c++.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; +class Node{ + private: + int item; + Node * next; + public: + Node(){} + Node(int data){ + this->item=data; + this->next = NULL; + } + Node(int data, Node * next){ + this->item = data; + this->next=next; + } + void insert_at_first(Node *head, int data){ + Node *n = new Node(data); + if(head==NULL){ + head=n; + n->next=NULL; + } + else{ + n->next = head; + head = n; + } + } + + void display(Node * head){ + if(head!=NULL){ + Node * temp = head; + while (temp != NULL) + { + cout<item<<"->"; + temp = temp->next; + } + cout<<"NULL"; + } + else{ + cout<<"List is empty"<insert_at_first(head,3); + list->insert_at_first(head,54); + list->insert_at_first(head, 90); + list->display(head); + + return 0; +} \ No newline at end of file diff --git a/LINKED LISTS/singly_ll_implementation.cpp b/LINKED LISTS/singly_ll_implementation.cpp new file mode 100644 index 0000000..78751e2 --- /dev/null +++ b/LINKED LISTS/singly_ll_implementation.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; +class Node{ + public: + int item; + Node* next; + + Node(int item){ + this->item=item; + this->next=nullptr; + } +}; +class LinkedList{ + private: + Node* head; + public: + LinkedList(){ + this->head=nullptr; + } + void insert_at_first(int value){ + Node* n = new Node(value); + if(head==nullptr){ + head = n; + } + else{ + n->next = head; + head = n; + } + } + void insert_at_last(int value){ + Node * n = new Node(value); + if(head==nullptr){ + head=n; + } + else{ + Node * temp = head; + while(temp->next!=nullptr){ + temp = temp->next; + } + temp->next = n; + } + + } + void display(){ + if(head!=nullptr){ + Node * temp = head; + while(temp!=nullptr){ + cout<item<<" "; + temp =temp->next; + } + } + } +}; +int main(){ + LinkedList l; + l.insert_at_first(2); + l.insert_at_first(3); + l.insert_at_last(1); + l.display(); + + + return 0; +} \ No newline at end of file diff --git a/PATTERNS/01.py b/PATTERNS/01.py new file mode 100644 index 0000000..fa9be5d --- /dev/null +++ b/PATTERNS/01.py @@ -0,0 +1 @@ +print("*****") \ No newline at end of file diff --git a/PATTERNS/02.py b/PATTERNS/02.py new file mode 100644 index 0000000..82bf24f --- /dev/null +++ b/PATTERNS/02.py @@ -0,0 +1,36 @@ +""" +Questin - Print this star pattern. +* * * * +* * * * +* * * * +* * * * +""" +# Method 1 TC = O(1) +""" +print("* * * *") +print("* * * *") +print("* * * *") +print("* * * *") +""" + +# Method 2 TC = O(n) +""" +for i in range(0,4): + print("* * * *") +""" + +# Method 3 TC = O(n) +""" +i=0 +while i<4: + print("* * * *") + i+=1 +""" + +# Method 4 TC = O(n^2) +""" +for i in range(0,4): + for j in range(0,4): + print("* ",end=" ") + print() +""" \ No newline at end of file diff --git a/PATTERNS/03.py b/PATTERNS/03.py new file mode 100644 index 0000000..dd88a92 --- /dev/null +++ b/PATTERNS/03.py @@ -0,0 +1,36 @@ +""" # Half Pyramid +* +* * +* * * +* * * * +""" + +# Method 1 TC = O(n^2) +""" +n=4 +for row in range(1,n+1): + for col in range(1, n+1): + if col<=row: + print("*",end=" ") + else: + print(" ",end=" ") + print() +""" + +""" # Half Pyramid +A +A B +A B C +A B C D + +This code uses nested loops, where the outer loop controls the number of rows (n), and the inner loop prints the characters from 'A' to 'A + i' in each row. The chr() function is used to convert an ASCII value to its corresponding character, and ord() is used to get the ASCII value of a character. +""" +''' +for row in range(0,4): + for col in range(0,4): + if col<=row: + print(chr(ord('A') + col), end=" ") + else: + print(" ",end=" ") + print() +''' \ No newline at end of file diff --git a/PATTERNS/04.py b/PATTERNS/04.py new file mode 100644 index 0000000..2030b7e --- /dev/null +++ b/PATTERNS/04.py @@ -0,0 +1,14 @@ +""" + * + * * + * * * +* * * * +""" + +for row in range(1,5): + for col in range(1,5): + if col>=5-row: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/05.py b/PATTERNS/05.py new file mode 100644 index 0000000..6343353 --- /dev/null +++ b/PATTERNS/05.py @@ -0,0 +1,19 @@ +# Inverted Half Pyramid +""" +* * * * +* * * +* * +* +""" + +# Method 1 + +n = 4 +for row in range(1,n+1): + for col in range(1,n+1): + if col<=n+1-row: + print("* ",end="") + else: + print(" ",end="") + print() + \ No newline at end of file diff --git a/PATTERNS/06.py b/PATTERNS/06.py new file mode 100644 index 0000000..3521485 --- /dev/null +++ b/PATTERNS/06.py @@ -0,0 +1,14 @@ +""" +* * * * + * * * + * * + * +""" + +for row in range(1,5): + for col in range(1,5): + if col>=row: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/07.py b/PATTERNS/07.py new file mode 100644 index 0000000..5bcc493 --- /dev/null +++ b/PATTERNS/07.py @@ -0,0 +1,14 @@ +''' + * + * * * + * * * * * +* * * * * * * +''' + +for row in range(1,5): + for col in range(1,8): + if col>=5-row and col<=3+row: + print("* ",end='') + else: + print(" ",end='') + print() \ No newline at end of file diff --git a/PATTERNS/08.py b/PATTERNS/08.py new file mode 100644 index 0000000..bee4a3d --- /dev/null +++ b/PATTERNS/08.py @@ -0,0 +1,14 @@ +''' +* * * * * * * + * * * * * + * * * + * +''' + +for row in range(1,5): + for col in range(1,8): + if col>=row and col<=8-row: + print("* ",end='') + else: + print(" ",end='') + print() \ No newline at end of file diff --git a/PATTERNS/09.py b/PATTERNS/09.py new file mode 100644 index 0000000..1536a11 --- /dev/null +++ b/PATTERNS/09.py @@ -0,0 +1,15 @@ + +''' +* * * * * * * +* * * * * * +* * * * +* * +''' +for row in range(1,5): + for col in range(1,8): + if col<=5-row or col>=3+row: + print("* ",end="") + else: + print(" ",end="") + print() + \ No newline at end of file diff --git a/PATTERNS/1.cpp b/PATTERNS/1.cpp new file mode 100644 index 0000000..571adb8 --- /dev/null +++ b/PATTERNS/1.cpp @@ -0,0 +1,6 @@ +#include +using namespace std; +int main(){ + cout<<"*"; + return 0; +} \ No newline at end of file diff --git a/PATTERNS/10.py b/PATTERNS/10.py new file mode 100644 index 0000000..6f191a1 --- /dev/null +++ b/PATTERNS/10.py @@ -0,0 +1,17 @@ +''' + * + * * * + * * * * * +* * * * * * * +* * * * * * * +* * * * * * * +* * * * * * * +''' + +for row in range(1,8): + for col in range(1,8): + if col>=5-row and col<=3+row: + print("* ",end='') + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/11 Rhombus.py b/PATTERNS/11 Rhombus.py new file mode 100644 index 0000000..5e69922 --- /dev/null +++ b/PATTERNS/11 Rhombus.py @@ -0,0 +1,15 @@ +# Rhombus +''' + * * * * * + * * * * * + * * * * * + * * * * * +* * * * * +''' +for row in range(1,6): + for col in range(1,10): + if col>=6-row and col<=10-row: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/12 Cross.py b/PATTERNS/12 Cross.py new file mode 100644 index 0000000..9aa3907 --- /dev/null +++ b/PATTERNS/12 Cross.py @@ -0,0 +1,17 @@ +''' +* * + * * + * * + * + * * + * * +* * +''' +n = int(input("Enter number of lines: ")) +for row in range(1,n+1): + for col in range(1,n+1): + if col==row or col==n+1-row: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/13 Hollow Rectangle.py b/PATTERNS/13 Hollow Rectangle.py new file mode 100644 index 0000000..30bc54a --- /dev/null +++ b/PATTERNS/13 Hollow Rectangle.py @@ -0,0 +1,29 @@ +''' # Hollo Rectangle +* * * * * +* * +* * +* * +* * +* * * * * +''' +"""rows = 5 # Number of rows +columns = 5 # Number of columns + +for i in range(rows): + for j in range(columns): + if i == 0 or i == rows - 1 or j == 0 or j == columns - 1: + # Print '*' for the first and last row, and the first and last column + print("*", end=" ") + else: + # Print a space for the inner part of the pattern + print(" ", end=" ") + print() # Move to the next line after each row +""" + +for i in range(6): + for j in range(5): + if i== 0 or i == 5 or j==0 or j==4: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/14 L Shape.py b/PATTERNS/14 L Shape.py new file mode 100644 index 0000000..ef7211b --- /dev/null +++ b/PATTERNS/14 L Shape.py @@ -0,0 +1,16 @@ +""" # Print L shape pattern +* +* +* +* +***** +""" + + +for i in range(5): + for j in range(5): + if j==0 or i == 4: + print("*",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/15 U Shape.py b/PATTERNS/15 U Shape.py new file mode 100644 index 0000000..e8bad47 --- /dev/null +++ b/PATTERNS/15 U Shape.py @@ -0,0 +1,8 @@ +# Print U shape +for i in range(5): + for j in range(5): + if i==4 or j==4 or j==0: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/16 Hollow Right Triangle.py b/PATTERNS/16 Hollow Right Triangle.py new file mode 100644 index 0000000..875130c --- /dev/null +++ b/PATTERNS/16 Hollow Right Triangle.py @@ -0,0 +1,18 @@ +''' +* +** +* * +* * +* * +* * +* * +******** +''' + +for i in range(8): + for j in range(8): + if i==7 or j==0 or j==i: + print("*",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/17 Number Right Triangle.py b/PATTERNS/17 Number Right Triangle.py new file mode 100644 index 0000000..92ff868 --- /dev/null +++ b/PATTERNS/17 Number Right Triangle.py @@ -0,0 +1,15 @@ +''' +1 +22 +333 +4444 +55555 +''' + +for i in range(5): + for j in range(5): + if j<=i: + print(i+1,end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/18 T Shape.py b/PATTERNS/18 T Shape.py new file mode 100644 index 0000000..9db3064 --- /dev/null +++ b/PATTERNS/18 T Shape.py @@ -0,0 +1,8 @@ +# Print T shape +for i in range(5): + for j in range(5): + if i==0 or j==2: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/19 B Shape.py b/PATTERNS/19 B Shape.py new file mode 100644 index 0000000..7388787 --- /dev/null +++ b/PATTERNS/19 B Shape.py @@ -0,0 +1,8 @@ +# Print B or 8 shape +for i in range(5): + for j in range(3): + if i == 0 or i == 4 or i == 2 or j==0 or j==2: + print("* ",end="") + else: + print(" ",end="") + print() diff --git a/PATTERNS/2.cpp b/PATTERNS/2.cpp new file mode 100644 index 0000000..94c3b7e --- /dev/null +++ b/PATTERNS/2.cpp @@ -0,0 +1,9 @@ +#include +using namespace std; +int main(){ + + for(int i=1; i<=4; i++){ + cout<<"* "; + } + return 0; +} \ No newline at end of file diff --git a/PATTERNS/20 S shape.py b/PATTERNS/20 S shape.py new file mode 100644 index 0000000..7cc1355 --- /dev/null +++ b/PATTERNS/20 S shape.py @@ -0,0 +1,8 @@ +# Print S shape +for i in range(5): + for j in range(4): + if i == 0 or i == 4 or i == 2: + print("* ",end="") + else: + print(" ",end="") + print() \ No newline at end of file diff --git a/PATTERNS/3.cpp b/PATTERNS/3.cpp new file mode 100644 index 0000000..cef3663 --- /dev/null +++ b/PATTERNS/3.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +int main(){ + /* Method 1 */ + cout<<"Method 1"< +using namespace std; +void pattern(int n); +int main(){ + pattern(5); + return 0; +} + +void pattern(int n){ + for(int row=1; row<=n; row++){ + for(int col=1; col<=n; col++){ + if(col<=row){ + cout<<"* "; + } + else{ + cout<<" "; + } + } + cout< +using namespace std; +void pattern1(int n){ + for (int row = 1; row <= n; row++) + { + for(int col=1; col<=n; col++ ){ + if(col<=n-row+1){ + cout<<"* "; + }else{ + cout<<" "; + } + } + cout< +using namespace std; +void pattern(int n){ + for(int row=1; row<=n; row++){ + for(int col=1; col<=n; col++){ + if(col<=row-1){ + cout<<" "; + } + else{ + cout<<"*"<<" "; + } + } + cout<=row){ + cout<<"* "; + } + else{ + cout<<" "; + } + } + cout< +using namespace std; +void pattern(int n){ + for (int row = 0; row <=n; row++) + { + for (int col = 0; col <=n; col++) + { + if (/* condition */) + { + /* code */ + } + + } + + } + +} +int main(){ + + return 0; +} \ No newline at end of file diff --git a/PATTERNS/alphabet_pyramid.cpp b/PATTERNS/alphabet_pyramid.cpp new file mode 100644 index 0000000..2dad2c1 --- /dev/null +++ b/PATTERNS/alphabet_pyramid.cpp @@ -0,0 +1,15 @@ +#include +using namespace std; +int main(){ + for(int row=1;row<=5; row++){ + for(int col=1;col<=5-row;col++){ + cout<<" "; + } + for(int col=1; col<=2*row-1; col++){ + char ch = 'A' + row - 1; + cout< +using namespace std; +int main(){ + int row=1,col=1; + int n; + cout<<"Enter number: "; + cin>>n; + for (row = 1; row <=n; row++) + { + for(col=1; col<=n-row; col++){ + cout<<" "; + } + for(col=1; col<=2*row-1; col++){ + cout<<"*"; + } + + cout< +using namespace std; +class Queue{ + int front,rear,size; + int * arr; + public: + Queue(int n){ + front=rear=-1; + arr = new int[n]; + size=n; + } + bool empty(){ + return front == -1; + } + bool full(){ + return (rear+1)%size == front; + } + void push(int val){ + if(empty()){ + front=rear=0; + arr[0]=val; + } + else if(full()){ + cout<<"Queue Overflow\n"; + return; + } + else{ + rear = (rear+1)%size; + arr[rear]=val; + } + } + void pop(){ + if(empty()){ + cout<<"Queue Underflow\n"; + return; + } + else{ + if(front==rear){ + front=rear=-1; + } + else{ + front = (front+1)%size; + } + } + } + int start(){ + if(empty()){ + return -1; + } + return arr[front]; + } +}; +int main(){ + Queue q(6); + q.push(1); + q.push(2); + q.push(3); + q.push(4); + q.push(5); + q.push(6); + q.pop(); + q.pop(); + cout< +#include +using namespace std; +int main(){ + queue q; + q.push(1); + q.push(2); + q.push(3); + q.push(4); + q.push(5); + int size = q.size(); + while(size){ + int element = q.front(); + cout< +using namespace std; +class Queue{ + int front,rear,size; + int * arr; + public: + Queue(int n){ + arr = new int[n]; + front=rear=-1; + size = n; + } + bool empty(){ + return front==-1; + } + bool full(){ + return rear==size-1; + } + void push(int val){ + if(empty()){ + rear=front=0; + arr[0]=val; + return; + } + if(full()){ + cout<<"Queue Overfloww\n"; + return; + } + else{ + rear++; + arr[rear]=val; + } + } + void pop(){ + if(empty()){ + cout<<"Queue Underflow\n"; + return; + } + else{ + if(front==rear){ + front=rear=-1; + }else{ + front++; + } + } + } + int start(){ + if(empty()){ + cout<<"Queue Underflow\n"; + return -1; + } + else{ + return arr[front]; + } + } +}; +int main(){ + Queue q(5); + q.push(10); + q.push(80); + q.push(12); + q.pop(); + cout< +#include +#define MAX_SIZE 100 + +int queue[MAX_SIZE]; +int front = -1, rear = -1; + +void enqueue(int element){ + if(rear == MAX_SIZE-1){ + printf("Queue is full\n"); + return; + } + else if(front == -1 && rear == -1){ + front = rear = 0; + } + else{ + rear = rear+1; + } + queue[rear] = element; +} + +int dequeue(){ + if(front == -1 || front > rear){ + printf("Queue is empty\n"); + return -1; + } + int element = queue[front]; + front = front + 1; + return element; +} + +int peek(){ + if(front == -1 || front > rear){ + printf("Queue is empty\n"); + return -1; + } + return queue[front]; +} + +int isEmpty(){ + if(front == -1 || front > rear){ + return 1; + } + return 0; +} + +int main(){ + enqueue(4); + enqueue(19); + enqueue(10); + enqueue(20); + enqueue(1); + + dequeue(); + + // Printing the all element of the Queue + while(!isEmpty()){ + printf("%d ", dequeue()); + } + return 0; +} \ No newline at end of file diff --git a/QUEUE/queue_stl.cpp b/QUEUE/queue_stl.cpp new file mode 100644 index 0000000..793981f --- /dev/null +++ b/QUEUE/queue_stl.cpp @@ -0,0 +1,17 @@ +#include +#include +using namespace std; +int main(){ + queue s; + s.push('a'); + s.push('b'); + s.push('c'); + s.push('d'); + cout< +class Node{ + public: + int data; + Node * next; + Node(int data){ + this->data = data; + this->next = NULL; + } +}; +class Queue{ + Node * front; + Node * rear; + public: + Queue(){ + front = NULL; + rear = NULL; + } + void push(int val){ + Node * n = new Node(val); + if(front == NULL){ + front = n; + rear = n; + } + else{ + front->next = n; + front = n; + } + } + void pop(){ + if(rear==NULL){ + cout<<"Queue Underflow\n"; + return; + } + Node * todelete = rear; + rear = rear->next; + delete todelete; + } + int peek(){ + if(rear==NULL){ + cout<<"Queue Underflow\n"; + return -1; + } + return rear->data; + } +}; +int main(){ + Queue q; + q.push(20); + q.push(2); + q.push(3); + q.push(35); + q.pop(); + q.pop(); + cout< +using namespace std; + +class Solution +{ +public: + void rotateClockWise(string &s) + { + char temp = s[s.size() - 1]; + int ind = s.size() - 2; + while (ind >= 0) + { + s[ind+1] = s[ind]; + ind--; + } + s[0] = temp; + } + void rotateAntiClockWise(string &s) + { + char temp = s[0]; + int ind = 1; + while (ind < s.size()) + { + s[ind-1] = s[ind]; + ind++; + } + s[s.size()-1] = temp; + } + bool isRotated(string str1, string str2) + { + if (str1.size() != str2.size()) + { + return 0; + } + string clockwise, anticlockwise; + clockwise = str1; + + rotateClockWise(clockwise); + rotateClockWise(clockwise); + if (clockwise == str2) + { + return 1; + } + anticlockwise = str1; + rotateAntiClockWise(anticlockwise); + rotateAntiClockWise(anticlockwise); + if (anticlockwise == str2) + { + return 1; + } + return 0; + } +}; +int main() +{ + string a = "amazon"; + string b = "azonam"; + Solution s; + cout< +using namespace std; +class BasicRecursion{ + public: + void printDec(int n){ + if(n==1){ + cout<0: + printN(n-1) + print(n,end=" ") +printN(5) + +# Write a recursive funtion to print first N natural numbers in reverse order. +def printNR(n): + if n>0: + print(n,end=" ") + printNR(n-1) +print() +printNR(5) + +# Write a recursive function to print first N odd natural numbers. +def printNOdd(n): + if n>0: + printNOdd(n-1) + print(2*n-1, end=" ") +print() +printNOdd(10) + +# Write a recursive funtion to print first N even natural numbers. +def printNEven(n): + if n>0: + printNEven(n-1) + print(2*n, end=" ") +print("\nfirst 10 even numbers: ",end=" ") +printNEven(10) + diff --git a/RECURSION/10_Birthday.cpp b/RECURSION/10_Birthday.cpp new file mode 100644 index 0000000..2d96009 --- /dev/null +++ b/RECURSION/10_Birthday.cpp @@ -0,0 +1,15 @@ +#include +using namespace std; +void birthday(string name,int day){ + // TC = O(n) + if(day==0){ + cout<<"Happy Birthday, "< +using namespace std; +// Recursion +void roneToN(int n){ + if(n==0){ + return; + } + roneToN(n-1); + cout< +using namespace std; +void nEven(int n) +{ + if(n==0){ + return; + } + nEven(n-1); + if (n % 2 == 0) + { + cout << n << " "; + } +} +void rNEven(int n){ + if(n==0){ + return; + } + if(n%2 == 0){ + cout< +using namespace std; +long long int factorial(int n){ + if(n==0 || n == 1){ + return 1; + } + return n*factorial(n-1); +} +int main(){ + cout< +using namespace std; +void print(int arr[], int i,int n){ + if(i==n)return; + cout< +using namespace std; +int arr_sum(int arr[],int i, int n){ + if(i==n){ + return 0; + } + return arr[i] + arr_sum(arr,i+1,n); +} +int min_element(int arr[],int i, int n){ + if(i==n-1){ + return arr[i]; + } + return min(arr[i], min_element(arr,i+1,n)); +} +int main(){ + int arr[] = {3,7,6,2,8}; + int length = sizeof(arr)/sizeof(arr[0]); + int r = min_element(arr,0,length); + cout< +using namespace std; + +// Sum of N natural numbers +int sum(int n){ + if(n==1){ + return 1; + } + return n + sum(n-1); +} + +// Fibonacci series 0 1 1 2 3 5 8 . . . +int fib(int n){ + if(n==1 or n==0){ + return n; + } + return fib(n-1) + fib(n-2); +} +int main(){ + cout< +#include +using namespace std; +// Check if array is sorted or not +bool isSorted(vector arr, int i){ + if(i == arr.size()-1) + return true; + if(arr[i]>arr[i+1]){ + return false; + } + return isSorted(arr,i+1); +} +int main(){ + vector arr = {1,2,3,4,5}; + cout< +#include +using namespace std; +int firstOccurence(vectorv , int key, int i) +{ + if(i==v.size()-1){ + return -1; + } + if(v[i] == key){ + return i; + } + return firstOccurence(v,key,i+1); +} +int lastOccurence(vector v, int key, int i){ + if(i<0){ + return -1; + } + if(v[i] == key){ + return i; + } + return lastOccurence(v,key,i-1); +} +int main(){ + vector v = {1,2,3,34,4,5,2,4,6,5,2}; + cout< +using namespace std; +long long int pow(int x, int n){ + int ans=1; + for (int i = 0; i < n; i++) + { + ans*=x; + } + return ans; + +} +long long int power(int x, int n){ + if(n==0){ + return 1; + } + return x * power(x, n-1); +} +int optPower(int x, int n){ + if(n==0){ + return 1; + } + int halfPower = optPower(x,n/2); + int halfPowerSq = halfPower * halfPower; + // if n is odd + if(n%2 != 0){ + halfPowerSq = x * halfPowerSq; + } + return halfPowerSq; +} +int main(){ + cout< +#include +using namespace std; +vector findNeg(vector v){ + vector ans; + for(int i=0; i v){ + for (int i = 0; i < v.size()-1; i++) + { + cout< v = {1,2,-4,5,12,-9,-5}; + vector ans = findNeg(v); + display(ans); + + return 0; +} \ No newline at end of file diff --git a/RECURSION/factorial.cpp b/RECURSION/factorial.cpp new file mode 100644 index 0000000..e22433c --- /dev/null +++ b/RECURSION/factorial.cpp @@ -0,0 +1,13 @@ +#include +using namespace std; +int factorial(int n){ + if(n==1 or n==0){ + return 1; + } + return n * factorial(n-1); +} +int main(){ + int result = factorial(5); + cout<<"Factorial is "<{ + ans = 1 + while(n>=1){ + ans*=n + n-=1 + } + return ans +} +console.log("Iterative : ", factorial_iterative(5)) + +// find factorial using recursion +const factorial = (n)=>{ + if(n<=1){ // this is also valid: n==0 || n==1 + return 1; + } + return n * factorial(n-1); +} +console.log("Recursive : ",factorial(0)); \ No newline at end of file diff --git a/RECURSION/fibo.cpp b/RECURSION/fibo.cpp new file mode 100644 index 0000000..412c1c7 --- /dev/null +++ b/RECURSION/fibo.cpp @@ -0,0 +1,7 @@ +#include +using namespace std; + +int main(){ + int n; + return 0; +} \ No newline at end of file diff --git a/RECURSION/fibonacci.js b/RECURSION/fibonacci.js new file mode 100644 index 0000000..119e598 --- /dev/null +++ b/RECURSION/fibonacci.js @@ -0,0 +1,11 @@ +const fibo =(n)=>{ + if (n==0){ + return 0; + } + if(n==1){ + return 1; + } + return fibo(n-1) + fibo(n-2) +} + +console.log(fibo(4)) \ No newline at end of file diff --git a/RECURSION/is_palindrome.py b/RECURSION/is_palindrome.py new file mode 100644 index 0000000..65b7613 --- /dev/null +++ b/RECURSION/is_palindrome.py @@ -0,0 +1,49 @@ +name = "naman" +def is_palindrome(s): + start,end=0,len(s)-1 + while startend: + return 1 + if s[start]!=s[end]: + return 0 + return ris_palilndrome(s,start+1,end-1) + +# print(ris_palilndrome(name,0,len(name)-1)) + +def iterate(s): + for x in s: + print(x, end=" ") +# iterate(name) + +def riterate(s,start): + if start>len(s)-1: + return + print(s[start],end=" ") + riterate(s,start+1) +# riterate(name,0) + +"""Count Vowel""" + +def count_vowel(s): + vowel="aeiouAEIOU" + result = 0 + for c in s: + if(c in vowel): + result+=1 + return result +print(count_vowel("Abhinay")) + +def rcount_vowel(s,start,result): + vowel="aeiouAEIOU" + + rcount_vowel(s,start+1,s[start] in vowel if result=1 else result) + diff --git a/RECURSION/main.cpp b/RECURSION/main.cpp new file mode 100644 index 0000000..26da612 --- /dev/null +++ b/RECURSION/main.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +int sumOfN(int n, int sum){ + if(n==0){ + return sum; + } + return sumOfN(n-1,sum+n); +} +int sum(int n){ + if(n==1){ + return n; + } + return n + sum(n-1); +} + +int main(){ + cout< +using namespace std; +int pow(int num, int n){ + if(n==0){ + return 1; + } + // if(n==1){ + // return num; + // } + return num*pow(num,n-1); +} +int square(int n){ + if(n==1){ + return 1; + } + return n*n + square(n-1); +} +int main(){ + // int num=2,n=3; + // cout< +#include +using namespace std; +/* # Time Complexity = O(2^n), SP=O(n^2)*/ +void subseq(int arr[],int index,int n, vector>& ans, vector temp){ + if(index==n){ + ans.push_back(temp); + return; + } + // Not Inlcuded + subseq(arr,index+1,n,ans,temp); // NO + // Included + temp.push_back(arr[index]); // YES + subseq(arr,index+1,n,ans,temp); // YES + temp.pop_back(); +} +void subseqs(string &s,int index,int n,vector& ans, string temp){ + if(index==n){ + ans.push_back(temp); + return; + } + // Not included + subseqs(s,index+1,n,ans,temp); + // Included + temp.push_back(s[index]); + subseqs(s,index+1,n,ans,temp); + temp.pop_back(); +} +int main(){ + // subsequence in array + /* + int arr[] = {1,2,3}; + vector> ans; + vector temp; + subseq(arr,0,3,ans,temp); + for (int i = 0; i < ans.size(); i++) + { + for (int j = 0; j < ans[i].size(); j++) + { + cout< ans; + string temp; + subseqs(s,0,s.size(),ans,temp); + for (int i = 0; i < ans.size(); i++) + { + cout< +#include +#include + +long long int sumOfN(long long int n){ + return (n*(n+1)/2); +} + +long long int iteractiveSum(long long int n){ + long long int sum=0; + for(int i=0; i<=n; i++){ + sum = sum + i; + } + return sum; +} +long long int recursiveSum(long long int n){ + if(n == 1 || n == 0){ + return 1; + } + return n + recursiveSum(n-1); +} +int main(int argc, char *argv[]){ + // printf("%d", sumOfN(10000000000000)); + printf("%d", recursiveSum(100)); + // printf("%d", iteractiveSum(1000000000000000)); + return 0; +} \ No newline at end of file diff --git a/SEARCHING ALGOS/binary_search.c b/SEARCHING ALGOS/binary_search.c new file mode 100644 index 0000000..71e35dd --- /dev/null +++ b/SEARCHING ALGOS/binary_search.c @@ -0,0 +1,18 @@ +#include +#include +int binarySearch(int arr[], int size, int key){ + int start=0, end = size-1,mid,i=0; + while(start<=end){ + mid = (start+end)/2; + if(arr[i] == key){ + return i; + } + else if(arr[i]>key) + } +} +int main(int argc, char *argv[]){ + int arr[] = {4,8,10,23,45,78,90}; + int size = sizeof(arr)/sizeof(int); + printf("%d",size); + return 0; +} \ No newline at end of file diff --git a/SEARCHING ALGOS/linear_search.c b/SEARCHING ALGOS/linear_search.c new file mode 100644 index 0000000..7f9236a --- /dev/null +++ b/SEARCHING ALGOS/linear_search.c @@ -0,0 +1,19 @@ +#include +#include +int linearSeach(int arr[], int size, int element){ + for(int i=0; i arr[mid2]) { + left = mid2 + 1 + } else { + left = mid1 + 1 + right = mid2 - 1 + } + } + return -1 +} + +console.log(ternary_search(arr, key)) \ No newline at end of file diff --git a/SEARCHING ALGOS/ternary_search.py b/SEARCHING ALGOS/ternary_search.py new file mode 100644 index 0000000..0c40b09 --- /dev/null +++ b/SEARCHING ALGOS/ternary_search.py @@ -0,0 +1,26 @@ +''' +# Ternary Search + mid1 = l + (r-l)/3 + mid2 = r - (r-l)/3 +''' + +arr = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] +key = 60 + +def ternary_search(arr,left,right,key): + if left <= right: + mid1 = left + (right-left)//3 + mid2 = right - (right-left)//3 + + if arr[mid1] == key: + return mid1 + elif arr[mid2] == key: + return mid2 + elif key < arr[mid1]: + return ternary_search(arr,left,mid1-1,key) + elif key > arr[mid2]: + return ternary_search(arr,mid2+1,right,key) + else: + return ternary_search(arr,mid1+1,mid2-1,key) + return -1 +print(ternary_search(arr,0,len(arr)-1,key)) \ No newline at end of file diff --git a/SLIDING WINDOW/main.cpp b/SLIDING WINDOW/main.cpp new file mode 100644 index 0000000..a20c3ec --- /dev/null +++ b/SLIDING WINDOW/main.cpp @@ -0,0 +1,6 @@ +#include +using namespace std; +int main(){ + cout< +#include + +void printArray(int * A, int n){ + for(int i=0; iA[j+1]){ + temp =A[j]; + A[j] = A[j+1]; + A[j+1] = temp; + isSorted = 0; + } + + } + if(isSorted){ + return; + } + } +} +int main(){ + + int A[] = {20,12,30,15,4,2,8,1}; + int n = sizeof(A)/sizeof(A[0]); + printf("Unsorted : "); + printArray(A,n); + bubbleSort(A,n); + printf("Sorted : "); + printArray(A,n); + return 0; +} \ No newline at end of file diff --git a/SORTING ALGOS/bubble_sort.cpp b/SORTING ALGOS/bubble_sort.cpp new file mode 100644 index 0000000..6632590 --- /dev/null +++ b/SORTING ALGOS/bubble_sort.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; +void bubble_sort(int arr[],int n){ + bool isSorted=true; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n-i-1; j++) + { + if(arr[j]>arr[j+1]){ + arr[j] = arr[j] + arr[j+1]; + arr[j+1] = arr[j] - arr[j+1]; + arr[j] = arr[j] - arr[j+1]; + isSorted=false; + } + } + if(isSorted){ + return; + } + } +} +void display(int arr[], int n){ + for (int i = 0; i < n; i++) + { + cout<val[j+1]: + val[j],val[j+1]=val[j+1],val[j] + +def modified_bubble_sort(val): + n = len(val) + flag=True + for i in range(n): + for j in range(0,n-i-1): + if val[j]>val[j+1]: + val[j],val[j+1]=val[j+1],val[j] + flag=False + if flag: + break + +print(data_list) +bubble_sort(data_list) # TC=(n^2) , BEST TC = O(n) +modified_bubble_sort(data_list) # if already sorted TC=O(n) +print(data_list) + diff --git a/SORTING ALGOS/main.cpp b/SORTING ALGOS/main.cpp new file mode 100644 index 0000000..b1b6130 --- /dev/null +++ b/SORTING ALGOS/main.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +void bubble_sort(vector& arr){ + bool isSorted=false; + for(int i=0; iarr[j]){ + swap(arr[j-1],arr[j]); + } + else{ + isSorted=true; + } + } + if(isSorted){ + return; + } + } +} +int main(){ + vector arr = {1,2,3,4,8,6}; + bubble_sort(arr); + for(auto e : arr){ + cout< +#include +using namespace std; +void merge(int arr[],int start,int mid, int end){ + vector temp(end-start+1); + int left = start,right=mid+1,index=0; + while(left<=mid && right<=end){ + if(arr[left]<=arr[right]){ + temp[index] = arr[left]; + index++;left++; + } + else{ + temp[index]=arr[right]; + index++;right++; + } + } + // Agar left array me element hai + while(left<=mid){ + temp[index]=arr[left]; + index++;left++; + } + // Agar right array me element hai + while(right<=end){ + temp[index]=arr[right]; + index++;right++; + } + // Put these values in array + index=0; + while (start<=end) + { + arr[start]=temp[index]; + start++;index++; + } + +} +void merge_sort(int arr[], int start, int end){ // O(nlogn) + if(start==end){ + return; + } + int mid = start + (end-start)/2; + merge_sort(arr,start, mid); // left array + merge_sort(arr,mid+1,end); // right array + merge(arr,start,mid,end); + +} +void print_array(int arr[],int n){ + for (int i = 0; i < n; i++) + { + cout< +#include +using namespace std; +int min(int arr[], int n){ + int min_index=0; + int min=arr[0]; + for (int i = 1; i < n; i++) + if(arr[i] data: + self.item.append(data) + else: + self.item.insert(len(self.item)-1,data) + else: + self.item.append(data) + def pop(self): + if not self.is_empty(): + return self.item.pop() + else: + raise IndexError("Stack is empty.") + def peek(self): + if not self.is_empty(): + return self.item[-1] + else: + raise IndexError("Stack is empty.") + def size(self): + return len(self.item) + +s = Stack() +s.push(10) +s.push(100) +s.push(14) +s.push(9) +s.push(8) +print(s.peek()) \ No newline at end of file diff --git a/STACK/parenthesis_matching.py b/STACK/parenthesis_matching.py new file mode 100644 index 0000000..bf2c054 --- /dev/null +++ b/STACK/parenthesis_matching.py @@ -0,0 +1,17 @@ +from stack import Stack + +s="[{()}]" + +def parenthesis_maching(string=""): + stc=Stack() + for c in s: + if c == '(' or c == '{' or c == '[': + stc.push(c) + elif c == ')' or c == '}' or c == ']': + if not stc.is_empty(): + stc.pop() + else: + return False + return stc.is_empty() + +print(parenthesis_maching("(]")) diff --git a/STACK/problems.md b/STACK/problems.md new file mode 100644 index 0000000..6ea5f3d --- /dev/null +++ b/STACK/problems.md @@ -0,0 +1,9 @@ +1. Implement two stacks in an array https://www.geeksforgeeks.org/problems/implement-two-stacks-in-an-array/1 +2. Reverse String https://leetcode.com/problems/reverse-string/description/ +3. Insert an Element at the Bottom of a Stack https://www.geeksforgeeks.org/problems/insert-an-element-at-the-bottom-of-a-stack/0 +4. Make the array beautiful https://www.geeksforgeeks.org/problems/make-the-array-beautiful--170647/0 +5. String Manipulation https://www.geeksforgeeks.org/problems/string-manipulation3706/1 +6. Valid Parentheses https://leetcode.com/problems/valid-parentheses/description/ +7. Minimum Add to Make Parentheses Valid https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/description/ +8. Next Greater Element https://www.geeksforgeeks.org/problems/next-larger-element-1587115620/1 +9. diff --git a/STACK/push_at_bottom.py b/STACK/push_at_bottom.py new file mode 100644 index 0000000..16bfb86 --- /dev/null +++ b/STACK/push_at_bottom.py @@ -0,0 +1,12 @@ +from stack import * + +s = Stack() +s.push(1) +s.push(2) +s.push(3) +# s.print_stack() +# s.reverse_stack() +s.print_stack() + + + diff --git a/STACK/reverse_string_using_stack.cpp b/STACK/reverse_string_using_stack.cpp new file mode 100644 index 0000000..64c9f22 --- /dev/null +++ b/STACK/reverse_string_using_stack.cpp @@ -0,0 +1,24 @@ +#include +#include +using namespace std; +void reverseString(vector &s) +{ + stack st; + for (int i = 0; i < s.size(); i++) + { + st.push(s[i]); + } + for (int i = 0; i < s.size(); i++) + { + s[i] = st.top(); + st.pop(); + } +} +int main() +{ + vector s = {'h', 'e', 'l', 'l', 'o'}; + string name = "Abhi"; + reverseString(s); + + return 0; +}; \ No newline at end of file diff --git a/STACK/reverse_string_using_stack.exe b/STACK/reverse_string_using_stack.exe new file mode 100644 index 0000000..ee75e19 Binary files /dev/null and b/STACK/reverse_string_using_stack.exe differ diff --git a/STACK/stack.cpp b/STACK/stack.cpp new file mode 100644 index 0000000..09b2479 --- /dev/null +++ b/STACK/stack.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +using namespace std; +/* +The functions associated with stack are: +empty() – Returns whether the stack is empty – Time Complexity : O(1) +size() – Returns the size of the stack – Time Complexity : O(1) +top() – Returns a reference to the top most element of the stack – Time Complexity : O(1) +push(g) – Adds the element ‘g’ at the top of the stack – Time Complexity : O(1) +pop() – Deletes the most recent entered element of the stack – Time Complexity : O(1) +*/ +int main() +{ + stack st; + string s = "leEeetcode"; + string ans = ""; + st.push(s[0]); + for (int i = 1; i < s.size(); i++) + { + if (st.top() == char(tolower(s[i]))){ + if(st.top() == s[i]){ + st.push(s[i]); + } + else{ + st.pop(); + } + } + else if (st.top() == s[i]){ + st.push(s[i]); + } + else{ + st.push(s[i]); + } + } + while(!st.empty()){ + char ch = st.top(); + ans=ch + ans; + st.pop(); + } + cout< +#include + +struct stack { + int size; + int top; + char *arr; +}; + +int isEmpty(struct stack *ptr) { + if (ptr->top == -1) { + return 1; + } + return 0; +} + +int isFull(struct stack *ptr) { + if (ptr->top == ptr->size - 1) { + return 1; + } + return 0; +} + +void push(struct stack *ptr, char val) { + if (isFull(ptr)) { + printf("Stack Overflow!"); + } else { + ptr->top++; + ptr->arr[ptr->top] = val; + } +} + +char pop(struct stack *ptr) { + if (isEmpty(ptr)) { + printf("Stack Underflow!"); + return -1; + } else { + char val = ptr->arr[ptr->top]; + ptr->top--; + return val; + } +} + +int parenthesisMatch(char *exp) { + // Create and Initialize the stack + struct stack *sp = (struct stack*) malloc(sizeof(struct stack)); + sp->size = 100; + sp->top = -1; + sp->arr = (char*) malloc(sp->size * sizeof(char)); + + for (int i = 0; exp[i] != '\0'; i++) { + if (exp[i] == '(') { + push(sp, '('); + } else if (exp[i] == ')') { + if (isEmpty(sp)) { + return 0; + } + pop(sp); + } + } + + if (isEmpty(sp)) { + return 1; + } + return 0; +} + +int main() { + char exp[] = "8*(9+(4*1))"; + + if (parenthesisMatch(exp)) { + printf("Parenthesis is Match"); + } else { + printf("Parenthesis is not Match"); + } + + return 0; +} diff --git a/STACK/stack_inherit_list.py b/STACK/stack_inherit_list.py new file mode 100644 index 0000000..58b9dd1 --- /dev/null +++ b/STACK/stack_inherit_list.py @@ -0,0 +1,28 @@ +class Stack(list): + def is_empty(self): + return len(self) == 0 + def push(self,data): + self.append(data) + def pop(self): + if not self.is_empty(): + return super().pop() + else: + raise IndexError("Stack is empty") + def peek(self): + if not self.is_empty(): + return self[-1] + else: + raise IndexError("Stack is empty") + def size(self): + return len(self) + def insert(self, index,data): + raise AttributeError("No attribute 'insert' in Stack.") + + +s1 = Stack() +# s1.insert(0,10) +s1.push(10) +s1.push(20) +s1.push(30) +print("top value =", s1.peek()) + \ No newline at end of file diff --git a/STACK/stack_inherit_sll.py b/STACK/stack_inherit_sll.py new file mode 100644 index 0000000..6f50a57 --- /dev/null +++ b/STACK/stack_inherit_sll.py @@ -0,0 +1,52 @@ +import sys +sys.path.append("../linked list") +from singly_ll import SinglyLL + +class Stack(SinglyLL): + def __init__(self): + super().__init__() + self.item_count = 0 + def is_empty(self): + return self.start == None + + def push(self,item): + self.insert_at_start(item) + self.item_count+=1 + def pop(self): + if not self.is_empty(): + self.item_count-=1 + return self.delete_first() + else: + raise IndexError("Stack Underflow") + def peek(self): + if not self.is_empty(): + return self.start.data + else: + raise IndexError("Stack Underflow") + def size(self): + return self.item_count + # restrict other object methods + def print_list(self): + raise AttributeError("no attribute 'print_list' in Stack.") + def insert_after(self): + raise AttributeError("no attribute 'insert_after' in Stack.") + def insert_at_last(self): + raise AttributeError("no attribute 'insert_at_last' in Stack.") + def delete_last(self): + raise AttributeError("no attribute 'delete_last' in Stack.") + def delete_item(self): + raise AttributeError("no attribute 'delete_item' in Stack.") + +st = Stack() +st.push(4) +print(st.is_empty()) +st.push(1) +st.push(19) +st.push(6) +st.pop() +print(st.size()) +print(st.peek()) + + + + diff --git a/STACK/stack_using_list.py b/STACK/stack_using_list.py new file mode 100644 index 0000000..15bc70a --- /dev/null +++ b/STACK/stack_using_list.py @@ -0,0 +1,45 @@ +class Stack: + def __init__(self): + self.item=[] + def is_empty(self): + return len(self.item) == 0 + def push(self,data): + self.item.append(data) + def pop(self): + if not self.is_empty(): + return self.item.pop() + else: + raise IndexError("Stack is empty.") + def peek(self): + if not self.is_empty(): + return self.item[-1] + else: + raise IndexError("Stack is empty.") + def size(self): + return len(self.item) + +stack = Stack() +stack.push(10) +stack.push(20) +stack.push(30) +stack.push(40) +print("Top element is", stack.peek()) +print("Removed element is", stack.pop()) +print("Top element is", stack.peek()) + + + +"""" Time Complexity = O(n) : Reverse String Using Stack""" +def reverse_string(string=""): + s = Stack() + for x in string: + s.push(x) + y=0 + rs="" + while y < s.size(): + rs = rs + s.pop() + y+1 + return rs + +name = "Abhi" +print(reverse_string(name)) \ No newline at end of file diff --git a/STACK/stack_using_sll.py b/STACK/stack_using_sll.py new file mode 100644 index 0000000..f6fde74 --- /dev/null +++ b/STACK/stack_using_sll.py @@ -0,0 +1,31 @@ +import sys +sys.path.append("../linked list") +from singly_ll import SinglyLL + +class Stack: + def __init__(self): + self.start = SinglyLL() + self.item_count=0 + def is_empty(self): + return self.item_count == 0 + def push(self,data): + self.start.insert_at_start(data) + self.item_count+=1 + def pop(self): + data=self.start.delete_first() + self.item_count-=1 + return data + def peek(self): + if not self.item_count: + return self.start.start.data + def size(self): + return self.item_count + +s = Stack() +s.push(1) +s.push(2) +s.push(3) +s.push(4) +print(s.peek()) +s.pop() +print(s.size()) \ No newline at end of file diff --git a/STACK/two_stack_in_an_array.cpp b/STACK/two_stack_in_an_array.cpp new file mode 100644 index 0000000..ea4769f --- /dev/null +++ b/STACK/two_stack_in_an_array.cpp @@ -0,0 +1,54 @@ +#include +#include +using namespace std; +class TwoStack{ + public : + int *arr; + int size; + int top1; + int top2; + TwoStack(int n){ + size = n; + arr = new int[n]; + top1 = -1; + top2 = size; + } + void push1(int x){ + if(top1+1==top2){ + cout<<"Stack Overflow"; + return; + } + top1++; + arr[top1] = x; + } + void push2(int x){ + if(top2-1==top1){ + cout<<"Stack Overflow"; + return; + } + top2--; + arr[top2] = x; + } + int pop1(){ + if(top1==-1){ + cout<<"Stack Underflow"; + return -1; + } + int res = arr[top1]; + top1--; + return res; + } + int pop2(){ + if(top2==size){ + cout<<"Stack Underflow"; + return -1; + } + int res = arr[top2]; + top2++; + return res; + } +}; +int main(){ + + return 0; +}; \ No newline at end of file diff --git a/STRINGS/problems.md b/STRINGS/problems.md new file mode 100644 index 0000000..ddd64f0 --- /dev/null +++ b/STRINGS/problems.md @@ -0,0 +1,34 @@ +0. To Lower Case https://leetcode.com/problems/to-lower-case/description/ +1. Reverse String https://leetcode.com/problems/reverse-string/description/ +2. Merge Sorted Array https://leetcode.com/problems/merge-sorted-array/description/ +3. Score of a String https://leetcode.com/problems/score-of-a-string/description/ +4. Find Words Containing Character https://leetcode.com/problems/find-words-containing-character/description/ +5. Maximum Number of Words Found in Sentences https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/description/ +6. Count Items Matching a Rule https://leetcode.com/problems/count-items-matching-a-rule/description/ +7. Reverse Prefix of Word https://leetcode.com/problems/reverse-prefix-of-word/description/ +8. Sort the People https://leetcode.com/problems/sort-the-people/submissions/1343814700/ +9. Faulty Keyboard https://leetcode.com/problems/faulty-keyboard/description/ +10. Sorting the Sentence https://leetcode.com/problems/sorting-the-sentence/description/ +11. Check If Two String Arrays are Equivalent https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/description/ +12. Goal Parser Interpretation https://leetcode.com/problems/goal-parser-interpretation/description/ +13. Find First Palindromic String in the Array https://leetcode.com/problems/find-first-palindromic-string-in-the-array/description/ +14. Count the Number of Consistent Strings https://leetcode.com/problems/count-the-number-of-consistent-strings/description/ +15. Find the Index of the First Occurrence in a String https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/ +16. Reverse Words in a String III https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ +17. Valid Palindrome https://leetcode.com/problems/valid-palindrome/description/ +18. Longest Palindrome https://leetcode.com/problems/longest-palindrome/description/ +19. Reverse Words in a String https://leetcode.com/problems/reverse-words-in-a-string/description/ +20. Defanging an IP Address https://leetcode.com/problems/defanging-an-ip-address/description/ +21. String Rotated by 2 Places https://www.geeksforgeeks.org/problems/check-if-string-is-rotated-by-two-places-1587115620/1 +22. Check if the Sentence Is Pangram https://leetcode.com/problems/check-if-the-sentence-is-pangram/description/ +23. Split a String in Balanced Strings https://leetcode.com/problems/split-a-string-in-balanced-strings/description/ +24. Split Strings by Separator https://leetcode.com/problems/split-strings-by-separator/description/ +25. Count Asterisks https://leetcode.com/problems/count-asterisks/description/ +26. Check if a String Is an Acronym of Words https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words/description/ +27. Word Pattern https://leetcode.com/problems/word-pattern/description/ +28. First Letter to Appear Twice https://leetcode.com/problems/first-letter-to-appear-twice/description/ +29. Excel Sheet Column Title https://leetcode.com/problems/excel-sheet-column-title/description + +30. Sort Vowels in a String https://leetcode.com/problems/sort-vowels-in-a-string/description/ +31. Isomorphic Strings https://leetcode.com/problems/isomorphic-strings/description/ +32. \ No newline at end of file diff --git a/STRINGS/string.py b/STRINGS/string.py new file mode 100644 index 0000000..cdbdfd0 --- /dev/null +++ b/STRINGS/string.py @@ -0,0 +1,11 @@ +columnNumber=28 +res="" +while columnNumber > 0: + columnNumber-=1 + ch = ord('A') + (columnNumber%26) + print(ch) + res+=chr(ch) + print(res) + columnNumber=columnNumber//26 + print(columnNumber) +print(res) \ No newline at end of file diff --git a/TREES/BST.cpp b/TREES/BST.cpp new file mode 100644 index 0000000..4b78919 --- /dev/null +++ b/TREES/BST.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; +class BST{ + public: + int data; + BST *left, *right; + BST(int value){ + this->data = value; + this->left = this->right = NULL; + } +}; +BST* insert(BST* root, int value){ + if(!root){ + BST * node = new BST(value); + return node; + } + if(value < root->data){ + root->left = insert(root->left,value); + } + else{ + root->right = insert(root->right,value); + } + return root; +} +void preorder(BST*root){ + if(root){ + cout<< root->data<<" "; + preorder(root->left); + preorder(root->right); + } +} +void inorder(BST* root){ + if(!root) return; + inorder(root->left); + cout<data<<" "; + inorder(root->right); +} +bool search(BST* root,int val){ + if(!root) return 0; + if(val==root->data) return 1; + if(valdata){ + return search(root->left,val); + } + else{ + return search(root->right,val); + } + +} +BST* remove(BST* root, int x){ + +} +int main(){ + int arr[] = {3,4,7,1,6,8}; + BST * root = NULL; + for(int i=0; i<6; i++){ + root = insert(root,arr[i]); + } + + inorder(root); + cout< root.item: + root.right=self.rinsert(root.right,data) + return root + def insert(self,data): + self.root = self.rinsert(self.root, data) + def rsearch(self,root,data): + if root is None or root.item == data: + return root + if data root.item: + root.right = self.rinsert(root.right,data) + return root + + def inorder(self): # O(log n) + result=[] + self.rinorder(self.root,result) + return result + def rinorder(self, root, result): # O(log n) + if root: + self.rinorder(root.left,result) + result.append(root.item) + self.rinorder(root.right,result) + def size(self): # O(log n) + return len(inorder()) + def preorder(self): # O(log n) + result=[] + self.rpreorder(self.root,result) + return result + def rpreorder(self,root,result): # O(log n) + if root: + result.append(root.item) + self.rpreorder(root.left,result) + self.rpreorder(root.right,result) + def postorder(self): # O(log n) + result=[] + self.rpostorder(self.root,result) + return result + def rpostorder(self,root,result): # O(log n) + if root: + self.rpostorder(root.left,result) + self.rpostorder(root.right,result) + result.append(root.item) + def min(self): # O(log n) + return self.rmin(self.root) + def rmin(self,root): # O(log n) + if root: + while root.left: + root = root.left + return root.item + return None + def max(self): # O(log n) + return self.rmax(self.root) + def rmax(self,root): # O(log n) + if root: + while root.right: + root = root.right + return root.item + return None + def height(self): # O(n) + return self.rheight(self.root) + def rheight(self,root): + if root: + lh = self.rheight(root.left) + rh = self.rheight(root.right) + return max(lh,rh) + 1 + return 0 + # count of nodes of tree - O(n) + def count(self): + return self.rcount(self.root) + def rcount(self,root): + if root: + return self.rcount(root.left) + self.rcount(root.right) +1 + return 0 + # sum of nodes + def sum(self): + return self.rsum(self.root) + def rsum(self,root): # O(n) + if root: + return self.rsum(root.left) + self.rsum(root.right) + root.item + return 0 + +bt = BinaryTree() +bt.insert(10) +bt.insert(5) +bt.insert(1) +bt.insert(20) +# bt.insert(0) +# bt.insert(30) + +# bt.insert(20) # it is like set() duplicate value of not inserted +# for item in bt.inorder(): +# print(item,end=" ") + +# print() +# print(bt.min()) +# print(bt.max()) +print("height of root =",bt.height()) +print("no. of nodes =",bt.count()) +print("sum of nodes value =",bt.sum()) + diff --git a/TREES/a.exe b/TREES/a.exe new file mode 100644 index 0000000..c9142e4 Binary files /dev/null and b/TREES/a.exe differ diff --git a/TREES/avl_rotation.c b/TREES/avl_rotation.c new file mode 100644 index 0000000..75be64b --- /dev/null +++ b/TREES/avl_rotation.c @@ -0,0 +1,82 @@ +#include +#include +struct Node{ + int key; + struct Node * left; + struct Node * right; + int height; +}; + +int getHeight(struct Node * n){ + if(n==NULL) + return 0; + return n->height; +} +struct Node * createNode(int key){ + struct Node * node = (struct Node *)malloc(sizeof(struct Node)); + node->key = key; + node->left = NULL; + node->right = NULL; + node->height = 1; + return node; +} +int getBalanceFactor(struct Node * n){ + if(n==NULL) + return 0; + return getHeight(n->left) - getHeight(n->right); +} + +struct Node * rightRotate(struct Node * y){ + struct Node * x = y->left; + struct Node * T2 = x->right; + + x->right = y; + y->left = T2; + + y->height = max(getHeight(y->left), getHeight(y->right)); + x->height = max(getHeight(x->left), getHeight(x->right)); + + return x; +} + +struct Node * leftRotate(struct Node * x){ + struct Node * y = x->right; + struct Node * T2 = y->left; + + y->left = x; + x->right = T2; + + y->height = max(getHeight(y->left), getHeight(y->right)) + 1; + x->height = max(getHeight(x->left), getHeight(x->right)) + 1; + + return x; +} + +struct Node * insert(struct Node * node, int key){ + if(node==NULL){ + return createNode(key); + } + + if(key < node->key){ + node->left = insert(node->left, key); + } + else if(key > node->key){ + node->right = insert(node->right, key); + } + return node; + node->height = 1 + max(getHeight(node->left), getHeight(node->right)); + int bf = getBalanceFactor(node); + + // Left Left Case + + // Left Right Case + + // Right Right Case + + // Right Left Case +} + +int main(){ + + return 0; +} \ No newline at end of file diff --git a/TREES/avl_tree.cpp b/TREES/avl_tree.cpp new file mode 100644 index 0000000..42650a1 --- /dev/null +++ b/TREES/avl_tree.cpp @@ -0,0 +1,59 @@ +#include +using namespace std; +class Node{ + public: + int data,height; + Node *left, *right; + + Node(int value){ + data = value; + height = 1; + left = right = NULL; + } +}; + +int getHeight(Node *root){ + if(!root) return 0; + return root->height; +} +int getBalance(Node* root){ + return getHeight(root->left) - getHeight(root->right); +} +Node* insert(Node * root,int key){ + // Doesn't exist + if(!root){ + return new Node(key); + } + // Exist + if(keydata){ + root->left = insert(root->left,key); // left Side + } + else if(key>root->data){ + root->right = insert(root->right,key); // Right Side + } + else{ + return root; // Duplication values not allowed + } + + // Update Height + root->height = 1 + max(getHeight(root->left),getHeight(root->right)); + + // Balancing Check + int balance = getBalance(root); +} +int main(){ + + // Duplicate elements not allowed + Node *root = NULL; + + root = insert(root,10); + root = insert(root,20); + root = insert(root,30); + root = insert(root,50); + root = insert(root,70); + root = insert(root,5); + root = insert(root,100); + root = insert(root,95); + + return 0; +} \ No newline at end of file diff --git a/TREES/binary_search.c b/TREES/binary_search.c new file mode 100644 index 0000000..a46f700 --- /dev/null +++ b/TREES/binary_search.c @@ -0,0 +1,28 @@ +#include +#include +int binarySearch(int arr[], int size, int element){ + int low,high,mid; + low = 0; + high = size-1; + while(low<=high){ + mid = (low+high)/2; + if(arr[mid] == element){ + return mid; + } + if(arr[mid] +#include + +struct node{ + int data; + struct node * left; + struct node * right;; +}; + +/* + 10 + / \ +BINARY TREE = 4 8 + / \ \ + 2 5 20 +*/ + +void inorder(struct node * root){ + if(root == NULL){ + return; + } + inorder(root->left); + printf("%d ", root->data); + inorder(root->right); + +} + +int main(){ + struct node * root = (struct node * )malloc(sizeof(struct node)); + struct node * a = (struct node * )malloc(sizeof(struct node)); + struct node * b = (struct node * )malloc(sizeof(struct node)); + struct node * x = (struct node * )malloc(sizeof(struct node)); + struct node * y = (struct node * )malloc(sizeof(struct node)); + struct node * z = (struct node * )malloc(sizeof(struct node)); + + root->data = 10; + a->data = 4; + b->data = 8; + x->data = 2; + y->data = 5; + z->data = 20; + + + root->left = a; + root->right = b; + + a->left = x; + a->right = y; + + b->left = NULL; + b->right = z; + + x->left = NULL; + x->right = NULL; + + y->left = NULL; + y->right = NULL; + + z->left = NULL; + z->right = NULL; + + + inorder(root); + + return 0; +} \ No newline at end of file diff --git a/TREES/create_bt.cpp b/TREES/create_bt.cpp new file mode 100644 index 0000000..a3cdac7 --- /dev/null +++ b/TREES/create_bt.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; +class Node{ + public: + int data; + Node *left, *right; + Node(int data){ + this->data = data; + left = right = NULL; + } +}; +Node * createBinaryTree(){ + int x; + cin>>x; + if(x==-1) return NULL; + Node * root = new Node(x); + root->left = createBinaryTree(); + root->right = createBinaryTree(); + return root; +} +int main(){ + int arr[] = {1,2,3,-1,-1,4,-1,-1,5,6,-1,-1,7,-1,-1}; + + Node *root = createBinaryTree(); + + return 0; +} \ No newline at end of file diff --git a/TREES/main.cpp b/TREES/main.cpp new file mode 100644 index 0000000..918c6a2 --- /dev/null +++ b/TREES/main.cpp @@ -0,0 +1,152 @@ +#include +using namespace std; +struct node +{ + int item; + node *left; + node *right; +}; + +class BST +{ +private: + node *root; + void rpreorder(node*); + void rinorder(node*); + void rpostorder(node*); + +public: + BST(); + bool empty(); + void insert(int); + void preorder(); + void inorder(); + void postorder(); + node* search(int data); +}; +BST::BST() +{ + root = NULL; +} +bool BST::empty() +{ + return root == NULL; +} +void BST::insert(int data) +{ + + node *ptr; + if (root == NULL) + { + node *n = new node; + n->right = NULL; + n->item = data; + n->right = NULL; + root = n; + } + else + { + bool flag = true; + ptr = root; + while (flag) + { + if (data == ptr->item) + break; + if (data > ptr->item) + { + // left subtree; + if (!ptr->left) + { + node *n = new node; + n->right = NULL; + n->item = data; + n->right = NULL; + ptr->left = n; + flag = false; + } + else + { + ptr = ptr->left; + } + } + else + { + // right subtree + if (!ptr->right) + { + node *n = new node; + n->right = NULL; + n->item = data; + n->right = NULL; + ptr->right = n; + flag = false; + } + else + { + ptr = ptr->right; + } + } + } + } +} + +void BST::rpreorder(node * root){ + if(root){ + cout<item<<" "; + rpreorder(root->left); + rpreorder(root->right); + } +} +void BST::preorder(){ + rpreorder(root); +} +void BST::rinorder(node * root){ + if(root){ + rinorder(root->left); + cout<item<<" "; + rinorder(root->right); + } +} +void BST::inorder(){ + rinorder(root); +} + +void BST::rpostorder(node * root){ + if(root){ + rpostorder(root->left); + rpostorder(root->right); + cout<item<<" "; + } +} +void BST::postorder(){ + rpostorder(root); +} + +node * BST::search(int data){ + node * ptr = root; + while(ptr){ + if(ptr->item == data){ + return ptr; + } + else if(data < ptr->item){ + ptr = ptr->left; + } + else{ + ptr = ptr->right; + } + } + return NULL; +} +int main() +{ + BST n = BST(); + // cout<item; + return 0; +} \ No newline at end of file diff --git a/TREES/main.exe b/TREES/main.exe new file mode 100644 index 0000000..6bacb2e Binary files /dev/null and b/TREES/main.exe differ diff --git a/TREES/main.py b/TREES/main.py new file mode 100644 index 0000000..7019da0 --- /dev/null +++ b/TREES/main.py @@ -0,0 +1,2 @@ +s='ab-cd' +print(s[::-1]) \ No newline at end of file diff --git a/TREES/readme.md b/TREES/readme.md new file mode 100644 index 0000000..8d89c00 --- /dev/null +++ b/TREES/readme.md @@ -0,0 +1,26 @@ +1. Binary Tree Inorder Traversal https://leetcode.com/problems/binary-tree-inorder-traversal/description/ +2. Binary Tree Postorder Traversal https://leetcode.com/problems/binary-tree-postorder-traversal/description/ +3. Binary Tree Preorder Traversal https://leetcode.com/problems/binary-tree-preorder-traversal/description/ +4. Level order traversal https://www.geeksforgeeks.org/problems/level-order-traversal/1 +5. Second Minimum Node In a Binary Tree https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/ +6. Size of Binary Tree https://www.geeksforgeeks.org/problems/size-of-binary-tree/1 +7. Sum of Binary Tree https://www.geeksforgeeks.org/problems/sum-of-binary-tree/0 +8. Count Leaves in Binary Tree https://www.geeksforgeeks.org/problems/count-leaves-in-binary-tree/1 +9. Count Non-Leaf Nodes in Tree https://www.geeksforgeeks.org/problems/count-non-leaf-nodes-in-tree/0 +10. Height of Binary Tree https://www.geeksforgeeks.org/problems/height-of-binary-tree/1 +11. Largest value in each level https://www.geeksforgeeks.org/problems/largest-value-in-each-level/1s +12. Identical Trees https://www.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1 +13. Same Tree https://leetcode.com/problems/same-tree/description/ +14. Binary Tree Level Order Traversal https://leetcode.com/problems/binary-tree-level-order-traversal/description/ +15. Mirror Tree https://www.geeksforgeeks.org/problems/mirror-tree/1 +16. Invert Binary Tree https://leetcode.com/problems/invert-binary-tree/description/ +17. Balanced Tree Check https://www.geeksforgeeks.org/problems/check-for-balanced-tree/1 +18. Balanced Binary Tree https://leetcode.com/problems/balanced-binary-tree/description/ +19. Maximum Depth of Binary Tree https://leetcode.com/problems/maximum-depth-of-binary-tree/description +30. Kth Smallest Element in a BST https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ +31. Path Sum https://leetcode.com/problems/path-sum/description/ +32. Path Sum II https://leetcode.com/problems/path-sum-ii/description/ +33. Preorder traversal (Iterative) https://www.geeksforgeeks.org/problems/preorder-traversal-iterative/1 +34. Delete a node from BST https://www.geeksforgeeks.org/problems/delete-a-node-from-bst/1 +35. Check for BST +36. Minimum Depth of Binary Tree https://leetcode.com/problems/minimum-depth-of-binary-tree/description/ \ No newline at end of file diff --git a/TREES/tempCodeRunnerFile.py b/TREES/tempCodeRunnerFile.py new file mode 100644 index 0000000..ab00e84 --- /dev/null +++ b/TREES/tempCodeRunnerFile.py @@ -0,0 +1,2 @@ + + s+=" " \ No newline at end of file diff --git a/TREES/treenode.py b/TREES/treenode.py new file mode 100644 index 0000000..e69de29 diff --git a/TWO POINTERS/main.cpp b/TWO POINTERS/main.cpp new file mode 100644 index 0000000..6288b88 --- /dev/null +++ b/TWO POINTERS/main.cpp @@ -0,0 +1,6 @@ +#include +using namespace std; +int main(){ + cout<< 11/double(2) <