diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..68539a2 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# These are supported funding model platforms + +github: # [@kasakvaish] +patreon: # @kasakvaish diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..d46b084 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,74 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '36 9 * * 6' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'cpp', 'java', 'python' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/greetings.yml b/.github/workflows/greetings.yml new file mode 100644 index 0000000..4677434 --- /dev/null +++ b/.github/workflows/greetings.yml @@ -0,0 +1,16 @@ +name: Greetings + +on: [pull_request_target, issues] + +jobs: + greeting: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/first-interaction@v1 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + issue-message: "Message that will be displayed on users' first issue" + pr-message: "Message that will be displayed on users' first pull request" diff --git a/.gitignore b/.gitignore index 3af1e24..ef13838 100644 --- a/.gitignore +++ b/.gitignore @@ -1044,4 +1044,7 @@ dkms.conf # Raspberry Pi Pico disassembler file *.dis -*:tests \ No newline at end of file +*:tests +*.out + +Dockerfile \ No newline at end of file diff --git a/0072-edit-distance.cpp b/0072-edit-distance.cpp new file mode 100644 index 0000000..64bb346 --- /dev/null +++ b/0072-edit-distance.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + + int f(string word1, string word2,int i,int j,vector>&dp){ + if(i<0) return j+1; + if(j<0) return i+1; + if(dp[i][j]!=-1) return dp[i][j]; + if(word1[i]==word2[j]){ + return dp[i][j] = 0 + f(word1,word2,i-1,j-1,dp); + } + return dp[i][j] = 1 + min(f(word1,word2,i-1,j,dp),min(f(word1,word2,i-1,j-1,dp),f(word1,word2,i,j-1,dp))); + } + + + int minDistance(string word1, string word2) { + int n= word1.size(); + int m = word2.size(); + vector>dp(word1.size()+1,vector(word2.size()+1,-1)); + for(int i=0;i<=n;i++){ + dp[i][0]=i; + } + for(int j=0;j<=m;j++){ + dp[0][j]=j; + } + for(int i=1;i<=n;i++){ + for(int j=1;j<=m;j++){ + if(word1[i-1]==word2[j-1]){ + dp[i][j] = 0 + dp[i-1][j-1]; + } + else + dp[i][j] = 1 + min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1])); + } + } + return dp[n][m]; + } +}; diff --git a/01Matrix.cpp b/01Matrix.cpp deleted file mode 100644 index e289c7a..0000000 --- a/01Matrix.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector> updateMatrix(vector>& mat) { - queue> q; - - vector> ans(mat.size(), vector(mat[0].size(), -1)); - - for(int i = 0; i < mat.size(); i++) { - for(int j = 0; j < mat[0].size(); j++) { - if(mat[i][j] == 0) { - q.push({i, j}); - ans[i][j] = 0; - } - } - } - - int m = mat.size(); - int n = mat[0].size(); - - while(not q.empty()) { - int i = q.front().first; - int j = q.front().second; - - if(checkvalid(i+1, j, m, n) and ans[i+1][j] == -1) { - q.push({i+1, j}); - ans[i+1][j] = ans[i][j]+1; - } - - if(checkvalid(i-1, j, m, n) and ans[i-1][j] == -1) { - q.push({i-1, j}); - ans[i-1][j] = ans[i][j]+1; - } - - if(checkvalid(i, j+1, m, n) and ans[i][j+1] == -1) { - q.push({i, j+1}); - ans[i][j+1] = ans[i][j]+1; - } - - if(checkvalid(i, j-1, m, n) and ans[i][j-1] == -1) { - q.push({i, j-1}); - ans[i][j-1] = ans[i][j]+1; - } - - q.pop(); - } - - return ans; - - } - - bool checkvalid(int i, int j, int m, int n) { - if(i < 0 or j < 0 or i >= m or j >= n) return false; - - return true; - } - -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< 1 && n <= 4) + return false; + + int sum = 0; + while(n > 0) { + int m = n % 10; + sum = sum + (m * m); + n = n / 10; + } + + return isHappy(sum); + } +}; \ No newline at end of file diff --git a/1-two-sums.cpp b/1-two-sums.cpp new file mode 100644 index 0000000..cc3d391 --- /dev/null +++ b/1-two-sums.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + vectorresult; + for(int i =0;i +#include +#include + +using namespace std; + +class Solution +{ +public: + TreeNode *sortedArrayToBST(vector &nums) + { + return helper(nums, 0, nums.size() - 1); + } + + TreeNode *helper(vector &nums, int left, int right) + { + + // base case + // If the left pointer crosses right return null; + if (left > right) + { + return NULL; + } + + // as middle of the array will be the root node + int mid = (left + right) / 2; + TreeNode *temp = new TreeNode(nums[mid]); + + // left part from middle will be left subtree + temp->left = helper(nums, left, mid - 1); + + // right part of array will be right subtree + temp->right = helper(nums, mid + 1, right); + return temp; + } +}; \ No newline at end of file diff --git a/1207_Unique_Number_Of_Occurrences.cpp b/1207_Unique_Number_Of_Occurrences.cpp new file mode 100644 index 0000000..3d45159 --- /dev/null +++ b/1207_Unique_Number_Of_Occurrences.cpp @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/unique-number-of-occurrences/ + +class Solution { +public: + bool uniqueOccurrences(vector& arr) { + bool flag{true}; + map m; + for(int i{0}; i count; + for(auto val : m){ + count.push_back(val.second); + } + sort(count.begin(),count.end()); + for(int i{0}; i>& a) { + int i, n, val, x, y; + n = a.size(); + x = a[1][0] - a[0][0]; + y = a[1][1] - a[0][1]; + for(i=0; i'Z')&&(s[i]<'a'|| s[i]>'z')&&(s[i]<'0' || s[i]>'9')){ + s.erase(i,1); + i--; + } + } + if(s.compare("")==0){ + return true; + } + //all small + for(int i =0;i& wordList) { + + unordered_map> mp; + unordered_map bank,visited; + vector mywordList; + + mywordList.push_back(beginWord); + bank[beginWord]=true; + for(auto it:wordList){ + bank[it]=true; + mywordList.push_back(it); + } + + for(int i=0;i q; + q.push(beginWord); + visited[beginWord]=true; + int level=2; + + while(!q.empty()) + { + int n=q.size(); + for(int i=0;i> diagonalSort(vector>& mat) { + int m = mat.size(); + int n = mat[0].size(); + cout << n; + int d = m*n-1; + + vector> ans(mat.size(),vector(mat[0].size(),0)); + + + for(int i = 0 ; i < m ; i++ ){ + vector diag; + int a = i; + int b = 0; + + while(a diag; + int a = 0; + int b = i; + + while(b& a) { + int i, n=a.size(), size=n, ans=1; + unordered_map mp; + priority_queue> pq; + for(auto x: a) mp[x]++; + for(auto x: mp) { + pq.push({x.second, x.first}); + } + while(size-pq.top().first > (n/2)) { + size -= pq.top().first; pq.pop(); + ans++; + } + return ans; + } +}; \ No newline at end of file diff --git a/136-single-number b/136-single-number new file mode 100644 index 0000000..8ddd4b2 --- /dev/null +++ b/136-single-number @@ -0,0 +1,13 @@ +#include +class Solution { +public: + int singleNumber(vector& nums) { + //approach 1 + int xorresult = 0; + for(int i =0;i& nums) { + int ans = 0; + for(int i = 0; i < nums.size(); i++){ + for(int j = i+1; j < nums.size(); j++){ + if(nums[i] == nums[j]){ + ans++; + } + } + } + return ans; + } +}; diff --git a/152._Maximum_Product_Subarray.java b/152._Maximum_Product_Subarray.java new file mode 100644 index 0000000..36d4309 --- /dev/null +++ b/152._Maximum_Product_Subarray.java @@ -0,0 +1,27 @@ +// Problem link +// https://leetcode.com/problems/maximum-product-subarray/ + + + +// Basically to undertand this solution, one should have idea on Kadanes Algorithm which is a DP approach to solve Maximum Subarray Sum. +// This question just replaced sum with product and we know that we got headache with the negative values if you have understood the question properly. +// So I swapped min and max values at current iteration of negative value. + + +class Solution { + public int maxProduct(int[] nums) { + int max=nums[0], min=nums[0],prod=max; + for(int i=1;i>>> &dp, string &s) + { + if(k < 0) return 100000000; + if(currIdx >= s.size()) return 0; + + if(curFreq >= 10) curFreq = 10; + if(dp[currIdx][prevchar][curFreq][k] != -1) return dp[currIdx][prevchar][curFreq][k]; + +// // exclude + int res = 100000000; + res = min(res, helper(currIdx + 1, prevchar, curFreq, k - 1, dp, s)); + +// // include + if(s[currIdx] - 'a' != prevchar) + { + res = min(res, 1 + helper(currIdx + 1, s[currIdx] - 'a', 1, k, dp, s)); + } + else + { + if(curFreq == 1 || curFreq == 9) + { + res = min(res, 1 + helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s)); + } + else res = min(res, helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s)); + } + + return dp[currIdx][prevchar][curFreq][k] = res; + } + +int getLengthOfOptimalCompression(string s, int k) +{ + int n = s.size(); + cout<>>> dp + (n+1,vector>>(28,vector>(11,vector(n+1,-1)))); + return helper(0, 27, 0, k, dp, s); +} + +}; diff --git a/1539. Kth Missing Positive Number.cpp b/1539. Kth Missing Positive Number.cpp new file mode 100644 index 0000000..22c4e4b --- /dev/null +++ b/1539. Kth Missing Positive Number.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int findKthPositive(vector& a, int k) { + int i,n=a.size(),ans; + unordered_map A; + for(i=0;i(); + for (int cut : cuts) + c.add(cut); + c.addAll(Arrays.asList(0, n)); + Collections.sort(c); + int[][] dp = new int[c.size()][c.size()]; + for (int i = c.size() - 1; i >= 0; --i) + for (int j = i + 1; j < c.size(); ++j) { + for (int k = i + 1; k < j; ++k) + dp[i][j] = Math.min(dp[i][j] == 0 ? Integer.MAX_VALUE : dp[i][j], + c.get(j) - c.get(i) + dp[i][k] + dp[k][j]); + } + return dp[0][c.size() - 1]; +} diff --git a/16. 3Sum Closest b/16. 3Sum Closest new file mode 100644 index 0000000..5cae7a0 --- /dev/null +++ b/16. 3Sum Closest @@ -0,0 +1,58 @@ +//Brutefoce O(N^3) Solution (Time Limit Exceeded): + +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + int minDiff = INT_MAX; + int sum, n = nums.size(); + for(int i = 0; i < n; i++) + { + for(int j = i + 1; j < n; j++) + { + for(int k = j + 1; k < n; k++) + { + int currSum = nums[i] + nums[j] + nums[k]; + int newDiff = abs(target - currSum); + if(newDiff < minDiff) minDiff = newDiff, sum = currSum; + } + } + } + + + return sum; + } +}; +//Optimized O(N^2) Solution (Accepted): + +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + int minDiff = INT_MAX; + int sum, n = nums.size(); + sort(nums.begin(), nums.end()); + + + for(int i = 0; i < n - 2; i++) + { + int s = i + 1, e = n - 1; + while(s < e) + { + + int currSum = nums[i] + nums[s] + nums[e]; + + int diff = currSum - target; + if(currSum > target)e--; + else if(currSum < target)s++; + else return target; + if(abs(currSum - target) < minDiff) + { + minDiff = abs(currSum - target); + sum = currSum; + } + } + } + + + return sum; + } +}; diff --git a/1636_Sort_Array_By_Increasing_Frequency.cpp b/1636_Sort_Array_By_Increasing_Frequency.cpp new file mode 100644 index 0000000..b7caf11 --- /dev/null +++ b/1636_Sort_Array_By_Increasing_Frequency.cpp @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/sort-array-by-increasing-frequency/ + +class Solution { +public: + bool static compare(pair a,pair b){ + if(a.second == b.second){ + return a>b; + } + else{ + return a.second frequencySort(vector& nums) { + map mp; + for(int i{0}; i> vec; + for(auto val : mp){ + vec.push_back(val); + } + sort(vec.begin(),vec.end(),compare); + vector answer; + for(int i{0}; i0){ + answer.push_back(vec.at(i).first); + vec.at(i).second--; + } + } + return answer; + } + +}; diff --git a/1662. Check If Two String Arrays are Equivalent b/1662. Check If Two String Arrays are Equivalent new file mode 100644 index 0000000..e027752 --- /dev/null +++ b/1662. Check If Two String Arrays are Equivalent @@ -0,0 +1,12 @@ +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + string sol1=""; + string sol2=""; + for(auto i:word1) + sol1+=i; + for(auto i:word2) + sol2+=i; + return sol1==sol2; + } +}; diff --git a/1752_Check_If_Array_Is_Sorted_And_Rotated.cpp b/1752_Check_If_Array_Is_Sorted_And_Rotated.cpp new file mode 100644 index 0000000..023c9b8 --- /dev/null +++ b/1752_Check_If_Array_Is_Sorted_And_Rotated.cpp @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ + +class Solution { +public: + bool check(vector& nums) { + int count{0}; + for(int i{0}; i nums.at(i+1)){ + count++; + } + } + if(nums.at(nums.size()-1) > nums.at(0)){ + count++; + } + if(count <= 1){ + return true; + } + else{ + return false; + } + } +}; diff --git a/19-remove-nth-node-from-end-of-list.cpp b/19-remove-nth-node-from-end-of-list.cpp new file mode 100644 index 0000000..cdc0cd9 --- /dev/null +++ b/19-remove-nth-node-from-end-of-list.cpp @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ + +// *********************************************************************************** +// Problem link : https://leetcode.com/problems/remove-nth-node-from-end-of-list/ + +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode *dummy = new ListNode(0); + dummy->next = head; + ListNode *slow = dummy, *fast = dummy; + while(n && fast->next) + { + fast = fast->next; + n--; + } + while(fast->next) + { + slow = slow->next; + fast = fast->next; + } + ListNode *temp = slow->next; + slow->next = slow->next->next; + delete temp; + return dummy->next; + } +}; \ No newline at end of file diff --git a/1_bfs.cpp b/1_bfs.cpp new file mode 100644 index 0000000..2863aac --- /dev/null +++ b/1_bfs.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + + +void bfs(int g[][7],int i,int n) +{ + queueq; + int arr[7]={0}; + // start ka index 1 + arr[i]=1; + cout<>&grid,int i,int j,int m,int n){ + + if(i<0||j<0||i>=m||j>=n||grid[i][j]!='1'){ + return; + } + grid[i][j] = '2'; + checkIslands(grid,i-1,j,m,n); + checkIslands(grid,i,j-1,m,n); + checkIslands(grid,i+1,j,m,n); + checkIslands(grid,i,j+1,m,n); + + + } + + + + int countIslands(vector> &grid){ + + int m = grid.size(); + int n = grid[0].size(); + int count = 0; + for(int i = 0 ; i < m ;i++){ + for(int j = 0 ;j < n ;j++){ + if(grid[i][j]=='1'){ + count++; + checkIslands(grid,i,j,m,n); + } + } + } + + return count; + + + } + + + int numIslands(vector>& grid) { + return countIslands(grid); + } +}; \ No newline at end of file diff --git a/2095-Delete-the-Middle-Node-of-a-Linked-List.cpp b/2095-Delete-the-Middle-Node-of-a-Linked-List.cpp new file mode 100644 index 0000000..d189186 --- /dev/null +++ b/2095-Delete-the-Middle-Node-of-a-Linked-List.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + ListNode* deleteMiddle(ListNode* head) { + ListNode *slow=head; + ListNode *fast=head; + ListNode *prev=NULL; + if(head->next==NULL) return NULL; + while(fast!=NULL and fast->next!=NULL){ + prev=slow; + slow=slow->next; + fast=fast->next->next; + } + prev->next=slow->next; + return head; + } +}; diff --git a/2095_Delete_the_Middle_Node_of_a_Linked_List.java b/2095_Delete_the_Middle_Node_of_a_Linked_List.java new file mode 100644 index 0000000..bb15df5 --- /dev/null +++ b/2095_Delete_the_Middle_Node_of_a_Linked_List.java @@ -0,0 +1,17 @@ +class Solution { + public ListNode deleteMiddle(ListNode head) { + if(head.next == null){ + return head.next; + } + ListNode slow = head; + ListNode fast = head; + ListNode prev = null; + while(fast != null && fast.next != null){ + prev = slow; + slow = slow.next; + fast = fast.next.next; + } + prev.next = prev.next.next; + return head; + } +} diff --git a/20_Valid_Parentheses.cpp b/20_Valid_Parentheses.cpp new file mode 100644 index 0000000..f3b5ef7 --- /dev/null +++ b/20_Valid_Parentheses.cpp @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/valid-parentheses/ + +class Solution { +public: + bool isValid(string s) { + stack Stack; + for(int i{0}; ival < b->val) { + temp->next = a; + a = a->next; + temp = temp->next; + } + else { + temp->next = b; + b = b->next; + temp = temp->next; + } + } + if(a) temp->next = a; + if(b) temp->next = b; + return dummy->next; + } +}; \ No newline at end of file diff --git a/234. Palindrome Linked List.cpp b/234. Palindrome Linked List.cpp new file mode 100644 index 0000000..7cfa4da --- /dev/null +++ b/234. Palindrome Linked List.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + ListNode *reverse(ListNode *head){ + ListNode *curr=head, *next=NULL, *prev=NULL; + while(curr){ + next=curr->next; + curr->next=prev; + prev=curr; + curr=next; + } + return head=prev; + } + bool isPalindrome(ListNode* head) { + ListNode *curr=head, *slow=head, *fast=head; + while(fast->next && fast->next->next) { + slow=slow->next; + fast=fast->next->next; + } + slow->next=reverse(slow->next); + slow=slow->next; + while(slow){ + if(slow->val != curr->val) return 0; + slow=slow->next; + curr=curr->next; + } + return 1; + } +}; \ No newline at end of file diff --git a/235. Lowest Common Ancestor of a Binary Search Tree.cpp b/235. Lowest Common Ancestor of a Binary Search Tree.cpp new file mode 100644 index 0000000..d0d09c1 --- /dev/null +++ b/235. Lowest Common Ancestor of a Binary Search Tree.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if(root==NULL) + return root; + if(root==p || root==q) + return root; + TreeNode* lca1=lowestCommonAncestor(root->left,p,q); + TreeNode* lca2=lowestCommonAncestor(root->right,p,q); + if(lca1 && lca2) + return root; + if(lca1) + return lca1; + if(lca2) + return lca2; + return NULL; + } +}; diff --git a/2365-Task-scheduler-ii.cpp b/2365-Task-scheduler-ii.cpp new file mode 100644 index 0000000..ab8f05a --- /dev/null +++ b/2365-Task-scheduler-ii.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + long long taskSchedulerII(vector& tasks, int space) { + unordered_mapmapp; + long long res=tasks.size(); + + vectorarr(tasks.size()); + long long c=0; + + for(int i=0;inext; + current->next = prev; + prev = current; + current = next; + + i++; + } + if(next!=NULL){ + head->next = swapPairs(next); + } + return prev; + } +}; \ No newline at end of file diff --git a/2421. Number of Good Paths b/2421. Number of Good Paths new file mode 100644 index 0000000..017879b --- /dev/null +++ b/2421. Number of Good Paths @@ -0,0 +1,66 @@ +class Solution { +public: + vector parent, rank; + int find(int p) { + if (parent[p] == -1) return p; + return parent[p] = find(parent[p]); + } + bool UNION(int p, int q) { + int i = find(p); + int j = find(q); + if (i==j) return false; + if (rank[i] < rank[j]){ + parent[i] = j; + rank[j]+=rank[i]; + } + else { + parent[j] = i; + rank[i]+=rank[j]; + } + return true; + } + int numberOfGoodPaths(vector& vals, vector>& edges) { + int n=vals.size(),goodPaths=0; + parent.resize(n,-1); + rank.resize(n,1); + + vector> adj(n); + map> sameValues;//Map is req bcz we have to start with smaller values else grp will contain larger values as well + + for (int i = 0; i < n; i++) { + sameValues[vals[i]].push_back(i); + } + + for (auto &e : edges) { + int u = e[0], v = e[1]; + + if (vals[u] >= vals[v]) { + adj[u].push_back(v); + } else if (vals[v] >= vals[u]) { + adj[v].push_back(u); + } + } + + for(auto &[value, allNodes] : sameValues){ + for(auto it:allNodes){ + for(auto itr:adj[it]) + UNION(it,itr); + } + + unordered_map group; + + for (int u : allNodes) { + group[find(u)]++; + } + + goodPaths += allNodes.size(); + + for(auto it:group){ + goodPaths+=(it.second*(it.second-1))/2; + } + + } + + return goodPaths; + } +}; diff --git a/2427. N509. Fibonacci Numberumber of Common Factors.cpp b/2427. N509. Fibonacci Numberumber of Common Factors.cpp new file mode 100644 index 0000000..c40461c --- /dev/null +++ b/2427. N509. Fibonacci Numberumber of Common Factors.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int fib(int n) { + if(n == 1) + return 1; + + int first = 0; + int second = 1; + int ans = 0; + for(int i = 1; i < n; i++){ + ans = first + second; + first = second; + second = ans; + } + return ans; + } +}; diff --git a/2427. Number of Common Factors.cpp b/2427. Number of Common Factors.cpp new file mode 100644 index 0000000..e346a2c --- /dev/null +++ b/2427. Number of Common Factors.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int commonFactors(int a, int b) { + int mini = min(a,b); + int ans = 0; + for(int i = 1; i <= mini; i++){ + if(a % i ==0 && b % i == 0) + ans++; + } + return ans; + } +}; diff --git a/2428. Maximum Sum of an Hourglass.cpp b/2428. Maximum Sum of an Hourglass.cpp new file mode 100644 index 0000000..0d2cf04 --- /dev/null +++ b/2428. Maximum Sum of an Hourglass.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; +class Solution +{ +public: + int maxSum(vector> &grid) + { + // vector> pos = {{0,0},{0,1},{0,2},{1,1},{2,0},{2,1},{2,2}}; + int sum = 0; + for (int i = 0; i < grid.size(); i++) + { + for (int j = 0; j < grid[0].size(); j++) + { + if (i + 2 < grid.size() && j + 2 < grid[0].size()) + { + int temp = grid[i][j] + grid[i][j + 1] + grid[i][j + 2] + grid[i + 1][j + 1] + grid[i + 2][j] + grid[i + 2][j + 1] + grid[i + 2][j + 2]; + sum = max(sum, temp); + } + } + } + return sum; + } +}; +int main() +{ + Solution b; + vector> grid = {{6, 2, 1, 3}, {4, 2, 1, 5}, {9, 2, 8, 7}, {4, 1, 2, 9}}; + cout << b.maxSum(grid) << endl; + return 0; +} \ No newline at end of file diff --git a/2433.FindTheOriginalArrayofPrefixXor b/2433.FindTheOriginalArrayofPrefixXor new file mode 100644 index 0000000..280c1ac Binary files /dev/null and b/2433.FindTheOriginalArrayofPrefixXor differ diff --git a/2433.FindTheOriginalArrayofPrefixXor.cpp b/2433.FindTheOriginalArrayofPrefixXor.cpp new file mode 100644 index 0000000..b7685c2 --- /dev/null +++ b/2433.FindTheOriginalArrayofPrefixXor.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; +class Solution +{ +public: + vector findArray(vector &A) + { + for (int i = A.size() - 1; i > 0; --i) + A[i] ^= A[i - 1]; + return A; + } +}; + +int main() +{ + Solution b; + vector arr = {5, 2, 0, 3, 1}; + auto ans = b.findArray(arr); + for (int x : ans) + cout << x << endl; + return 0; +} \ No newline at end of file diff --git a/268_Missing_Number.cpp b/268_Missing_Number.cpp new file mode 100644 index 0000000..5520c1a --- /dev/null +++ b/268_Missing_Number.cpp @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/missing-number/ + +class Solution { +public: + int missingNumber(vector& nums) { + sort(nums.begin(),nums.end()); + int ans{}; + for(int i{0}; i& nums) { + for(int i{0}; i& a) { + int lo = 0, hi = a.size() - 1, mid; + sort(a.begin(), a.end()); + while(lo <= hi) { + mid = (lo + hi) >> 1; + if(a[mid] < a.size() - mid) lo = mid + 1; + else hi = mid - 1; + } + return a.size() - lo; + } +}; diff --git a/27_Remove_Element.cpp b/27_Remove_Element.cpp new file mode 100644 index 0000000..520676f --- /dev/null +++ b/27_Remove_Element.cpp @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/remove-element/ + +class Solution { +public: + int removeElement(vector& nums, int val) { + for(int i{0}; i&prices,vector>&dp) + { + if(ind>=prices.size())return 0; + int profit=0; + if(dp[ind][buy]!=-1)return dp[ind][buy]; + if(buy) + { + profit=max(-prices[ind]+find(ind+1,0,prices,dp),find(ind+1,1,prices,dp)); + } + else + profit=max(prices[ind]+find(ind+2,1,prices,dp),find(ind+1,0,prices,dp)); + return dp[ind][buy]=profit; + } + int maxProfit(vector& prices) { + vector>dp(prices.size(),vector(2,-1)); + int a=find(0,1,prices,dp); + return a; + } +}; diff --git a/326. Power of Three.cpp b/326. Power of Three.cpp new file mode 100644 index 0000000..ca1435e --- /dev/null +++ b/326. Power of Three.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + bool isPowerOfThree(int n) { + if(n<=0) return 0; + return ((1162261467%n) == 0); + } +}; + + diff --git a/342. Power of Four.cpp b/342. Power of Four.cpp new file mode 100644 index 0000000..512bcbc --- /dev/null +++ b/342. Power of Four.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + bool isPowerOfFour(int n) { + return ((n > 0) && ((n&(n-1)) == 0) && (n%3 == 1)); + } +}; \ No newline at end of file diff --git a/35-search-insert-position.cpp b/35-search-insert-position.cpp new file mode 100644 index 0000000..427d870 --- /dev/null +++ b/35-search-insert-position.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int searchInsert(vector& nums, int target) { + int indx; + if(nums[0]>target){ + indx = 0; + } + else if(nums[nums.size()-1]target){ + indx = i+1; + } + } + } + return indx; + } +}; \ No newline at end of file diff --git a/394. Decode String.cpp b/394. Decode String.cpp new file mode 100644 index 0000000..ecef681 --- /dev/null +++ b/394. Decode String.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + string decodeString(const string& s, int& i) { + string res; + + while (i < s.length() && s[i] != ']') { + if (!isdigit(s[i])) + res += s[i++]; + else { + int n = 0; + while (i < s.length() && isdigit(s[i])) + n = n * 10 + s[i++] - '0'; + + i++; // '[' + string t = decodeString(s, i); + i++; // ']' + + while (n-- > 0) + res += t; + } + } + + return res; + } + + string decodeString(string s) { + int i = 0; + return decodeString(s, i); + } +}; diff --git a/412. Fizz Buzz.cpp b/412. Fizz Buzz.cpp new file mode 100644 index 0000000..e608de4 --- /dev/null +++ b/412. Fizz Buzz.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector fizzBuzz(int n) { + vector ans; + for(int i = 1; i <= n; i++){ + if(i % 3 == 0 && i % 5 == 0) + ans.push_back("FizzBuzz"); + else if(i % 3 == 0) + ans.push_back("Fizz"); + else if(i % 5 == 0) + ans.push_back("Buzz"); + else + ans.push_back(to_string(i)); + } + return ans; + } +}; diff --git a/46. Permutations.cpp b/46. Permutations.cpp new file mode 100644 index 0000000..23736e5 --- /dev/null +++ b/46. Permutations.cpp @@ -0,0 +1,33 @@ +/* +leetcode problem no 46 Permutations + +Input: nums = [1,2,3] +Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] +*/ + +class Solution { +public: + void backtrack(vector>& pers, vector& per, vector& nums){ + if(per.size() == nums.size()){ + pers.push_back(per); + }else{ + for(int e : nums){ + if(find(per.begin(), per.end(), e) != per.end()){ + continue; + } + per.push_back(e); + backtrack(pers, per, nums); + per.pop_back(); + } + } + }; + + vector> permute(vector& nums) { + vector> pers; + vector per; + + backtrack(pers, per, nums); + + return pers; + } +}; diff --git a/48.Rotate_Image.cpp b/48.Rotate_Image.cpp new file mode 100644 index 0000000..67a01b6 --- /dev/null +++ b/48.Rotate_Image.cpp @@ -0,0 +1,25 @@ +// Solution to the Problem : Rotate Image +// https://leetcode.com/problems/rotate-image/ + +class Solution { +public: + void rotate(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + + for(int i = 0 ; i < m ; i++){ + + for(int j = i ; j < n ; j++){ + swap(matrix[i][j],matrix[j][i]); + } + + } + + for(int i = 0 ; i < m ; i++){ + for(int j = 0 ; j < n /2 ;j++){ + swap(matrix[i][j],matrix[i][n-j-1]); + } + } + + } +}; \ No newline at end of file diff --git a/4Sum.cpp b/4Sum.cpp new file mode 100644 index 0000000..6979ff4 --- /dev/null +++ b/4Sum.cpp @@ -0,0 +1,35 @@ +vector> fourSum(vector& nums, int target) { + int n = nums.size(); + sort(nums.begin() , nums.end()); // sort the array to use the two pointers method + vector> ans; + set> store; // to store and remove the duplicate answers + + for(int i = 0 ; i < n; i++){ + + for(int j = i + 1; j < n ; j++){ + + int new_target = target - nums[i] - nums[j]; + + int x = j+1 , y = n-1; + + while(x < y){ + + int sum = nums[x] + nums[y]; + + if(sum > new_target) y--; + else if(sum < new_target ) x++; + else { + store.insert({nums[i] , nums[j] , nums[x] , nums[y]}); + x++; + y--; + }; + } + } + } + + for(auto i : store){ + ans.push_back(i); // store the answers in an array(ans) + } + + return ans; + } diff --git a/4_prims.cpp b/4_prims.cpp new file mode 100644 index 0000000..601cce3 --- /dev/null +++ b/4_prims.cpp @@ -0,0 +1,43 @@ +#include +#define I INT_MAX +#define V 8 +using namespace std; + +void prime_mst(int cost[][V], int n) +{ + int u, v, i, j, k, min = I; + vector near; + for (i = 1; i <= n; i++) + { + for (j = i; j <= n; j++) + { + if (cost[i][j] < min) + { + u = i; + v = j; + } + } + } + + +} + +int main() +{ + + int cost[V][V]{ + {I, I, I, I, I, I, I, I}, + {I, I, 25, I, I, I, 5, I}, + {I, 25, I, 12, I, I, I, 10}, + {I, I, 12, I, 8, I, I, I}, + {I, I, I, 8, I, 16, I, 14}, + {I, I, I, I, 16, I, 20, 18}, + {I, 5, I, I, I, 20, I, I}, + {I, I, 10, I, 14, 18, I, I}, + }; + + int n = sizeof(cost[0]) / sizeof(cost[0][0]) - 1; + + prime_mst(cost, n); + return 0; +} \ No newline at end of file diff --git a/53. Maximum Subarray.java b/53. Maximum Subarray.java new file mode 100644 index 0000000..63279bb --- /dev/null +++ b/53. Maximum Subarray.java @@ -0,0 +1,16 @@ + public int maxSubArray(int[] nums) { + int maxsofar=nums[0]; + int sum=0; + for(int i=0;imaxsofar) + { + maxsofar=sum; + } + if(sum<0) + { + sum=0; + } + } + return maxsofar; + } diff --git a/62. Unique Paths.cpp b/62. Unique Paths.cpp new file mode 100644 index 0000000..a304a2f --- /dev/null +++ b/62. Unique Paths.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int uniquePaths(int m, int n) { + if(m& a) { + unordered_map mp; + for(auto x: a) mp[x]++; + for(auto x: a) { + if(mp[x] == 0) continue; + int freq = mp[x], count = 0, currElement = x; + while(mp.count(currElement) && mp[currElement] >= freq) { + freq = max( freq, mp[currElement]); + mp[currElement]--; + currElement++; + count++; + } + if(count < 3) return 0; + } + return 1; + } +}; \ No newline at end of file diff --git a/66_Plus_One.cpp b/66_Plus_One.cpp new file mode 100644 index 0000000..e9d0cbc --- /dev/null +++ b/66_Plus_One.cpp @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/plus-one/ + +class Solution { +public: + vector plusOne(vector& digits) { + int end{}; + end = digits.size()-1; + int carry_back{1}; + for(int i{end}; i>=0; --i){ + digits.at(i) += carry_back; + carry_back = 0; + if(digits.at(i) == 10){ + digits.at(i) = 0; + carry_back = 1; + } + } + if(carry_back == 1){ + digits.insert(digits.begin(),1); + } + return digits; + } +}; diff --git a/674. Longest Continuous Increasing Subsequence.cpp b/674. Longest Continuous Increasing Subsequence.cpp new file mode 100644 index 0000000..27e3d93 --- /dev/null +++ b/674. Longest Continuous Increasing Subsequence.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int findLengthOfLCIS(vector& nums) { + int prev=INT_MIN, cnt=0, ans=0; + for(auto x: nums) { + if(x > prev) { + cnt++; + ans = max(ans, cnt); + prev=x; + } + else { + cnt=1; + ans=max(ans, cnt); + prev=x; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/692. Top K Frequent Words.cpp b/692. Top K Frequent Words.cpp new file mode 100644 index 0000000..02769c4 --- /dev/null +++ b/692. Top K Frequent Words.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector topKFrequent(vector& words, int k) { + unordered_map freq; + for(auto w : words){ + freq[w]++; + } + + auto comp = [&](const pair& a, const pair& b) { + return a.second > b.second || (a.second == b.second && a.first < b.first); + }; + typedef priority_queue< pair, vector>, decltype(comp) > my_priority_queue_t; + my_priority_queue_t pq(comp); + + for(auto w : freq ){ + pq.emplace(w.first, w.second); + if(pq.size()>k) pq.pop(); + } + + vector output; + while(!pq.empty()){ + output.insert(output.begin(), pq.top().first); + pq.pop(); + } + return output; + + } +}; diff --git a/69_Sqrt(x).cpp b/69_Sqrt(x).cpp new file mode 100644 index 0000000..b9db0c4 --- /dev/null +++ b/69_Sqrt(x).cpp @@ -0,0 +1,8 @@ +// https://leetcode.com/problems/sqrtx/ + +class Solution { +public: + int mySqrt(int x) { + return sqrt(x); + } +}; diff --git a/704_Binary_Search.cpp b/704_Binary_Search.cpp new file mode 100644 index 0000000..6b6bc7f --- /dev/null +++ b/704_Binary_Search.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +using namespace std; + +class Solution +{ +public: + int search(vector &nums, int target) + { + int low = 0; // Least element + int high = nums.size() - 1; // Highest element + + // Loop while low and high intersect + while (low <= high) + { + int mid = low + (high - low) / 2; + // Mid value to check target is left side of mid or right side of mid + + if (nums[mid] < target) + { + // If target > nums[mid] value + // ==> target is on right side so we should search in the range (mid+1 to high) so change low to mid + 1; + low = mid + 1; + } + else if (nums[mid] > target) + { + // If target < nums[mid] value + // ==> target is on left side so we should search in the range (low to mid-1) so change high to mid - 1; + high = mid - 1; + } + else + { + // Found the target !!! + return mid; + } + } + // Target is not present in array + return -1; + } +}; \ No newline at end of file diff --git a/713_Subarray_Product_Less_Than_K.cpp b/713_Subarray_Product_Less_Than_K.cpp new file mode 100644 index 0000000..0bc2546 --- /dev/null +++ b/713_Subarray_Product_Less_Than_K.cpp @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/subarray-product-less-than-k/ + +class Solution { +public: + int numSubarrayProductLessThanK(vector& nums, int k) { + if(k <= 1){ + return 0; + } + int left{0},right{0},product{1},ans{0}; + while(right= k){ + product /= nums.at(left); + left++; + } + ans += (right-left+1); + right++; + } + return ans; + } +}; diff --git a/72._Edit_Distance.cpp b/72._Edit_Distance.cpp new file mode 100644 index 0000000..0cb7e97 --- /dev/null +++ b/72._Edit_Distance.cpp @@ -0,0 +1,99 @@ +// Problem Link +// https://leetcode.com/problems/edit-distance/ + +// Recursion based approach +class Solution { +public: + + int editDis(string& word1, string& word2, int n1, int n2) + { + if(n1 == 0) + return n2; + if(n2 == 0) + return n1; + if(word1[n1-1] == word2[n2-1]) { + return editDis(word1, word2, n1-1, n2-1); + } + + return 1+min(editDis(word1, word2, n1, n2-1), + min(editDis(word1, word2, n1-1, n2), + editDis(word1, word2, n1-1, n2-1))); + } + + int minDistance(string word1, string word2) { + int n1 = word1.size(); + int n2 = word2.size(); + return editDis(word1, word2, n1, n2); + + } +}; + +// DP tabulation based approach +class Solution { +public: + int minDistance(string word1, string word2) { + int n=word1.length(); + int m=word2.length(); + vector> dp(n+1,vector(m+1,0)); + + for(int i=0;i<=m;++i) + dp[0][i]=i; + for(int i=0;i<=n;++i) + dp[i][0]=i; + + for(int i=1;i<=n;++i){ + for(int j=1;j<=m;++j){ + if(word1[i-1]==word2[j-1]) + dp[i][j]=dp[i-1][j-1]; + else + dp[i][j]=1+min({dp[i-1][j],dp[i-1][j-1],dp[i][j-1]}); + } + } + + return dp[n][m]; + } +}; + +// DP memoization based approach +class Solution { +public: + int dp[1001][1001]; + + int editDis(string& word1, string& word2, int n1, int n2) + { + if(n1 == 0) + return n2; + if(n2 == 0) + return n1; + + if(dp[n1][n2] !=-1) + { + return dp[n1][n2]; + } + + if(word1[n1-1] == word2[n2-1]) { + dp[n1][n2] = editDis(word1, word2, n1-1, n2-1); + return dp[n1][n2]; + } + + dp[n1][n2]= 1+min(editDis(word1, word2, n1, n2-1), + min(editDis(word1, word2, n1-1, n2), + editDis(word1, word2, n1-1, n2-1))); + return dp[n1][n2]; + } + + int minDistance(string word1, string word2) { + int n1 = word1.size(); + int n2 = word2.size(); + for(int i=0;i<=n1+1;i++) + { + for(int j=0;j<=n2+1;j++) + { + dp[i][j] = -1; + } + } + + dp[n1][n2] = editDis(word1, word2, n1, n2); + return dp[n1][n2]; + } +}; \ No newline at end of file diff --git a/72._Edit_Distance.java b/72._Edit_Distance.java new file mode 100644 index 0000000..29ec95b --- /dev/null +++ b/72._Edit_Distance.java @@ -0,0 +1,37 @@ +// Problem Link +// https://leetcode.com/problems/edit-distance/ + + +public class Solution { + int[][] dp; + + public int minDistance(String word1, String word2) { + dp = new int[word1.length()][word2.length()]; + + return minDistanceHelper(word1, word2, 0, 0); + } + + private int minDistanceHelper(String word1, String word2, int index1, int index2) { + if (index1 == word1.length()) return word2.length() - index2; + if (index2 == word2.length()) return word1.length() - index1; + + if (dp[index1][index2] > 0) return dp[index1][index2]; + + int result; + if (word1.charAt(index1) == word2.charAt(index2)) { + result = minDistanceHelper(word1, word2, index1+1, index2+1); + } else { + // replace char + result = 1 + minDistanceHelper(word1, word2, index1+1, index2+1); + + // delete char from word1 + result = Math.min(result, 1 + minDistanceHelper(word1, word2, index1+1, index2)); + + // delete char from word2 + result = Math.min(result, 1 + minDistanceHelper(word1, word2, index1, index2+1)); + } + + dp[index1][index2] = result; + return result; + } +} diff --git a/74. Search a 2D Matrix.java b/74. Search a 2D Matrix.java new file mode 100644 index 0000000..8862744 --- /dev/null +++ b/74. Search a 2D Matrix.java @@ -0,0 +1,13 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + for (int r=0; r>& board) { + string expected="123450"; + string cur=""; + vector> swaps={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}}; + int z; + + for(int i=0;i<2;i++) + for(int j=0;j<3;j++){ + cur+=board[i][j]+'0'; + if(board[i][j]==0) + z=(i*3)+j; + } + + queue> q; + unordered_map visited; + visited[cur]=true; + q.push({cur,z}); + int level=0; + + while(!q.empty()) + { + int n=q.size(); + for(int i=0;i>& grid) { + + int n=grid.size(),ans=0; + priority_queue,vector>,greater>> q; + unordered_map visited; + vector d={1,0,-1,0,1}; + + q.push({grid[0][0],0,0}); + visited[0]=true; + + while(!q.empty()) + { + auto p=q.top(); + q.pop(); + // ans=max(ans,p[0]); + for(int i=0;i<4;i++) + { + int X=p[1]+d[i]; + int Y=p[2]+d[i+1]; + if(X>=0&&Y>=0&&X& words) { + vector A = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; + unordered_set st; + for(auto x : words) { + string str = ""; + for(auto ch : x) str += A[ch - 'a']; + st.insert(str); + } + return st.size(); + } +}; \ No newline at end of file diff --git a/869.Reordered_Power_of_2.cpp b/869.Reordered_Power_of_2.cpp new file mode 100644 index 0000000..3248db7 --- /dev/null +++ b/869.Reordered_Power_of_2.cpp @@ -0,0 +1,27 @@ +// Solution to : Reordered Power Of 2 +// https://leetcode.com/problems/reordered-power-of-2/ + +// This Solution has very minimal runtime + +class Solution { +public: + bool reorderedPowerOf2(int n) { + string s = to_string(n); + sort(s.begin(),s.end()); + + vector power; + for(int i=0;i<=30;i++){ + int p = pow(2,i); + power.push_back(to_string(p)); + } + + for(int i=0;i<=30;i++){ + sort(power[i].begin(),power[i].end()); + } + + for(int i=0;i<=30;i++){ + if(power[i] == s ) return true; + } + return false; + } +}; \ No newline at end of file diff --git a/871. Minimum Number of Refueling Stops.cpp b/871. Minimum Number of Refueling Stops.cpp new file mode 100644 index 0000000..f4e6d94 --- /dev/null +++ b/871. Minimum Number of Refueling Stops.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + int i=0, ans=0; + priority_queue pq; + while(startFuel < target) { + while(i < stations.size() && stations[i][0] <= startFuel) { + pq.push(stations[i][1]); + i++; + } + if(pq.size()==0) return -1; + startFuel += pq.top(); pq.pop(); + ans++; + } + return ans; + } +}; \ No newline at end of file diff --git a/88-Merge-Sorted-Array.cpp b/88-Merge-Sorted-Array.cpp new file mode 100644 index 0000000..050fa86 --- /dev/null +++ b/88-Merge-Sorted-Array.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + nums1.resize(m); + for(int i =0;i& a, int m, vector& b, int n) { + int ind = m + n - 1, i = m - 1, j = n - 1; + while(i >= 0 && j >= 0) { + if(a[i] >= b[j]) a[ind--] = a[i--]; + else a[ind--] = b[j--]; + } + while(i >= 0) a[ind--] = a[i--]; + while(j >= 0) a[ind--] = b[j--]; + } +}; \ No newline at end of file diff --git a/887.Super_Egg_Drop.java b/887.Super_Egg_Drop.java new file mode 100644 index 0000000..04a1458 --- /dev/null +++ b/887.Super_Egg_Drop.java @@ -0,0 +1,43 @@ +// Problem Link +// https://leetcode.com/problems/super-egg-drop/ + +class Solution { + Integer dp[][]=new Integer[101][10001]; + //Declared wrapper class because no need to initialise values, will be null defaultly + + public int superEggDrop(int K, int N) { + + if(K==1)//when there is only one egg + return N; + + if(N==0 || N==1)//when no. of floors are 0 or 1 + return N; + + if(dp[K][N]!=null)//checking if it is filled + return dp[K][N]; + + int i,l=1,h=N; + int ans=Integer.MAX_VALUE; + + while(l<=h) + { + int mid=(l+h)/2; + + int down_temp=superEggDrop(K-1,mid-1);//If egg breaks go down + + int up_temp=superEggDrop(K,N-mid);//if egg doesn't break go up + + int temp=1+Math.max(down_temp,up_temp); + //adding one because we have used 1 attempt and max of up and down because + //we need worst case attempts from both + + if(down_temp movesToStamp(string stamp, string target) { + vector res; + int n = stamp.size(), total = 0; + while (true) { + bool isStamped = false; + for (int size = n; size > 0; --size) { + for (int i = 0; i <= n - size; ++i) { + string t = string(i, '*') + stamp.substr(i, size) + string(n - size - i, '*'); + auto pos = target.find(t); + while (pos != string::npos) { + res.push_back(pos); + isStamped = true; + total += size; + fill(begin(target) + pos, begin(target) + pos + n, '*'); + pos = target.find(t); + } + } + } + if (!isStamped) break; + } + reverse(res.begin(), res.end()); + return total == target.size() ? res : vector(); + } +}; \ No newline at end of file diff --git a/98. Validate Binary Search Tree.cpp b/98. Validate Binary Search Tree.cpp new file mode 100644 index 0000000..fe3f386 --- /dev/null +++ b/98. Validate Binary Search Tree.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + static bool valid(TreeNode* root,long long Left,long long Right){ + if(root==NULL){ + return true; + } + if(root->val<=Left || root->val>=Right){ + return false; + } + return valid(root->left,Left,root->val) && valid(root->right,root->val,Right); + + + + } + bool isValidBST(TreeNode* root) { + if(root->left==NULL && root->right==NULL){ + return true; + } + return valid(root,-3147483648,3147483647); + + + } +}; diff --git a/99. Recover Binary Search Tree.cpp b/99. Recover Binary Search Tree.cpp new file mode 100644 index 0000000..dec211d --- /dev/null +++ b/99. Recover Binary Search Tree.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + vector> v; + void ans(TreeNode* root){ + if(root==NULL){ + return; + } + ans(root->left); + v.push_back({root->val,root}); + ans(root->right); + + } + void recoverTree(TreeNode* root) { + ans(root); + vector b; + for(int i=0;ival; + change1->val=change2->val; + change2->val=a; + return ; + } +}; diff --git a/994. Rotting Oranges.cpp b/994. Rotting Oranges.cpp new file mode 100644 index 0000000..9da6fd9 --- /dev/null +++ b/994. Rotting Oranges.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + bool ispos(int a,int b,int m,int n,vector>& grid){ + if(a<0||a>=m||b<0||b>=n){ + return false; + } + if(grid[a][b]==1){ + return true; + } + return false; + } + int orangesRotting(vector>& grid) { + queue> q; + for(int i=0;i +using namespace std; +int main() +{ + char c = 'A'; + cout << "The ASCII value of " << c << " is " << int(c); + return 0; +} diff --git a/ActivitySelection.cpp b/ActivitySelection.cpp new file mode 100644 index 0000000..414a498 --- /dev/null +++ b/ActivitySelection.cpp @@ -0,0 +1,34 @@ +#include +#include +using namespace std; +struct Activitiy +{ + int start, end; +}; +bool comp(Activitiy act1, Activitiy act2) +{ + return (act1.end < act2.end); +} +void maxActivity(Activitiy act[], int n) +{ + sort(act, act + n, comp); // sort activities using compare function + + cout << "Selected Activities are: " << endl; + int i = 0; // first activity as 0 is selected + cout << "Activity: " << i << " , Start: " << act[i].start << " End: " << act[i].end << endl; + for (int j = 1; j < n; j++) + { // for all other activities + if (act[j].start >= act[i].end) + { // when start time is >= endtime, print the activity + cout << "Activity: " << j << " , Start: " << act[j].start << " End: " << act[j].end << endl; + i = j; + } + } +} +int main() +{ + Activitiy actArr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}}; + int n = 6; + maxActivity(actArr, n); + return 0; +} \ No newline at end of file diff --git a/Add two nos.cpp b/Add two nos.cpp new file mode 100644 index 0000000..753d8d3 --- /dev/null +++ b/Add two nos.cpp @@ -0,0 +1,53 @@ +https://leetcode.com/problems/add-two-numbers/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode *p=l1; + ListNode *q=l2; + ListNode *newna=new ListNode(); + ListNode *temp=newna; + int c=0; + while(l1!=NULL||l2!=NULL||c!=0){ + int sum=0,dig=0; + if(l1!=NULL){ + sum+=l1->val; + l1=l1->next;} + + if(l2!=NULL){ + sum+=l2->val; + l2=l2->next; + } + if(c!=0) sum+=c; + c=sum/10; + dig=sum%10; + ListNode *newn=new ListNode(dig); + temp->next=newn; + temp=temp->next; + + + } +// if(l1!=NULL){ +// p=l1; + +// } +// if(l2!=NULL){ +// if(c!=0){ +// l2->val=l2->val+1; + +// } +// temp->next=l2; +// } + return newna->next; + } +}; diff --git a/AllAnagram.cpp b/AllAnagram.cpp deleted file mode 100644 index b47b809..0000000 --- a/AllAnagram.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector findAnagrams(string s, string p) { - int len_s = s.size(); - int len_p = p.size(); - - if(len_s < len_p) return {}; - - vector p_freq(26, 0); - vector window(26, 0); - - for(int i = 0; i < len_p; i++) { - p_freq[p[i]- 'a']++; - window[s[i]- 'a']++; - } - - vector ans; - - if(p_freq == window) ans.push_back(0); - - for(int i = len_p; i < len_s; i++) { - window[s[i-len_p] - 'a']--; // Ascii of s[i-len_p] - ascii of 'a' --index - window[s[i] - 'a']++; - if(p_freq == window) ans.push_back(i-len_p+1); - } - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& time) { + int days = 1; + + long long daysSum = 0; + + for(int i = 0; i < m; i++) { + if(daysSum + time[i] <= t) { + daysSum += time[i]; + } + else { + days += 1; + daysSum = time[i]; + } + } - stackst1, st2; - long long mini; + return days <= n; +} -public: - MinStack() { - - } - - void push(int val) { - if(st2.empty() or val <= st2.top()) st2.push(val); - st1.push(val); - } + +long long ayushGivesNinjatest(int n, int m, vector time) { + // Write your code here. - void pop() { - - if(st1.top() == st2.top()) { - st2.pop(); - } + int minTime = 0; + long long maxTime = 0; - st1.pop(); + for(int i = 0; i < m; i++) { + maxTime += time[i]; + minTime = max(minTime, time[i]); + } - } - - int top() { - - return st1.top(); - } - - int getMin() { - return st2.top(); - } -}; - -/** - * Your MinStack object will be instantiated and called as such: - * MinStack* obj = new MinStack(); - * obj->push(val); - * obj->pop(); - * int param_3 = obj->top(); - * int param_4 = obj->getMin(); - */ + long long l = minTime, r = maxTime, ans; + while(l <= r) { + + long long mid = (l+r)/2; + + if(isPossible(mid, n, m, time)) { + ans = mid; + r = mid - 1; + } + else { + l = mid + 1; + } + } + return ans; + +} diff --git a/Armstrong number.cpp b/Armstrong number.cpp new file mode 100644 index 0000000..fe1d8c3 --- /dev/null +++ b/Armstrong number.cpp @@ -0,0 +1,43 @@ +#include + +using namespace std; + +int main() { + + int num, originalNum, remainder, result = 0; + + cout << "Enter a three-digit integer: "; + + cin >> num; + + originalNum = num; + + while (originalNum != 0) { + + + + remainder = originalNum % 10; + + + + result += remainder * remainder * remainder; + + + + + + originalNum /= 10; + + } + + if (result == num) + + cout << num << " is an Armstrong number."; + + else + + cout << num << " is not an Armstrong number."; + + return 0; + +} \ No newline at end of file diff --git a/Autobot Youtube clipper.py b/Autobot Youtube clipper.py new file mode 100644 index 0000000..aad07dc --- /dev/null +++ b/Autobot Youtube clipper.py @@ -0,0 +1,174 @@ +# Input Twitch vod URL +# Input timestamps of the clip +# Retrieve the clip from the twitch live stream +# Show the clip for preview +# Open Video trimmer for editting the clip +# Input Title, Description, Tags +# Input credits +# Upload to YT +# Show YT link + + +import os +import os.path +import re +import sys +from datetime import datetime +import pytz +import videotrim_util +import ytupload_util +import webbrowser +import time + + +default_description = "" +default_categoryId = "20" + +try: + f=open("constdesc.txt") + default_description=f.read() + f.close() +except Exception as e: + default_description="" + + + +def credits(): + print("[~] Written by Archit Shukla") + print("[~] Thanks to streamlink CLI (https://streamlink.github.io)") + print() + + +def checks(): + # check if client_secret.json and credentials.txt files are present + if not os.path.isfile("client_secrets.json"): + print("[!] Client Secret file is missing. Make sure you download it from your GCP dashboard and place it in the current directory") + sys.exit(0) + + if not os.path.isfile("credentials.txt"): + # Trigger flask server to enable use to authenticate with their account + print("[!] credentials.txt is missing!") + print("[!] You need to initially authenticate with your Google Account so that the video can be uploaded to your channel. Don't worry, you only need to do this once.") + print("[-] Run config.py to authenticate with your google account and create credentials.txt") + +def validateInput(inp, pattern): + if re.search(pattern, inp): + return True + return False + + +def getOffsetAndDuration(start_time, end_time): + start_do = datetime.strptime(start_time, "%H:%M:%S") + end_do = datetime.strptime(end_time, "%H:%M:%S") + offset = start_time + duration = str(end_do-start_do).split(".")[0] + return [offset,duration] + + +def getTwitchClip(creator_name, twitch_url, offset, duration): + print("[*] Getting clip from Twitch Live Stream with streamlink..") + # Use Streamlink to get the clip + filename = os.path.join("clips",creator_name+(datetime.now(pytz.timezone('Asia/Kolkata'))).strftime("%m%d%Y-%H_%M_%S")+".ts") + + cmd = "streamlink %s best --hls-start-offset %s --hls-duration %s -o %s"%(twitch_url,offset,duration,filename) + print("[*] %s"%cmd) + os.system(cmd) + return filename + + +def main(): + credits() + creator_name = input("[+] Twitch Creator name: ").replace(" ","") + twitch_url = input("[+] Twitch VOD URL: ") + if not validateInput(twitch_url,r"^https://www.twitch.tv/videos/.*$"): + print("[!] Bad Input. Make sure you input twitch VOD URL and not the live stream URL.") + sys.exit() + start_time = input("[+] Clip Start time (HH:MM:SS): ") + if not validateInput(start_time,r"^[0-9][0-9]:[0-6][0-9]:[0-6][0-9]$"): + print("[!] Bad Input. Make sure you follow the input format correctly.") + sys.exit() + end_time = input("[+] Clip End time (HH:MM:SS): ") + if not validateInput(end_time,r"^[0-9][0-9]:[0-6][0-9]:[0-6][0-9]$"): + print("[!] Bad Input. Make sure you follow the input format correctly.") + sys.exit() + + + offset, duration = getOffsetAndDuration(start_time, end_time) + + + if not os.path.isdir("clips"): + os.mkdir("clips") + + + filename = getTwitchClip(creator_name, twitch_url, offset, duration) + + # Check if the download is successful + if os.path.isfile(filename): + print("[*] Downloaded clip succesfully! - %s"%filename) + else: + print("[!] Download failed!") + sys.exit(0) + + + print("[*] Opening clip in video player..") + os.startfile(filename) + + op = input("[+] Do you want to trim the video? (Y/n): ") + if(op in ["Y","y",""]): + # Open video trimming util + if (videotrim_util.trimVideo(filename)): + print("[*] Video trimmed successfully!") + filename = filename.split(".ts")[0]+"_trimmed.ts" + else: + print("[!] Video trim failed!") + op = input("Do you want to (E)xit or (C)ontinue?") + if op in ["E","e",""]: + sys.exit() + + elif op in ["N","n"]: + # Do not open video trimming util + pass + + + op = input("[+] Upload to YouTube? (Y/n): ") + + if op in ["Y","y",""]: + # Upload created clip to YT + + yt_title = input("[+] Video Title: ") + yt_description = input("[+] Video Description (leave empty for default description): ") + yt_tags = input("[+] Video Tags (seperated by comas): ") + yt_categoryId = input("[+] Category ID (Leave empty for Gaming): ") + yt_privacyStatus = input("[+] Privacy Status (public/private/unlisted): ") + yt_credits = input("[+] Credits for Original Creator: ") + + if yt_title=="": + print("[!] Title can't be empty") + + if yt_privacyStatus.lower() not in ["public","private","unlisted"]: + print("[!] Invalid privacy status") + + if yt_description=="": + yt_description = default_description + + if yt_categoryId=="": + yt_categoryId = default_categoryId + + + yt_description+="\n"+"Credits: \n"+yt_credits + + print("[*] Uploading video to YouTube. This might take a while..be patient, do not close the script.") + videoId = ytupload_util.upload(filename, yt_title, yt_description, yt_tags, yt_categoryId, yt_privacyStatus) + + if videoId is not None: + print("[*] Succesfully uploaded video. ") + print("[*] https://www.youtube.com/watch?v=%s"%videoId) + + else: + print("[!] Video upload failed.") + + + +if __name__ == "__main__": + checks() + main() diff --git a/BFS.cpp b/BFS.cpp new file mode 100644 index 0000000..44e22d6 --- /dev/null +++ b/BFS.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +void bfs(vector> &graph, int source, vector &vis) +{ + queue q; + q.push(source); + vis[source] = true; + while (!q.empty()) + { + int curr = q.front(); + q.pop(); + cout << curr << " "; + for (int neigh : graph[curr]) + if (!vis[neigh]) + { + q.push(neigh); + vis[neigh] = true; + } + } +} + +int main() +{ + int n, e; + cout << "Enter the Number of Nodes : " << endl; + cin >> n; + cout << "Enter the number of Edges : " << endl; + cin >> e; + vector> graph(n); + vector vis(n, false); + for (int i = 0; i < e; i++) + { + int u, v; + cin >> u >> v; + graph[u].push_back(v); + graph[v].push_back(u); + } + for (int i = 0; i < n; i++) + { + if (!vis[i]) + bfs(graph, i, vis); + } + return 0; +} \ No newline at end of file diff --git a/BFS_2.cpp b/BFS_2.cpp new file mode 100644 index 0000000..fce318a --- /dev/null +++ b/BFS_2.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; +class Graph +{ + int V; + vector> adj; +public: + Graph(int V); + void addEdge(int v, int w); + void BFS(int s); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj.resize(V); +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); +} + +void Graph::BFS(int s) +{ + vector visited; + visited.resize(V,false); + list queue; + visited[s] = true; + queue.push_back(s); + + while(!queue.empty()) + { + s = queue.front(); + cout << s << " "; + queue.pop_front(); + for (auto adjecent: adj[s]) + { + if (!visited[adjecent]) + { + visited[adjecent] = true; + queue.push_back(adjecent); + } + } + } +} +int main() +{ + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Breadth First Traversal " + << "(starting from vertex 2) \n"; + g.BFS(2); + + return 0; +} diff --git a/Balanced Paranthesis.cpp b/Balanced Paranthesis.cpp new file mode 100644 index 0000000..fc62289 --- /dev/null +++ b/Balanced Paranthesis.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; + +unordered_mapsymbol={ {'[',-1},{'(',-2},{'{',-3},{']',1},{')',2},{'}',3}}; +void solve() +{ + string s; + cin >> s; + stackst; + for(auto bracket : s) + { + if(symbol[bracket]<0) + { + st.push(bracket); + } + else + { + if(st.empty()) + { + cout << "NO\n"; + return; + } + char top=st.top(); + st.pop(); + if(symbol[top]+symbol[bracket]!=0) + { + cout << "NO\n"; + return; + } + } + } + if(st.empty()) + { + cout << "YES\n"; + return; + } + cout << "NO\n"; + return; + +} + +int main() +{ + int t; + cin >> t; + while(t--) + { + solve(); + } +} + diff --git a/BalancedBinaryTree.cpp b/BalancedBinaryTree.cpp deleted file mode 100644 index f77ac16..0000000 --- a/BalancedBinaryTree.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -// Definition for a binary tree node. -struct TreeNode { - - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(0), left(nullptr), right(nullptr) {} - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} -}; - -class Solution { -public: - - int heightBT(TreeNode* root) { - if(root == nullptr) return 0; - - return max(heightBT(root -> left), heightBT(root -> right)) + 1; - } - - void inOrderUtil(TreeNode* root, bool &ans) { - if(root != nullptr) { - inOrderUtil(root -> left, ans); - - int d1 = heightBT(root -> left); - int d2 = heightBT(root -> right); - int diff = abs(d1 - d2); - - if(diff > 1) - ans = ans && false; - - - inOrderUtil(root -> right, ans); - } - } - - bool isBalanced(TreeNode* root) { - bool ans = true; - inOrderUtil(root, ans); - - return ans; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - vector findBall(vector>& grid) { - // Approach 1 :-> Brute Force - int n = grid.size(); - int m = grid[0].size(); - - vector ans(m); - - for(int j = 0; j < m; j++) { - int cpos = j; - int npos = -1; - for(int i = 0; i < n; i++) { - npos = cpos + grid[i][cpos]; - - if(npos < 0 or npos >= m or grid[i][cpos] != grid[i][npos]){ - cpos = -1; - break; - } - cpos = npos; - } - ans[j] = cpos; - - } - - return ans; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int m, n; - - cin >> m >> n; - - vector> grid(m, vector(n, 0)); - - for(int i = 0; i < m; i++) { - for(int j = 0; j < n; j++) { - cin >> grid[i][j]; - } - } - - Solution ans; - - - vector res = ans.findBall(grid); - - for(auto ball : res) { - cout << ball << " "; - } - - cout << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int calculate(string s) { - int len = s.length(); - if(len == 0) return 0; - int curNum = 0, lastNum = 0, result = 0; - char sign = '+'; - for(int i = 0; i < len; i++) { - char curChar = s[i]; - if(isdigit(curChar)) { - curNum = (curNum*10) + (curChar - '0'); - } - if(not isdigit(curChar) and not iswspace(curChar) or i == len - 1) { - if(sign == '+' or sign == '-') { - result += lastNum; - lastNum = (sign == '+') ? curNum : -curNum; - } - else if(sign == '*'){ - lastNum = lastNum * curNum; - } - else if(sign == '/') { - lastNum = lastNum / curNum; - } - - sign = curChar; - curNum = 0; - } - } - - result += lastNum; - cerr << result << endl; - return result; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& prices) { + int ans = 0; + int n = prices.size(); + int mini = prices[0]; + for(int i = 1 ;i -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int findMaxProfit(int i, int canBuy, int k, vector& prices, vector>>& dp) { - if(k == 0) return 0; - if(i == prices.size()) return 0; - - int maxProfit = 0; - - if(dp[i][canBuy][k] != -1) return dp[i][canBuy][k]; - - if(canBuy) { - int buy = -prices[i] + findMaxProfit(i+1, 0, k, prices, dp); - int notBuy = 0 + findMaxProfit(i+1, 1, k, prices, dp); - maxProfit = max(buy, notBuy); - } - else { - int sell = prices[i] + findMaxProfit(i+1, 1, k-1, prices, dp); - int notSell = 0 + findMaxProfit(i+1, 0, k, prices, dp); - maxProfit = max(sell, notSell); - } - - return maxProfit; - } - - int maxProfit(int k, vector& prices) { - vector>> dp(n+1, vector>(2, vector(k+1, -1))); - return findMaxProfit(0, 1, k, prices, dp); - } -}; - - - -class Solution { -public: - int maxProfit(int k, vector& prices) { - int n = prices.size(); - int tt = k; - - vector>> dp(n+1, vector>(2, vector(k+1, 0))); - - for(int i = n-1; i >= 0; i--) { - for(int canBuy = 0; canBuy <= 1; canBuy++) { - for(int k = 1; k <= tt; k++) { - int maxProfit = 0; - if(canBuy) { - int buy = -prices[i] + dp[i+1][0][k]; - int notBuy = 0 + dp[i+1][1][k]; - maxProfit = max(buy, notBuy); - } - else { - int sell = prices[i] + dp[i+1][1][k-1]; - int notSell = 0 + dp[i+1][0][k]; - maxProfit = max(sell, notSell); - } - dp[i][canBuy][k] = maxProfit; - } - } - } - - return dp[0][1][tt]; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<= 3000000 OR population >= 25000000; diff --git a/BinarySearch.cpp b/BinarySearch.cpp deleted file mode 100644 index f61d321..0000000 --- a/BinarySearch.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -class Solution { -public: - int search(vector& nums, int target) { - int low = 0; int n = nums.size(); - int high = n - 1; - - - while(low <= high){ - int mid = (low + high) / 2; - if(target == nums[mid]) - return mid; - else if(target < nums[mid]) - high = mid - 1; - else - low = mid + 1; - } - - return -1; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - int n; - cin >> n; - - int target; - - cin >> target; - - vector nums(n); - - for(auto i = 0; i < n; i++){ - cin >> nums[i]; - } - - - Solution ans; - - cout << ans.search(nums, target) << endl; - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector> levelOrder(TreeNode* root) { - vector> v; - queueq; - q.push(root); - if(root == NULL) - return v; - - while(not q.empty()){ - int x = q.size(); - vector v1; - while(x--){ - TreeNode* front = q.front(); - q.pop(); - if(front->left != NULL) - q.push(front->left); - if(front->right != NULL) - q.push(front->right); - - v1.push_back(front->val); - } - v.push_back(v1); - } - return v; - } -}; - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - // Definition for a binary tree node. - struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(0), left(nullptr), right(nullptr) {} - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - }; - -class Solution { -public: - vector rightSideView(TreeNode* root) { - - vector ans; - - queue que; - - que.push(root); - - if(root == nullptr) return ans; - - while(true) { - int size = que.size(); - - if(size == 0) return ans; - - int data = 0; - - while(size > 0) { - - TreeNode* temp = que.front(); - que.pop(); - - data = temp -> val; - - if(temp -> left != nullptr) que.push(temp -> left); - if(temp -> right != nullptr) que.push(temp -> right); - size--; - } - - ans.push_back(data); - } - - return ans; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<10 in base 2 is 1010. + * \f{eqnarray*}{ + * 2^{10_d} &=& 2^{1010_b} = 2^8 * 2^2\\ + * 2^1 &=& 2\\ + * 2^2 &=& (2^1)^2 = 2^2 = 4\\ + * 2^4 &=& (2^2)^2 = 4^2 = 16\\ + * 2^8 &=& (2^4)^2 = 16^2 = 256\\ + * \f} + * Hence to calculate 2^10 we only need to multiply \f$2^8\f$ and \f$2^2\f$ + * skipping \f$2^1\f$ and \f$2^4\f$. + * + * Bitwise Operations Used: + * a>>1 => is same as a/2. + * a>>=1 => is same as a = a/2. + * a&1 => is same as a%2. Checks wether number a is odd or not. Results to 1 i.e. True if a is odd and 0 or False otherwise. + * + * Modular Properties + * ( a * a ) % m = ( a%m * a%m ) % m + * Using this property of modular aithmetic we can efficiently calculate (a^b)%m. + */ + +#include + +/// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary +/// exponent. +long long int binExpo(long long int a, long long int b) { + if (b == 0) { + return 1; + } + long long int res = binExpo(a, b>>1); + if (b&1) { // Same as b%2==1. Result to true if b is odd. + return res * res * a; + } else { + return res * res; + } +} + +/// Recursive function to calculate exponent modular m (a^b %m) in \f$O(\log(n))\f$ using +/// binary exponentiation. +long long int binModExpo(long long int a, long long int b, long long int m) { + if (b == 0) { + return 1; + } + long long int res = binExpo(a, b>>1, m) % m; + if (b&1) { + return (res * res * a%m ) % m; + } else { + return (res * res) % m; + } +} + +/// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary +/// exponent. +long long int binExpo_alt(long long int a, long long int b) { + long long int res = 1; + while (b > 0) { + if (b&2) { + res = res * a; + } + a = a * a; + b >>= 1; + } + return res; +} + + +/// Iterative function to calculate exponent modular m (a^b %m) in \f$O(\log(n))\f$ using +/// binary exponentiation. +long long int binModExpo_alt(long long int a, long long int b, long long int m) { + long long int res = 1; + a %= m ; + while (b > 0) { + if (b&1) { + res = (res * a) % m ; + } + a = (a * a) % m; + b >>= 1 ; + } + return res; +} + +/// Main function +int main() { + long long int a, b, m; + /// Give three numbers a, b, m. + std::cin >> a >> b >> m; + if (a == 0 && b == 0) { + std::cout << "Math error" << std::endl; + } else if (b < 0) { + std::cout << "Exponent must be positive !!" << std::endl; + } else if ( m == 0 ) { + std::cout << "m cannot be zero." << std::endl; + } else { + std::cout << "Result of a^b Recursive : " << binExpo(a,b) << std::endl; + std::cout << "Result of a^b%m Recursive : " << binModExpo(a,b,m) << std::endl; + std::cout << "Result of a^b Iterative : " << binExpo_alt(a,b) << std::endl; + std::cout << "Result of a^b%m Iterative : " << binModExpo_alt(a,b,m) << std::endl; + } +} \ No newline at end of file diff --git a/Binary_search.cpp b/Binary_search.cpp new file mode 100644 index 0000000..a090a8c --- /dev/null +++ b/Binary_search.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; +int bin_search(int arr[],int n, int s){ + int mid=n/2; + int temp[mid]; + if (arr[mid]==s){ + cout<<"Element found at position "<>n; + int arr[n]; + for(int i=0; i>arr[i]; + } + cin>>s; + bin_search(arr,n,s); +} diff --git a/Bubble Sorting an Array using pointers.cpp b/Bubble Sorting an Array using pointers.cpp new file mode 100644 index 0000000..ff9db3e --- /dev/null +++ b/Bubble Sorting an Array using pointers.cpp @@ -0,0 +1,22 @@ +#include +void main(){ + int *a,i,j,t,n; + printf("Size of Array : "); + scanf("%d",&n); + printf("Give Array Elements: "); + for(i=0;i *(a+j)){ + t = *(a+i);*(a+i) = *(a+j); + *(a+j) = t; + } + } + } + printf("Sorted array is: "); + for(i=0;i +using namespace std; + +// A function to implement bubble sort +void bubbleSort(int arr[], int n) +{ + int i, j; + for (i = 0; i < n - 1; i++) + + // Last i elements are already + // in place + for (j = 0; j < n - i - 1; j++) + if (arr[j] > arr[j + 1]) + swap(arr[j], arr[j + 1]); + /* + //can also be done using a temporary varibale + + temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp + */ +} + +// Function to print an array +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout << arr[i] << " "; + cout << endl; +} + +// Driver code +int main() +{ + int arr[] = { 5, 1, 4, 2, 8}; + int N = sizeof(arr) / sizeof(arr[0]); + bubbleSort(arr, N); + cout << "Sorted array: \n"; + printArray(arr, N); + return 0; +} diff --git a/BullsAndCow.cpp b/BullsAndCow.cpp deleted file mode 100644 index fe98365..0000000 --- a/BullsAndCow.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - string getHint(string secret, string guess) { - int secretFre[10] = {0}; - int guessFre[10] = {0}; - - int bull = 0; - int cow = 0; - // BULL - for(int i = 0; i < secret.size(); i++) { - if(secret[i] == guess[i]) - bull++; - else { - secretFre[secret[i] - '0']++; - guessFre[guess[i] - '0']++; - } - } - - for(int i = 0; i < 10; i++) { - cow += min(secretFre[i], guessFre[i]); - } - - return to_string(bull) + "A" + to_string(cow) + "B"; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { -public: - int numBusesToDestination(vector>& routes, int source, int target) { - unordered_map> stop_routes; - - for(int i = 0; i < routes.size(); i++) { - for(int j : routes[i]) - stop_routes[j].insert(i); - } - - queue> to_visit; - - to_visit.push({source, 0}); - - unordered_set stops_visited = {source}; - - while(not to_visit.empty()) { - int stop = to_visit.front().first; - int bus_n = to_visit.front().second; - - if(stop == target) { - return bus_n; - } - - to_visit.pop(); - - for(const auto& route : stop_routes[stop]) { - for(const auto& next_stop : routes[route]) { - auto it = stops_visited.insert(next_stop); - if(it.second) - to_visit.push({next_stop, bus_n+1}); - } - - routes[route].clear (); - } - } - - return -1; - } -}; - - - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - int maxProfit(vector& prices) { - int maxProfit = 0; - int minPrice = INT_MAX; - - for(int i = 0; i < prices.size(); i++){ - minPrice = min(minPrice, prices[i]); - maxProfit = max(maxProfit, prices[i] - minPrice); - } - - return maxProfit; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n; - cin >> n; - vector prices(n); - - for(auto i = 0; i < n; i++){ - cin >> prices[i]; - } - - Solution ans; - - cout << ans.maxProfit(prices) << endl; - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include + +// Function to draw moving car +void draw_moving_car(void) { + + int i, j = 0, gd = DETECT, gm; + + // Passed three arguments to initgraph + // function to initialize graphics mode + initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); + + for (i = 0; i <= 420; i = i + 10) { + + // Set color of car as red + setcolor(RED); + + // Thease lines for bonnet and + // body of car + line(0 + i, 300, 210 + i, 300); + line(50 + i, 300, 75 + i, 270); + line(75 + i, 270, 150 + i, 270); + line(150 + i, 270, 165 + i, 300); + line(0 + i, 300, 0 + i, 330); + line(210 + i, 300, 210 + i, 330); + + // For left wheel of car + circle(65 + i, 330, 15); + circle(65 + i, 330, 2); + + // For right wheel of car + circle(145 + i, 330, 15); + circle(145 + i, 330, 2); + + // Line left of left wheel + line(0 + i, 330, 50 + i, 330); + + // Line middle of both wheel + line(80 + i, 330, 130 + i, 330); + + // Line right of right wheel + line(210 + i, 330, 160 + i, 330); + + delay(100); + + // To erase previous drawn car, draw + // the whole car at same position + // but color using black + //setcolor(BLACK); + + // Lines for bonnet and body of car + //line(0 + i, 300, 210 + i, 300); + //line(50 + i, 300, 75 + i, 270); + //line(75 + i, 270, 150 + i, 270); + //line(150 + i, 270, 165 + i, 300); + //line(0 + i, 300, 0 + i, 330); + //line(210 + i, 300, 210 + i, 330); + + // For left wheel of car + //circle(65 + i, 330, 15); + //circle(65 + i, 330, 2); + + // For right wheel of car + //circle(145 + i, 330, 15); + //circle(145 + i, 330, 2); + + // Line left of left wheel + //line(0 + i, 330, 50 + i, 330); + + // Line middle of both wheel + //line(80 + i, 330, 130 + i, 330); + + // Line right of right wheel + //line(210 + i, 330, 160 + i, 330); + Cleardevice(); + } + + getch(); + + closegraph(); +} + +// Driver code +int main() +{ + draw_moving_car(); + + return 0; +} diff --git a/CLosestPAirOfPoints.cpp b/CLosestPAirOfPoints.cpp new file mode 100644 index 0000000..d43aa87 --- /dev/null +++ b/CLosestPAirOfPoints.cpp @@ -0,0 +1,144 @@ +// A divide and conquer program in C++ to find the smallest distance from a +// given set of points. +#include +#include +#include +#include +using namespace std; + +// A structure to represent a Point in 2D plane +struct Point +{ + int x, y; +}; +// Needed to sort array of points according to X coordinate +int compareX(const void *a, const void *b) +{ + Point *p1 = (Point *)a, *p2 = (Point *)b; + return (p1->x != p2->x) ? (p1->x - p2->x) : (p1->y - p2->y); +} +// Needed to sort array of points according to Y coordinate +int compareY(const void *a, const void *b) +{ + Point *p1 = (Point *)a, *p2 = (Point *)b; + return (p1->y != p2->y) ? (p1->y - p2->y) : (p1->x - p2->x); +} + +// A utility function to find the distance between two points +float dist(Point p1, Point p2) +{ + return sqrt((p1.x - p2.x) * (p1.x - p2.x) + + (p1.y - p2.y) * (p1.y - p2.y)); +} + +// A Brute Force method to return the smallest distance between two points +// in P[] of size n +float bruteForce(Point P[], int n) +{ + float min = FLT_MAX; + for (int i = 0; i < n; ++i) + for (int j = i + 1; j < n; ++j) + if (dist(P[i], P[j]) < min) + min = dist(P[i], P[j]); + return min; +} + +// A utility function to find a minimum of two float values +float min(float x, float y) +{ + return (x < y) ? x : y; +} + +// A utility function to find the distance between the closest points of +// strip of a given size. All points in strip[] are sorted according to +// y coordinate. They all have an upper bound on minimum distance as d. +// Note that this method seems to be a O(n^2) method, but it's a O(n) +// method as the inner loop runs at most 6 times +float stripClosest(Point strip[], int size, float d) +{ + float min = d; // Initialize the minimum distance as d + + // Pick all points one by one and try the next points till the difference + // between y coordinates is smaller than d. + // This is a proven fact that this loop runs at most 6 times + for (int i = 0; i < size; ++i) + for (int j = i + 1; j < size && (strip[j].y - strip[i].y) < min; ++j) + if (dist(strip[i], strip[j]) < min) + min = dist(strip[i], strip[j]); + + return min; +} + +// A recursive function to find the smallest distance. The array Px contains +// all points sorted according to x coordinates and Py contains all points +// sorted according to y coordinates +float closestUtil(Point Px[], Point Py[], int n) +{ + // If there are 2 or 3 points, then use brute force + if (n <= 3) + return bruteForce(Px, n); + + // Find the middle point + int mid = n / 2; + Point midPoint = Px[mid]; + + // Divide points in y sorted array around the vertical line. + // Assumption: All x coordinates are distinct. + Point Pyl[mid]; // y sorted points on left of vertical line + Point Pyr[n - mid]; // y sorted points on right of vertical line + int li = 0, ri = 0; // indexes of left and right subarrays + for (int i = 0; i < n; i++) + { + if ((Py[i].x < midPoint.x || (Py[i].x == midPoint.x && Py[i].y < midPoint.y)) && li < mid) + Pyl[li++] = Py[i]; + else + Pyr[ri++] = Py[i]; + } + + // Consider the vertical line passing through the middle point + // calculate the smallest distance dl on left of middle point and + // dr on right side + float dl = closestUtil(Px, Pyl, mid); + float dr = closestUtil(Px + mid, Pyr, n - mid); + + // Find the smaller of two distances + float d = min(dl, dr); + + // Build an array strip[] that contains points close (closer than d) + // to the line passing through the middle point + Point strip[n]; + int j = 0; + for (int i = 0; i < n; i++) + if (abs(Py[i].x - midPoint.x) < d) + strip[j] = Py[i], j++; + + // Find the closest points in strip. Return the minimum of d and closest + // distance is strip[] + return stripClosest(strip, j, d); +} + +// The main function that finds the smallest distance +// This method mainly uses closestUtil() +float closest(Point P[], int n) +{ + Point Px[n]; + Point Py[n]; + for (int i = 0; i < n; i++) + { + Px[i] = P[i]; + Py[i] = P[i]; + } + + qsort(Px, n, sizeof(Point), compareX); + qsort(Py, n, sizeof(Point), compareY); + + // Use recursive function closestUtil() to find the smallest distance + return closestUtil(Px, Py, n); +} +int main() +{ + Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; + int n = sizeof(P) / sizeof(P[0]); + cout << "The smallest distance is " << closest(P, n); + return 0; +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..41dd9eb --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,127 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/Calculator application b/Calculator application new file mode 100644 index 0000000..0100892 --- /dev/null +++ b/Calculator application @@ -0,0 +1,29 @@ +#include +void main() +{ char ch; + float p,q; + + printf("enter the type of operation you want to perform="); + scanf("%c",&ch); + printf(" enter the two numbers "); + scanf("%f %f",&p,&q); + + if(ch=='+') + { + printf("p +q=%f",p+q); + } + else if(ch=='-') + { + printf("p -q=%f",p-q); + } + else if(ch=='*') + { + printf("p*q=%f",p*q); + } + else if(ch=='/') + { + printf(" p/q=%f",p/q); + } + + +} diff --git a/Calculator.py b/Calculator.py new file mode 100644 index 0000000..7a50b2c --- /dev/null +++ b/Calculator.py @@ -0,0 +1,18 @@ + +a=int(input("Enter First Number:")) +b=int(input("Enter Second Number:")) +c=input("Enter The sign:") +if c=='*': + print("Multiplication:",a*b) +if c=='+': + print("Addition:",a+b) +if c=='-': + print("Substraction:",a-b) +if c=='/': + print("Division:",a/b) +if c=='%': + print("Moduls:",a%b) +if c=='**': + print("Power:",a**b) +if c=='//': + print("Floor Division:",a//b) diff --git a/ClimbingStair.cpp b/ClimbingStair.cpp deleted file mode 100644 index d2d5484..0000000 --- a/ClimbingStair.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -class Solution { -public: - int climbStairs(int n) { - int t[2] = {1, 1}; - - for(n -= 2; n > 0; n -= 2) { - t[0] += t[1]; - t[1] += t[0]; - } - if(n < 0) return t[1]; - - return t[0]+t[1]; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - int n; - cin >> n; - - Solution result; - - cout << result.climbStairs(n) << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<1 or directly 2 + + + // from n = 3 ==> calculate from last two steps + for(int i = 3; i <= n; i++){ + arr[i] = arr[i-1]+arr[i-2]; + } + return arr[n]; + + } +}; diff --git a/Coin_Change_2_DP.cpp b/Coin_Change_2_DP.cpp new file mode 100644 index 0000000..07b6dcc --- /dev/null +++ b/Coin_Change_2_DP.cpp @@ -0,0 +1,45 @@ +//problem-statement +//You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. +//Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. +//You may assume that you have an infinite number of each kind of coin. +#include + +using namespace std; + +long countWaysToMakeChange(vector& arr, int n, int T){ + + vector> dp(n,vector(T+1,0)); + + + //Initializing base condition + for(int i=0;i<=T;i++){ + if(i%arr[0]==0) + dp[0][i]=1; + // Else condition is automatically fulfilled, + // as dp array is initialized to zero + } + + for(int ind=1; ind arr ={1,2,3}; + int target=4; + + int n =arr.size(); + + cout<<"The total number of ways is " <> sum = combinationSum(candidates, 7); + System.out.println(sum); + } + public static List> combinationSum(int[] candidates, int target) { + List> ans = new ArrayList<>(); + findCombination(0, candidates, target, ans, new ArrayList<>()); + return ans; + } + public static void findCombination(int index, int[] arr, int target, List> ans, List ds){ + if(index == arr.length){ + if(target == 0){ + ans.add(new ArrayList<>(ds)); + } + return; + } + + if(arr[index] <= target){ + ds.add(arr[index]); + findCombination(index, arr, target - arr[index], ans, ds); + ds.remove(ds.size()-1); + } + findCombination(index+1, arr, target, ans, ds); + } +} +======= +// https://leetcode.com/problems/combination-sum/ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CombinationSum { + public static void main(String[] args) { + int[] candidates = {2,3,6,7}; + List> sum = combinationSum(candidates, 7); + System.out.println(sum); + } + public static List> combinationSum(int[] candidates, int target) { + List> ans = new ArrayList<>(); + findCombination(0, candidates, target, ans, new ArrayList<>()); + return ans; + } + public static void findCombination(int index, int[] arr, int target, List> ans, List ds){ + if(index == arr.length){ + if(target == 0){ + ans.add(new ArrayList<>(ds)); + } + return; + } + + if(arr[index] <= target){ + ds.add(arr[index]); + findCombination(index, arr, target - arr[index], ans, ds); + ds.remove(ds.size()-1); + } + findCombination(index+1, arr, target, ans, ds); + } +} +>>>>>>> 67aafb10a70e470ee512334062930bef20542fa0 diff --git a/Combination_Sum.cpp b/Combination_Sum.cpp new file mode 100644 index 0000000..c4e7fff --- /dev/null +++ b/Combination_Sum.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + vector> ans; + vector sum; + sort(candidates.begin(),candidates.end()); + combination(candidates, target, sum, 0, ans); + return ans; + } + + void combination(vector & nums, int target, vector &sum, int idx, vector>& ans) + { + if(target==0) + { + return ans.push_back(sum); + } + + if(target<0) + { + return; + } + + for(int i=idx;iidx && nums[i]==nums[i-1]) + continue; + + sum.push_back(nums[i]); + combination(nums,target-nums[i],sum,i+1,ans); + sum.pop_back(); + } + } +}; diff --git a/Combinations.cpp b/Combinations.cpp deleted file mode 100644 index 6948ba3..0000000 --- a/Combinations.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - void add(int i, int n, int k, vector& v, vector>& res, int count) { - for(int j = i; j <= n; j++) { - v[count - 1] = j; - - if(count == k) - res.push_back(v); - else - add(j+1, n, k, v, res, count+1); - } - } - - vector> combine(int n, int k) { - vector v; - - vector> res; - - for(int i = 0; i < k; i++) { - v.push_back(0); - } - - add(1, n, k, v, res, 1); - - return res; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< getConcatenation(vector& nums) { + vector ans = nums; + + for(int i=0; i& height) { + int water = 0; + int i = 0, j = height.size() - 1; + while (i < j) { + int h = min(height[i], height[j]); + water = max(water, (j - i) * h); + while (height[i] <= h && i < j) i++; + while (height[j] <= h && i < j) j--; + } + return water; +} diff --git a/ContainerWithMostWater.cpp b/ContainerWithMostWater.cpp deleted file mode 100644 index ed5a5e9..0000000 --- a/ContainerWithMostWater.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - int maxArea(vector& height) { - int left = 0; - int right = height.size()-1; - - int ans = 0; - - while(left <= right) { - ans = max(min(height[left], height[right])*(right-left), ans); - if(height[left] <= height[right]) - left++; - else - right--; - } - - return ans; - } -}; - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< dp(n + 1); + dp[0] = 1; + for (int i = 0; i < n; i++) + { + dp[i + 1] = dp[i]; + if (i > 0 and s[i] == s[i - 1]) + { + dp[i + 1] = (dp[i + 1] + dp[i - 1]) % mod; + if (i > 1 and s[i] == s[i - 2]) + { + dp[i + 1] = (dp[i + 1] + dp[i - 2]) % mod; + if (i > 2 and s[i] == s[i - 3] and (s[i] == '7' or s[i] == '9')) + dp[i + 1] = (dp[i + 1] + dp[i - 3]) % mod; + } + } + } + return dp[n]; + } +}; diff --git a/Count_Reverse_Pairs.java b/Count_Reverse_Pairs.java new file mode 100644 index 0000000..16da23a --- /dev/null +++ b/Count_Reverse_Pairs.java @@ -0,0 +1,55 @@ +//https://leetcode.com/problems/reverse-pairs/ +//Given an array of numbers, you need to return the count of reverse pairs. Reverse Pairs are those pairs where i2*arr[j]. +// Time Complexity : O( N log N ) + O (N) + O (N) +// Space Complexity : O(N) + +import java.util.*; + +public class Count_Reverse_Pairs { + static int merge(int[] nums, int low, int mid, int high) { + int cnt = 0; + int j = mid + 1; + for(int i = low;i<=mid;i++) { + while(j<=high && nums[i] > (2 * (long) nums[j])) { + j++; + } + cnt += (j - (mid+1)); + } + + ArrayList temp = new ArrayList<>(); + int left = low, right = mid+1; + while(left <= mid && right<=high) { + if(nums[left]<=nums[right]) { + temp.add(nums[left++]); + } + else { + temp.add(nums[right++]); + } + } + + while(left<=mid) { + temp.add(nums[left++]); + } + while(right<=high) { + temp.add(nums[right++]); + } + + for(int i = low; i<=high;i++) { + nums[i] = temp.get(i - low); + } + return cnt; + } + static int mergeSort(int[] nums, int low, int high) { + if(low>=high) return 0; + int mid = (low + high) / 2; + int inv = mergeSort(nums, low, mid); + inv += mergeSort(nums, mid+1, high); + inv += merge(nums, low, mid, high); + return inv; + } + public int reversePairs(int[] nums) { + return mergeSort(nums, 0, nums.length - 1); + } +} + + diff --git a/Counting Bits.cpp b/Counting Bits.cpp new file mode 100644 index 0000000..335ef2c --- /dev/null +++ b/Counting Bits.cpp @@ -0,0 +1,18 @@ +/* + +Counting Bits + + +Share +Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. + +*/ + +vector countBits(int n) { + vector answer; + for(int i = 0; i <=n; i++){ + int m = __builtin_popcount(i); + answer.push_back(m); + } + return answer; + } diff --git a/CourseSchedular.cpp b/CourseSchedular.cpp new file mode 100644 index 0000000..a4c7f4b --- /dev/null +++ b/CourseSchedular.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + vector findOrder(int V, vector>& a) { + + + + vectoradj[V+1]; + for(int i=0;iindegree(V,0); + + for(int i=0;iq; + for(int i=0;iv; + while(!q.empty()){ + + + + + int x=q.front(); + v.push_back(x); + q.pop(); + + for(auto it : adj[x]){ + + indegree[it]--; + if(indegree[it]==0)q.push(it); + } + + + } + if(v.size()!=V){ + + return {}; + } + return v; + } +}; diff --git a/Create Grading Students problem.py b/Create Grading Students problem.py new file mode 100644 index 0000000..5f23bbf --- /dev/null +++ b/Create Grading Students problem.py @@ -0,0 +1,46 @@ +#!/bin/python3 + +import math +import os +import random +import re +import sys + +def gradingStudents(grades): + + for i in range(0,len(grades)): + + if grades[i] < 38: #grade is less than 38 , no rounding occurs as the result will still be a failing grade + continue + else: + temp = grades[i] + te = temp % 5 #If the difference between grade and the next multiple of 5 is less than 3 , round up to the next multiple of 5 + if te == 3: + temp = temp + 2 + grades[i] = temp + elif te == 4: + temp = temp + 1 + grades[i] = temp + else: + continue + return grades + + + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + grades_count = int(input().strip()) + + grades = [] + + for _ in range(grades_count): + grades_item = int(input().strip()) + grades.append(grades_item) + + result = gradingStudents(grades) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() \ No newline at end of file diff --git a/DFA.py b/DFA.py new file mode 100644 index 0000000..79efead --- /dev/null +++ b/DFA.py @@ -0,0 +1,96 @@ + Python3 program to implement DFS that accepts +# all Stringing which follow the language +# L = {a ^ n b ^ m (n)mod 2 = 0, m>= 1 } + +# This function is for the dfa = starting +# dfa = state (zeroth) of DFA +def start(c): + if (c == 'a'): + dfa = 1 + elif (c == 'b'): + dfa = 3 + + # -1 is used to check for any + # invalid symbol + else: + dfa = -1 + return dfa + +# This function is for the first +# dfa = state of DFA +def state1(c): + if (c == 'a'): + dfa = 2 + elif (c == 'b'): + dfa = 4 + else: + dfa = -1 + return dfa + +# This function is for the second +# dfa = state of DFA +def state2(c): + if (c == 'b'): + dfa = 3 + elif (c == 'a'): + dfa = 1 + else: + dfa = -1 + return dfa + +# This function is for the third +# dfa = state of DFA +def state3(c): + if (c == 'b'): + dfa = 3 + elif (c == 'a'): + dfa = 4 + else: + dfa = -1 + return dfa + +# This function is for the fourth +# dfa = state of DFA +def state4(c): + dfa = -1 + return dfa + +def isAccepted(String): + + # store length of Stringing + l = len(String) + + # dfa tells the number associated + # with the present dfa = state + dfa = 0 + for i in range(l): + if (dfa == 0): + dfa = start(String[i]) + + elif (dfa == 1): + dfa = state1(String[i]) + + elif (dfa == 2) : + dfa = state2(String[i]) + + elif (dfa == 3) : + dfa = state3(String[i]) + + elif (dfa == 4) : + dfa = state4(String[i]) + else: + return 0 + if(dfa == 3) : + return 1 + else: + return 0 + +# Driver code +if __name__ == "__main__" : + String = "aaaaaabbbb" + if (isAccepted(String)) : + print("ACCEPTED") + else: + print("NOT ACCEPTED") + +# This code is contributed by XPLOSIVE POTATO. diff --git a/DFS.cpp b/DFS.cpp new file mode 100644 index 0000000..5d73fd2 --- /dev/null +++ b/DFS.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +void dfs(vector> &graph, int source, vector &vis) +{ + cout << source << " "; + vis[source] = true; + for (int neigh : graph[source]) + if (!vis[neigh]) + dfs(graph, neigh, vis); +} + +int main() +{ + int n, e; + cin >> n >> e; + vector> graph(n); + vector vis(n, false); + for (int i = 0; i < e; i++) + { + int u, v; + cin >> u >> v; + graph[u].push_back(v); + graph[v].push_back(u); + } + for (int i = 0; i < n; i++) + { + if (!vis[i]) + dfs(graph, i, vis); + } + return 0; +} \ No newline at end of file diff --git a/Delete Node in a Linked List.cpp b/Delete Node in a Linked List.cpp new file mode 100644 index 0000000..a63ebac --- /dev/null +++ b/Delete Node in a Linked List.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + void deleteNode(ListNode* node) { + ListNode* temp = node -> next; + node -> val = temp -> val; + node -> next = temp -> next; + delete temp; + } +}; diff --git a/Design_A_Text_Editor.cpp b/Design_A_Text_Editor.cpp new file mode 100644 index 0000000..34a39d0 --- /dev/null +++ b/Design_A_Text_Editor.cpp @@ -0,0 +1,86 @@ +class TextEditor { +public: + std::list v; + std::list::iterator itr; + TextEditor() { + v.clear(); + v.insert(v.begin(), '#'); + itr = v.end(); + } + void showme() + { + for (auto &i : v) + cout << i; + cout << endl; + } + void addText(string text) { + for (auto &i : text) + v.insert(itr, i); + } + + int deleteText(int k) { + int res = 0; + while (k-- and itr != v.begin()) + itr--, res++; + if (itr == v.begin()) + itr++, res--; + k = res; + while (res-- and itr != v.end()) + itr = v.erase(itr); + return k; + } + + string cursorLeft(int k) { + while (k-- and itr != v.begin()) + itr--; + if (itr == v.begin()) + { + itr++; + return ""; + } + auto it = itr; + k = 10; + string ans = ""; + while (it != v.begin() and k--) + { + it--; + ans += *it; + } + if (it == v.begin()) + { + ans.pop_back(); + it++; + } + reverse(ans.begin(), ans.end()); + return ans; + } + + string cursorRight(int k) { + while (k-- and itr != v.end()) + itr++; + auto it = itr; + k = 10; + string ans = ""; + while (it != v.begin() and k--) + { + it--; + ans += *it; + } + if (it == v.begin()) + { + ans.pop_back(); + it++; + } + reverse(ans.begin(), ans.end()); + return ans; + } +}; + +/** + * Your TextEditor object will be instantiated and called as such: + * TextEditor* obj = new TextEditor(); + * obj->addText(text); + * int param_2 = obj->deleteText(k); + * string param_3 = obj->cursorLeft(k); + * string param_4 = obj->cursorRight(k); + */ diff --git a/Disjisktra.cpp b/Disjisktra.cpp new file mode 100644 index 0000000..ae52f76 --- /dev/null +++ b/Disjisktra.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +void dijisktra(vector>> &adj, int source) +{ + int n = adj.size(); + vector vis(n, false); + vector dis(n, INT_MAX); + set> st; + + st.insert({0, source}); + dis[source] = 0; + + while (st.size() > 0) + { + auto node = *st.begin(); + int v = node.second; + int v_dis = node.first; + st.erase(st.begin()); + if (vis[v]) + continue; + vis[v] = true; + for (auto neigh : adj[v]) + { + int neigh_v = neigh.first; + int neigh_wt = neigh.second; + if (dis[v] + neigh_wt < dis[neigh_v]) + { + dis[neigh_v] = dis[v] + neigh_wt; + st.insert({dis[neigh_v], neigh_v}); + } + } + } + for (int i = 0; i < n; i++) + cout << "distance from " << source << " to " << i << " is : - > " << dis[i] << endl; +} +int main() +{ + int n, m; + cout << "Enter Number of Nodes" << endl; + cin >> n; + cout << "Enter number of edges" << endl; + cin >> m; + vector>> adj(n); + for (int i = 0; i < m; i++) + { + int u, v, w; + cin >> u >> v >> w; + adj[u].push_back({v, w}); + } + int source; + cin >> source; + dijisktra(adj, source); + return 0; +} +// 0 1 4 0 7 8 1 2 8 1 7 1 2 3 7 2 8 2 2 5 4 3 4 9 3 5 1 4 5 1 5 6 2 6 7 1 6 8 6 7 8 7 \ No newline at end of file diff --git a/Distance of nearest cell having 1 b/Distance of nearest cell having 1 new file mode 100644 index 0000000..89d0d22 --- /dev/null +++ b/Distance of nearest cell having 1 @@ -0,0 +1,46 @@ + +#include +#define N 3 +#define M 4 +using namespace std; + +void printDistance(int mat[N][M]) +{ + int ans[N][M]; + + for (int i = 0; i < N; i++) + for (int j = 0; j < M; j++) + ans[i][j] = INT_MAX; + + for (int i = 0; i < N; i++) + for (int j = 0; j < M; j++) { + // Traversing the whole matrix + // to find the minimum distance. + for (int k = 0; k < N; k++) + for (int l = 0; l < M; l++) { + // If cell contain 1, check + // for minimum distance. + if (mat[k][l] == 1) + ans[i][j] + = min(ans[i][j], + abs(i - k) + abs(j - l)); + } + } + + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) + cout << ans[i][j] << " "; + + cout << endl; + } +} + +int main() +{ + int mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; + + // Function call + printDistance(mat); + + return 0; +} diff --git a/EditDistance.cpp b/EditDistance.cpp new file mode 100644 index 0000000..1dab8aa --- /dev/null +++ b/EditDistance.cpp @@ -0,0 +1,41 @@ +/*Name -:Jai Sinha + Date-:03-10-2022 */ + +//Question +//to convert one string to another by deleting,updating,replacing the characters of the first string in minimum moves + + +#include +using namespace std; +int editDistance(string str1, string str2) +{ + //doing space optimization + int n=str1.length(); + int m=str2.length(); + vector pre(m+1,0); //creating a pre vector + for(int i=0;i<=m;i++) + pre[i]=i; //initializing the pre vector by i + for(int i=1;i<=n;i++) + { + vector temp(m+1,0); //making a temperorary vector + temp[0]=i; + for(int j=1;j<=m;j++) + { + if(str1[i-1]==str2[j-1]) //if the previous elements are equal + temp[j]= pre[j-1]; store the value + else + temp[j]=1+min(pre[j],min(temp[j-1],pre[j-1])); //else store the minimum of the elements + } + pre=temp; //now==>previous vector becomes temp vector + } + return pre[m]; +} +//main function +int main() +{ + string s; + cin>>s; + string s2; + cin>>s2; + return editDistance(s,s2); //calling function +} diff --git a/Eventual_safe_states b/Eventual_safe_states new file mode 100644 index 0000000..3677944 --- /dev/null +++ b/Eventual_safe_states @@ -0,0 +1,79 @@ +#include +using namespace std; +class Solution { +public: + bool detect(int node,vectoradj[],int vis[],int pathVis[],int check[]) + { + vis[node]=1; + pathVis[node]=1; + check[node]=0; + //traversing all adjacent nodes + for(auto adjacentNode:adj[node]) + { + //when the node is not visited + if(!vis[adjacentNode]) + { + if(detect(adjacentNode,adj,vis,pathVis,check)) + { + check[node]=0; + return true; + } + } + //if the node has been previously visited + //but it has to be visited on the same path + else if(pathVis[adjacentNode]) + { + check[node]=0; + return true; + } + } + check[node]=1; + pathVis[node]=0; + return false; + } + vector eventualSafeNodes(int V, vector adj[]) + { + int vis[V]={0}; + int check[V]={0}; + int pathVis[V]={0}; + vectorans; + for(int i = 0 ; i < V ; i++) + { + if(!vis[i]) + { + detect(i,adj,vis,pathVis,check); + } + } + for(int i = 0 ; i >t; + while(t--) + { + int Vertices,Edges; + cin>>Vertices>>Edges; + vectoradj[Vertices]; + + for(int i = 0 ; i < Edges ; i++) + { + int u,v;cin>>u>>v; + adj[u].push_back(v); + } + + Solution obj; + vectorsafeNodes=obj.eventualSafeNodes(V,adj); + for(auto i:safeNodes){ + cout< +#include +int fact(int); +int main() +{ + int ans, n; + printf("enter n:"); + scanf("%d",&n); + ans = fact(n); + printf("Factorial of %d is %d", n,ans); + return 0; +} +int fact(int n) +{ + for(int i=0; i<=n; i++) + { + if(n==0 || n==1) + { + return 1; + } + else if(n>1) + { + return(fact(n-1)*n); + } + } +} + diff --git a/Fibonacci Series without recursion b/Fibonacci Series without recursion new file mode 100644 index 0000000..64e6399 --- /dev/null +++ b/Fibonacci Series without recursion @@ -0,0 +1,17 @@ +#include +int main() +{ int t1=0,t2=1,t3,term,n; + printf("Enter the no of term = "); + scanf("%d",&n); + printf("%d\t%d\t",t1,t2); + for(term=3;term<=n;term++) + { + t3=t1+t2; + printf("%d\t",t3); + t1=t2; + t2=t3; + + } + + return 0; +} diff --git a/FindCustomerReferee.sql b/FindCustomerReferee.sql new file mode 100644 index 0000000..b39d760 --- /dev/null +++ b/FindCustomerReferee.sql @@ -0,0 +1,10 @@ +# MySQL query for problem of Finding Customer Referee + +# Problem link : https://leetcode.com/problems/find-customer-referee/ + +SELECT name +From Customer +WHERE id NOT IN (SELECT id + WHERE referee_id = 2); + + diff --git a/Find_whether_an_array_is_a_subset_of_another_array.cpp b/Find_whether_an_array_is_a_subset_of_another_array.cpp new file mode 100644 index 0000000..8334169 --- /dev/null +++ b/Find_whether_an_array_is_a_subset_of_another_array.cpp @@ -0,0 +1,32 @@ + +#include +bool isSubset(int arr1[], int arr2[], int m, int n) +{ + int i = 0; + int j = 0; + for (i = 0; i < n; i++) { + for (j = 0; j < m; j++) { + if (arr2[i] == arr1[j]) + break; + } + if (j == m) + return 0; + } + return 1; +} +int main() +{ + int arr1[] = { 11, 1, 13, 21, 3, 7 }; + int arr2[] = { 11, 3, 7, 1 }; + + int m = sizeof(arr1) / sizeof(arr1[0]); + int n = sizeof(arr2) / sizeof(arr2[0]); + + if (isSubset(arr1, arr2, m, n)) + printf("arr2[] is subset of arr1[] "); + else + printf("arr2[] is not a subset of arr1[]"); + + getchar(); + return 0; +} diff --git a/FirstBadVersion.cpp b/FirstBadVersion.cpp deleted file mode 100644 index 056f624..0000000 --- a/FirstBadVersion.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -// The API isBadVersion is defined for you. -// bool isBadVersion(int version); - -class Solution { -public: - - int firstBadVersion(int n) { - int low = 0, int high = n; - int ans = 0; - - while(low <= high) { - int mid = low + (high - low)/2; - if(isBadVersion(mid)){ - high = mid - 1; - ans = mid; - } - else{ - low = mid + 1; - } - } - - return ans; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n, m; - - cin >> n >> m; - - Solution ans; - - cout << ans.firstBadVersion(n) << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { -public: - vector searchRange(vector& nums, int target) { - int low = 0; - int high = nums.size()-1; - - vector ans(2, -1); - - while (low <= high) { - int mid = low + (high - low) / 2; - - if(nums[mid] == target) { - ans[0] = mid; - high = mid - 1; - } - else if(nums[mid] < target) { - low = mid + 1; - } - else - high = mid - 1; - } - - low = 0; - high = nums.size()-1; - - while(low <= high) { - int mid = low + (high - low) / 2; - if(nums[mid] == target) { - ans[1] = mid; - low = mid + 1; - } - else if(nums[mid] < target){ - low = mid + 1; - } - else - high = mid - 1; - } - - return ans; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n; - cin >> n; - int target; - cin >> target; - - vector nums(n); - - for(int i = 0; i < nums.size(); i++) { - cin >> nums[i]; - } - - Solution ans; - - // vector result; - - cout << ans.searchRange(nums, target) << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + +int firstNonRepeating(int arr[], int n) +{ + + unordered_map mp; + for (int i = 0; i < n; i++) + mp[arr[i]]++; + + + for (int i = 0; i < n; i++) + if (mp[arr[i]] == 1) + return arr[i]; + return -1; +} + + +int main() +{ + int arr[] = { 9, 4, 9, 6, 7, 4 }; + int n = sizeof(arr) / sizeof(arr[0]); + cout << firstNonRepeating(arr, n); + return 0; +} diff --git a/FloodFill.cpp b/FloodFill.cpp deleted file mode 100644 index 3a423ae..0000000 --- a/FloodFill.cpp +++ /dev/null @@ -1,105 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - bool isValid(vector> &image, int i, int j, int n, int m, int color) { - if(i >= 0 and i < n and j >= 0 and j < m and image[i][j] == color) - return true; - - return false; - } - - void floodFillRec(vector> &image, int sr, int sc, int n, int m, int color, int newColor) { - image[sr][sc] = newColor; - - if(isValid(image, sr+1, sc, n, m, color)) - floodFillRec(image, sr+1, sc, n, m, color, newColor); - if(isValid(image, sr-1, sc, n, m, color)) - floodFillRec(image, sr-1, sc, n, m, color, newColor); - if(isValid(image, sr, sc+1, n, m, color)) - floodFillRec(image, sr, sc+1, n, m, color, newColor); - if(isValid(image, sr, sc-1, n, m, color)) - floodFillRec(image, sr, sc-1, n, m, color, newColor); - } - - vector> floodFill(vector>& image, int sr, int sc, int newColor) { - int n = image.size(); - int m = image[0].size(); - - int color = image[sr][sc]; - - if(color == newColor) return image; - - floodFillRec(image, sr, sc, n, m, color, newColor); - - return image; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; +bool isValid(int screen[][8], int m, int n, int x, int y, int prevC, int newC) +{ + if(x < 0 || x >= m || y < 0 || y >= n || screen[x][y] != prevC + || screen[x][y]== newC) + return false; + return true; +} +void floodFill(int screen[][8], int m, int n, int x, int y, int prevC, int newC) +{ + vector> queue; + pair p(x,y); + queue.push_back(p); + screen[x][y] = newC; + while(queue.size() > 0) + { + pair currPixel = queue[queue.size() - 1]; + queue.pop_back(); + + int posX = currPixel.first; + int posY = currPixel.second; + if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) + { + screen[posX + 1][posY] = newC; + p.first = posX + 1; + p.second = posY; + queue.push_back(p); + } + + if(isValid(screen, m, n, posX-1, posY, prevC, newC)) + { + screen[posX-1][posY]= newC; + p.first = posX-1; + p.second = posY; + queue.push_back(p); + } + + if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) + { + screen[posX][posY + 1]= newC; + p.first = posX; + p.second = posY + 1; + queue.push_back(p); + } + + if(isValid(screen, m, n, posX, posY-1, prevC, newC)) + { + screen[posX][posY-1]= newC; + p.first = posX; + p.second = posY-1; + queue.push_back(p); + } + } +} + +int main() +{ + int screen[][8] ={ + {1, 1, 1, 1, 1, 1, 1, 1}, + {1, 1, 1, 1, 1, 1, 0, 0}, + {1, 0, 0, 1, 1, 0, 1, 1}, + {1, 2, 2, 2, 2, 0, 1, 0}, + {1, 1, 1, 2, 2, 0, 1, 0}, + {1, 1, 1, 2, 2, 2, 2, 0}, + {1, 1, 1, 1, 1, 2, 1, 1}, + {1, 1, 1, 1, 1, 2, 2, 1}}; + int m = 8; + int n = 8; + int x = 4; + int y = 4; + int prevC = screen[x][y]; + int newC = 3; + floodFill(screen, m, n, x, y, prevC, newC); + for(int i = 0; i < m; i++) + { + for(int j = 0; j < n; j++) + { + cout << screen[i][j] << " "; + } + cout << endl; + } + + return 0; +} diff --git a/Flower Planting With No Adjacent.cpp b/Flower Planting With No Adjacent.cpp new file mode 100644 index 0000000..1d2d415 --- /dev/null +++ b/Flower Planting With No Adjacent.cpp @@ -0,0 +1,40 @@ +class Solution { + bool apply(vector>& adj, vector& colors, int u, int n, int par) { + for (int c = 1; c <= 4; c++) { + if (c != par) { + colors[u] = c; + bool safe = true; + for (int v : adj[u]) { + if (colors[v] == c) { + safe = false; + break; + } + if (colors[v] == -1 && !apply(adj, colors, v, n, c)) { + safe = false; + break; + } + } + if (safe) + break; + colors[u] = -1; + } + } + return colors[u] != -1; + } + +public: + vector gardenNoAdj(int N, vector>& paths) { + vector> adj(N); + for (auto e : paths) { + adj[e[0]-1].push_back(e[1]-1); + adj[e[1]-1].push_back(e[0]-1); + } + + vector colors(N, -1); + for (int i = 0; i < N; i++) { + if (colors[i] == -1) + apply(adj, colors, i, N, -1); + } + return colors; + } +}; diff --git a/Fractional Knapsack b/Fractional Knapsack new file mode 100644 index 0000000..6fe43b3 --- /dev/null +++ b/Fractional Knapsack @@ -0,0 +1,38 @@ +/* +struct Item{ + int value; + int weight; +}; +*/ + +bool comp(Item a,Item b){ + double r1=(double)a.value/(double)a.weight; + double r2=(double)b.value/(double)b.weight; + return r1>r2; +} + +class Solution +{ + public: + //Function to get the maximum total value in the knapsack. + double fractionalKnapsack(int W, Item arr[], int n) + { + // Your code here + sort(arr,arr+n,comp); + int currWeight=0; + double finalValue=0.0; + for(int i=0;i +using namespace std; + +// Recursive function to return gcd of a and b in single line + +int gcd(int a, int b) +{ + + return b == 0 ? a : gcd(b, a % b); +} + + +// Driver program to test above function + +int main() +{ + + int a , b ; + cin>>a>>b; + + cout<<"GCD of "< +using namespace std; + +int main() { + int n,m; + cin>>n>>m; + int arr1[n]; + int arr2[m]; + for(int i=0;i>arr1[i]; + for(int i=0;i>arr2[i]; + unordered_set s; + for (int i = 0; i < m; i++) + s.insert(arr2[i]); + for (int i = 0; i < n; i++) + if (s.find(arr1[i]) == s.end()) + cout << arr1[i] << " "; +// Agr element set me nahi hota hai to set ka end point return krdeta hai +// Aur agr element hota hai to wo s.end ke equal nahi hoga wo us element ka pointer dedega +// s.find(element) returns an iterator pointing to the element, if the iterator reaches s.end() +// that means if it reaches the end of set s, which actually means that the element is not in the set +// and we had reached the end searching the whole set, then cout<& citations) { + const auto n = citations.size(); + vector count(n + 1, 0); + for (const auto& x : citations) { + // Put all x >= n in the same bucket. + if (x >= n) { + ++count[n]; + } else { + ++count[x]; + } + } + + int h = 0; + for (int i = n; i >= 0; --i) { + h += count[i]; + if (h >= i) { + return i; + } + } + return h; + } +}; + + +// Time complexity: O(n) +// Space complexity: O(n) diff --git a/Height_Of_A_Binary_Tree.cpp b/Height_Of_A_Binary_Tree.cpp new file mode 100644 index 0000000..f1c17da --- /dev/null +++ b/Height_Of_A_Binary_Tree.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; + +class node { +public: + int data; + node* left; + node* right; +}; + +int maxHeight(node* node) +{ + if (node == NULL) + return 0; + else + { + int lHeight = mmaxHeight(node->left); + int rHeight = maxHeight(node->right); + + return max(lHeight+1,rHeight+1); + + } +} + + +node* newNode(int data) +{ + node* Node = new node(); + Node->data = data; + Node->left = NULL; + Node->right = NULL; + + return (Node); +} + +// Driver code +int main() +{ + node* root = newNode(1); + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(4); + root->left->right = newNode(5); + + cout<<"Height of tree is "< +using namespace std; + +class Solution { +public: +int countOfDistinctNo(string str){ + // Code here + int n = str.length() ; + long long int dp[n+1] , hash[256] ; + vector>dp_aux(n+1 , vector(n+1 , 0)); + memset(dp , 0 , sizeof(dp)); + memset(hash , 0 , sizeof(hash)); + + + long long int mod = 1000000007; + + + for(int i=0;i<=n;i++){ + + for(int j=0;j<=i;j++){ + + if(j == 0 || j == i) dp_aux[i][j] = 1; + + else if(j == 1) dp_aux[i][j] = i; + else dp_aux[i][j] = dp_aux[i-1][j] + dp_aux[i-1][j-1]; + + dp_aux[i][j] %= mod; + + } + } + + + + + + dp[0] = 1; + int zero = 0; + + + for(int i=0;i=0;k--){ + + for(int j=1;j<=freq;j++){ + + + if(k-j < 0) break; + dp[k] += (dp[k-j]* 1LL * dp_aux[k][k-j]) % mod; + dp[k] %= mod; + + } + } + } + + + for(int k=n;k>=0;k--){ + + for(int j=1;j<=zero;j++){ + + if(k-j <= 0) break; + + dp[k] += (dp[k-j] * 1LL * dp_aux[k-1][k-j-1]) % mod; + dp[k] %= mod; + } + } + + if(zero) dp[1]++; + + long long int sum = 0; + for(int i=1;i<=n;i++){ + + sum += dp[i]; + sum %= mod; + } + + return sum; +} +}; +int main(){ +int t; +cin>>t; +while(t--){ +string s; +cin>>s; +Solution a; +cout< 1: + (key1, c1) = nodes[-1] + (key2, c2) = nodes[-2] + nodes = nodes[:-2] + node = NodeTree(key1, key2) + nodes.append((node, c1 + c2)) + + nodes = sorted(nodes, key=lambda x: x[1], reverse=True) + +huffmanCode = huffman_code_tree(nodes[0][0]) + +print(' Char | Huffman code ') +print('----------------------') +for (char, frequency) in freq: + print(' %-4r |%12s' % (char, huffmanCode[char])) diff --git a/ImpQueueUsingStack.cpp b/ImpQueueUsingStack.cpp deleted file mode 100644 index 45727c8..0000000 --- a/ImpQueueUsingStack.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class MyQueue { -public: - - stackinput, output; - - MyQueue() { - - } - - void push(int x) { - input.push(x); - } - - int pop() { - int val = peek(); - output.pop(); - return val; - } - - int peek() { - if(output.empty()) { - while(input.empty() == false) { - output.push(input.top()); - input.pop(); - } - } - - return output.top(); - } - - bool empty() { - return input.empty() and output.empty(); - } -}; - -/** - * Your MyQueue object will be instantiated and called as such: - * MyQueue* obj = new MyQueue(); - * obj->push(x); - * int param_2 = obj->pop(); - * int param_3 = obj->peek(); - * bool param_4 = obj->empty(); - */ - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector> insert(vector>& intervals, vector& newInterval) { - int flag = 1; - - for(int i = 0; i < intervals.size(); i++) { - if(newInterval[0] < intervals[i][0]) { - flag = 0; - intervals.insert(intervals.begin()+i, newInterval); - break; - } - } - - if(flag) { - intervals.insert(intervals.end(), newInterval); - } - - vector> ans; - - int start = intervals[0][0]; - int end = intervals[0][1]; - - for(int i = 1; i < intervals.size(); i++) { - if(intervals[i][0] <= end) { - end = max(end, intervals[i][1]); - } - - else { - ans.push_back({start, end}); - start = intervals[i][0]; - end = intervals[i][1]; - } - } - - ans.push_back({start, end}); - - return ans; - - } -}; - - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< str: + valueSymbols = [(1000, 'M'), (900, 'CM'), + (500, 'D'), (400, 'CD'), + (100, 'C'), (90, 'XC'), + (50, 'L'), (40, 'XL'), + (10, 'X'), (9, 'IX'), + (5, 'V'), (4, 'IV'), + (1, 'I')] + ans = [] + + for value, symbol in valueSymbols: + if num == 0: + break + count, num = divmod(num, value) + ans.append(symbol * count) + + return ''.join(ans) + diff --git a/IntegertoRoman.cpp b/IntegertoRoman.cpp deleted file mode 100644 index 6077d83..0000000 --- a/IntegertoRoman.cpp +++ /dev/null @@ -1,143 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - string intToRoman(int num) { - string roman = ""; - - while(num >= 1000){ - roman = roman + "M"; - num -= 1000; - } - - if(num >= 900){ - roman = roman + "CM"; - num -= 900; - } - - while(num >= 500){ - roman = roman + "D"; - num -= 500; - } - - if(num >= 400){ - roman = roman + "CD"; - num -= 400; - } - - while(num >= 100){ - roman = roman + "C"; - num -= 100; - } - - if(num >= 90){ - roman = roman + "XC"; - num -= 90; - } - - while(num >= 50){ - roman = roman + "L"; - num -= 50; - } - - if(num >= 40){ - roman = roman + "XL"; - num -= 40; - } - - while(num >= 10){ - roman = roman + "X"; - num -= 10; - } - - if(num == 9){ - roman = roman + "IX"; - num -= 9; - } - - while(num >= 5){ - roman = roman + "V"; - num -= 5; - } - - if(num == 4){ - roman = roman + "IV"; - num -= 4; - } - - while(num >= 1){ - roman = roman + "I"; - num -= 1; - } - return roman; - } - -}; - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int num; - cin >> num; - - Solution s; - - string str = s.intToRoman(num); - - cout << str << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<=numm[i]) + { + s=s+ans[i]; + num=num-numm[i]; + } + } + return s; + } +}; diff --git a/IsSubsequence.cpp b/IsSubsequence.cpp deleted file mode 100644 index 47f742f..0000000 --- a/IsSubsequence.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - // bool isSubsequence(string s, string t) { - // if(s == "") return true; - // if(t == "") return false; - - // if(s.size() == 1 and t.size() == 1) return s[0] == t[0]; - - // int a = 0; - - // for(int i = 0; i < t.size(); i++){ - // if(s[a] == t[i]) - // a += 1; - // } - - - // if(a == s.size()) return true; - - // else - // return false; - // } - - - bool isSubsequence(string s, string t) { - unordered_map> hg; - - for(int i = 0; i < t.length(); i++) { - hg[t[i]].push_back(i); - } - - int prev = -1; - - for(auto c : s) { - auto it = hg.find(c); - if(it == hg.end()) - return false; - auto vec = it->second; - int pos = upper_bound(vec.begin(), vec.end(), prev) - vec.begin(); - if(pos == vec.size()) return false; - - prev = vec[pos]; - } - - return true; - } - - -}; - - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - - string s, t; - - getline(cin, s); - getline(cin, t); - - // cin >> s >> t; - - Solution ans; - - bool result = ans.isSubsequence(s, t); - - cout << result << end; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - // bool isIsomorphic(string s, string t) { - // int seen[128] = {}; - // for(int i = 0; i < s.size(); i++){ - // char c = s[i]; - // if(not seen[c]){ - // for(char k : seen){ - // if(k == t[i]) - // return false; - // } - // seen[c] = t[i]; - // } - // else if(seen[c] != t[i]) - // return false; - // } - // return true; - // } - - - bool isIsomorphic(string s, string t) { - char map_s[128] = {0}; - char map_t[128] = {0}; - - for(int i = 0; i < s.size(); i++) { - if(map_s[s[i]] != map_t[t[i]]) return false; - map_s[s[i]] = i+1; - map_t[t[i]] = i+1; - } - - return true; - } - - -}; - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - string s, t; - - getline(cin, s); - getline(cin, t); - - Solution ans; - - bool result = ans.isIsomorphic(s, t); - - if(result) - cout << "true" << endl; - else - cout << "false" << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -//Top Down Method - -// class Solution { -// public: - -// int dp[1001][1001] = {}; - -// int kInversePairs(int n, int k) { -// if(k <= 0) return k == 0; -// if(dp[n][k] == 0){ -// dp[n][k] = 1; -// for(auto i = 0; i < n; i++){ -// dp[n][k] = (dp[n][k] + kInversePairs(n-1, k-i))%mod; -// } -// } - -// return dp[n][k] - 1; -// } -// }; - - -// Bottom Up Method - - -class Solution { -public: - - int dp[1001][1001] = {}; - - int kInversePairs(int n, int k) { - int dp[1001][1001] = {1}; - for(int N = 1; N <= n; N++){ - for(int K = 0; K <= k; K++){ - for(int i = 0; i <= min(,K N-1); i++){ - dp[N][k] = (dp[N][K] + dp[N-1][K-i])%mod; - } - } - } - - return dp[n][k]; - } - -}; - - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -long long maxSubarraySum(int arr[], int n) -{ - /* - Don't write main(). - Don't read input, it is passed as function argument. - No need to print anything. - Taking input and printing output is handled automatically. - - */ - long long curr=0; - long long maxTillNow=0; - for(int i=0;i>arr[i]; - } - - cout< kidsWithCandies(int[] candies, int extraCandies) { + ArrayList list = new ArrayList(); + int max = Integer.MIN_VALUE; + for(int i=0;i= max){ + list.add(true); + }else{ + list.add(false); + } + } + + return list; + } +} \ No newline at end of file diff --git a/Kruskal.cpp b/Kruskal.cpp new file mode 100644 index 0000000..e4d4092 --- /dev/null +++ b/Kruskal.cpp @@ -0,0 +1,84 @@ +#include +#include +#include +using namespace std; + +#define edge pair + +class Graph { + private: + vector > G; // graph + vector > T; // mst + int *parent; + int V; // number of vertices/nodes in graph + public: + Graph(int V); + void AddWeightedEdge(int u, int v, int w); + int find_set(int i); + void union_set(int u, int v); + void kruskal(); + void print(); +}; +Graph::Graph(int V) { + parent = new int[V]; + for (int i = 0; i < V; i++) + parent[i] = i; + + G.clear(); + T.clear(); +} +void Graph::AddWeightedEdge(int u, int v, int w) { + G.push_back(make_pair(w, edge(u, v))); +} +int Graph::find_set(int i) { + if (i == parent[i]) + return i; + else + return find_set(parent[i]); +} + +void Graph::union_set(int u, int v) { + parent[u] = parent[v]; +} +void Graph::kruskal() { + int i, uRep, vRep; + sort(G.begin(), G.end()); // increasing weight + for (i = 0; i < G.size(); i++) { + uRep = find_set(G[i].second.first); + vRep = find_set(G[i].second.second); + if (uRep != vRep) { + T.push_back(G[i]); // add to tree + union_set(uRep, vRep); + } + } +} +void Graph::print() { + cout << "Edge :" + << " Weight" << endl; + for (int i = 0; i < T.size(); i++) { + cout << T[i].second.first << " - " << T[i].second.second << " : " + << T[i].first; + cout << endl; + } +} +int main() { + Graph g(6); + g.AddWeightedEdge(0, 1, 4); + g.AddWeightedEdge(0, 2, 4); + g.AddWeightedEdge(1, 2, 2); + g.AddWeightedEdge(1, 0, 4); + g.AddWeightedEdge(2, 0, 4); + g.AddWeightedEdge(2, 1, 2); + g.AddWeightedEdge(2, 3, 3); + g.AddWeightedEdge(2, 5, 2); + g.AddWeightedEdge(2, 4, 4); + g.AddWeightedEdge(3, 2, 3); + g.AddWeightedEdge(3, 4, 3); + g.AddWeightedEdge(4, 2, 4); + g.AddWeightedEdge(4, 3, 3); + g.AddWeightedEdge(5, 2, 2); + g.AddWeightedEdge(5, 4, 3); + g.kruskal(); + g.print(); + return 0; +} \ No newline at end of file diff --git a/KthSymbol.java b/KthSymbol.java new file mode 100644 index 0000000..6519bdc --- /dev/null +++ b/KthSymbol.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/k-th-symbol-in-grammar/ +class Solution { + public int kthGrammar(int n, int k) { + if(n==1 || k==1){ + return 0; + } + if(k%2==0){ + return 1 - kthGrammar(n-1, (k+1)/2); + }else{ + return kthGrammar(n-1, (k+1)/2); + } + } +} \ No newline at end of file diff --git a/LCAofBST.cpp b/LCAofBST.cpp deleted file mode 100644 index b19be30..0000000 --- a/LCAofBST.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ - -class Solution { -public: - TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - if(root == NULL or root->val == p->val or root->val == q->val) return root; - - TreeNode* a = NULL, *b == NULL; - - if(root -> val > p -> val and root -> val > q -> val) - a = lowestCommonAncestor(root -> left, p, q); - else if(root -> val < p -> val and root -> val < q -> val) - b = lowestCommonAncestor(root -> right, p, q); - - else{ - a = lowestCommonAncestor(root -> left, p, q); - b = lowestCommonAncestor(root -> right, p, q); - } - - if(a == NULL and b == NULL) return NULL; - - if(a != NULL and b == NULL) return a; - - if(a == NULL and b != NULL) return b; - - if(a != NULL and b != NULL) return root; - - return root; - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - if(root == NULL) return NULL; - - if(root == p or root == q) return root; - - TreeNode* left = lowestCommonAncestor(root -> left, p, q); - - TreeNode* right = lowestCommonAncestor(root -> right, p, q); - - if(left and right) return root; - - if(left) return left; - - if(right) return right; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - // Definition for a binary tree node. -/* struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(0), left(nullptr), right(nullptr) {} - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - }; - -class Solution { -public: - - - TreeNode* buildT(vector &preorder, int preStart, int preEnd, vector &inorder, int inStart, int inEnd, map inMap){ - if(preStart > preEnd or inStart > inEnd) return NULL; - TreeNode* root = new TreeNode(preorder[preStart]); - - int inRoot = inMap[root->val]; - int numLeft = inRoot - inStart; - - root->left = buildT(preorder, preStart+1, preStart+numLeft, inorder, inStart, inRoot-1, inMap); - root->right = buildT(preorder, preStart+numLeft+1, preEnd, inorder, inRoot+1, inEnd, inMap); - - return root; - } - - TreeNode* buildTree(vector& preorder, vector& inorder) { - map inMap; - - for(int i = 0; i < inorder.size(); i++){ - inMap[inorder[i]] = i; - } - - TreeNode* root = buildT(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1, inMap); - - return root; - } - -}; -*/ - - - - - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - int startp = 0; - - TreeNode* construct(vector& preorder, vector& inorder, int starti, int endi) { - if(starti > endi) return NULL; - - TreeNode* root = new TreeNode(preorder[startp++]); - int k = 0; - - for(int i = starti; i <= endi; i++) { - if(inorder[i] == root->val) { - k = i; - break; - } - } - root->left = construct(preorder, inorder, starti, k-1); - root->right = construct(preorder, inorder, k+1, endi); - - return root; - } - - - TreeNode* buildTree(vector& preorder, vector& inorder) { - int n = preorder.size(); - if(n <= 0) return NULL; - return construct(preorder, inorder, 0, n-1); - } -}; - - - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - int numSubmatrixSumTarget(vector>& matrix, int target) { - int res = 0, m = matrix.size(), n = matrix[0].size(); - for(int i = 0; i < m; i++){ - for(int j = 1; j < n; j++){ - matrix[i][j] += matrix[i][j-1]; - } - } - unordered_map counter; - for(int i = 0; i < n; i++){ - for(int j = i; j < n; j++){ - counter = {{0, 1}}; - int cur = 0; - for(int k = 0; k < m; k++) { - cur += matrix[k][j] - (i > 0 ? matrix[k][i-1] : 0); - res += counter.find(cur - target) != counter.end() ? counter[cur - target] : 0; - counter[cur]++; - } - } - } - - return res; - } -}; - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { -public: - vector findSubstring(string s, vector& words) { - int len = words[0].size(), noOfWords = words.size(); - - unordered_map wordsMap; - - vector result; - - if(len*noOfWords > s.size()) return result; - - for(string word : words) - wordsMap[word]++; - for(int idx = 0; idx <= s.length()-(noOfWords*len); idx++) { - unordered_map wordsUsedMap; - - for(int chunkIdx = idx; chunkIdx < idx + (noOfWords*len); chunkIdx += len) { - string cur = s.substr(chunkIdx, len); - if(wordsMap.find(cur) == wordsMap.end()) - break; - wordsUsedMap[cur]++; - - if(wordsUsedMap[cur] > wordsMap[cur]) - break; - } - if(wordsUsedMap == wordsMap) - result.push_back(idx); - } - - return result; - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - // Merge Sort - - - void merge(vector> &arr, vector&count, int l, int mid, int r) { - vector> temp(r-l+1); - - int i = l, j = mid+1, k = 0; - - while(i <= mid and j <= r) { - if(arr[i].first <= arr[j].first) - temp[k++] = arr[j++]; - else { - count[arr[i].second] += r-j+1; - temp[k++] = arr[i++]; - } - } - - while(i <= mid) { - temp[k++] = arr[i++]; - } - while(j <= r) { - temp[k++] = arr[j++]; - } - - for(int x = l; x <= r; x++) { - arr[x] = temp[x-l]; - } - } - - - - void merge_sort(vector> &arr, vector &count, int l, int r) { - if(l >= r) { - return; - } - - int mid = (l+r)/2; - merge_sort(arr, count, l, mid); - merge_sort(arr, count, mid+1, r); - merge(arr, count, l, mid, r); - - } - - - - vector countSmaller(vector& nums) { - int n = nums.size(); - vector> arr(n); - for(int i = 0; i < n; i++){ - arr[i] = {nums[i], i}; - } - vector count(n, 0); - merge_sort(arr, count, 0, n-1); - - return count; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - /*int n; - cin >> n; - - vector nums; - - for(int i = 0; i < n; i++){ - cin >> nums[i]; - } - - Solution ans; - - vector result; - - for(int i = 0; i < n; i++){ - result[i] = ans.countSmaller(nums); - } - - for(int i = 0; i < n; i++){ - cout << result[i] << endl; - }*/ - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< se = new HashSet < > (); + for (int j = i; j < str.length(); j++) // nested loop for getting different + string starting with str[i] + { + if (se.contains(str.charAt(j))) // if element if found so mark it as ans + and break from the loop + { + maxans = Math.max(maxans, j - i); + break; + } + se.add(str.charAt(j)); + } + } + return maxans; + } + + public static void main(String args[]) { + String str = "takeUforward"; + System.out.println("The length of the longest substring without repeating + characters is " + solve(str)); + + } +} diff --git a/Linked-List-Cycle-Detection.cpp b/Linked-List-Cycle-Detection.cpp new file mode 100644 index 0000000..b9566d8 --- /dev/null +++ b/Linked-List-Cycle-Detection.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool hasCycle(ListNode *head) { + ListNode *fast = head; + ListNode *slow = head; + + while(fast!=NULL && fast->next!=NULL){ + slow = slow->next; + fast = fast->next->next; + if(fast==slow){ + return true; + } + } + return false; + } +}; \ No newline at end of file diff --git a/LinkedListCycleII.cpp b/LinkedListCycleII.cpp deleted file mode 100644 index 6c092c7..0000000 --- a/LinkedListCycleII.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode *detectCycle(ListNode *head) { - if(head == nullptr or head->next == nullptr) - return NULL; - ListNode *slow = head; - ListNode *fast = head; - ListNode *entry = head; - - while(fast -> next and fast -> next -> next) { - slow = slow -> next; - fast = fast -> next -> next; - - if(slow == fast){ - while(slow != entry){ - slow = slow -> next; - entry = entry -> next; - } - return entry; - } - } - return NULL; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + +struct node{ + int data; + node* link; +}; + +node* head=NULL; +void InsertAtEnd(int d){ + node* n = new node(); + n->data=d; + n->link=NULL; + if(head==NULL){ + head=n; + cout<link)!=NULL){ + temp=temp->link; + } + temp->link=n; + cout<data=d; + n->link=head; + head=n; + cout<link; + free(ptr); + cout<link!=NULL){ + prev=temp; + temp=temp->link; + } + prev->link=NULL; + free(temp); + cout<link != NULL){ + temp=temp->link; + count++; + } + temp=head; + mid=count/2; + for(int i=0; ilink; + } + cout<data<link!=NULL){ + slow=slow->link; + fast=fast->link; + fast=fast->link; //or instead of writng 2 times, write fast->link->link; + } + cout<data<link; + cur->link=prev; + prev=cur; + cur=next; + } + head=prev; + } +} + +void display(){ + if(head==NULL){ + cout<data<<"->"; + temp=temp->link; + } + cout<<"NULL"; + } +} + +int main(){ + int choice,d; + char ans='y'; + while(ans=='y'){ + cout<<"1. Display Linked List"<>choice; + switch(choice){ + case 1: + display(); + break; + case 2: + cout<<"Enter the value to be added: "; + cin>>d; + InsertAtBeg(d); + break; + case 3: + cout<<"Enter the value to be added: "; + cin>>d; + InsertAtEnd(d); + break; + case 4: + DeleteBeg(); + break; + case 5: + DeleteEnd(); + break; + case 6: + MidDisplay(); + break; + case 7: + reverse(); + break; + default: + cout<<"Invalid Choice!"; + break; + } + cout<>ans; + } +} diff --git a/Longest Increasing Subsequence b/Longest Increasing Subsequence new file mode 100644 index 0000000..890736c --- /dev/null +++ b/Longest Increasing Subsequence @@ -0,0 +1,26 @@ +class Solution { +public: + int solve(vector& nums) + { + int n=nums.size(); + vector> dp(nums.size()+1,vector (nums.size()+1,0)); + for(int curr=n-1;curr>=-0;curr--) + { + for(int prev=curr-1;prev>=-1;prev--) + { + int include=0; + if(prev==-1 || nums[prev]& nums) { + + return solve(nums); + } +}; diff --git a/Longest Valid Parenthesis b/Longest Valid Parenthesis new file mode 100644 index 0000000..6fbb30f --- /dev/null +++ b/Longest Valid Parenthesis @@ -0,0 +1,28 @@ +class Solution { +public: + int longestValidParentheses(string s) { + int n = s.length(), longest = 0; + stack st; + for (int i = 0; i < n; i++) { + if (s[i] == '(') st.push(i); + else { + if (!st.empty()) { + if (s[st.top()] == '(') st.pop(); + else st.push(i); + } + else st.push(i); + } + } + if (st.empty()) longest = n; + else { + int a = n, b = 0; + while (!st.empty()) { + b = st.top(); st.pop(); + longest = max(longest, a-b-1); + a = b; + } + longest = max(longest, a); + } + return longest; + } +}; diff --git a/LongestPalindrome.cpp b/LongestPalindrome.cpp deleted file mode 100644 index dc5016a..0000000 --- a/LongestPalindrome.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - int longestPalindrome(string s) { - unordered_map counts; - for(char c : s) counts[c]++; - - int result = 0; - bool odd_found = false; - for(auto &c : counts) { - if(c.second % 2 == 0) { - result += c.second; - } - else { - odd_found = true; - result += c.second - 1; - } - } - - if(odd_found) result++; - return result; - } -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - string s; - - getline(cin, s); - - Solution ans; - - cout << ans.longestPalindrome(s) << end; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int longestPalindrome(vector& words) { - mapm; - - for(auto i: words) - m[i]++; - - int ans = 0; - int mid = 0; - - for(auto i : m) { - string rev = i.first; - reverse(rev.begin(), rev.end()); - - if(m[rev] != 0) { - if(rev != i.first) - ans += 4*min(m[i.first], m[rev]); - else { - ans += (m[i.first]/2)*4; - - if(m[i.first]%2) - mid = 1; - } - } - m.erase(rev); - m.erase(i.first); - } - - return ans+mid*2; - - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; +int solve(string& s, string& t, int i, int j, vector>& dp){ + if(i==s.size()) return 0; + if(j==t.size()) return 0; + if(dp[i][j]!=-1) return dp[i][j]; + int ans=0; + if(s[i]==t[j]) ans=1+solve(s,t,i+1,j+1,dp); + else ans=max(solve(s,t,i+1,j,dp), solve(s,t,i,j+1,dp)); + dp[i][j]=ans; + return dp[i][j]; +} +int longestCommonSubsequence(string text1, string text2) { + int n=text1.size(), m=text2.size(); + vector> dp(n, vector(m, -1)); + int ans=solve(text1,text2,0,0,dp); + return ans; +} +int main(){ + string s,t; + cin>>s>>t; + int ans=longestCommonSubsequence(s,t); + cout< +using namespace std; + +int lps(string& s1, string& s2, int n1, int n2) +{ + if (n1 == 0 || n2 == 0) { + return 0; + } + if (dp[n1][n2] != -1) { + return dp[n1][n2]; + } + if (s1[n1 - 1] == s2[n2 - 1]) { + return dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1); + } + else { + return dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2),lps(s1, s2, n1, n2 - 1)); + } +} + + +int main() +{ + string seq = "CARORCAR"; + int n = seq.size(); + int dp[n][n]; + memset(dp, -1, sizeof(dp)); + string s2 = seq; + reverse(s2.begin(), s2.end()); + cout<<"The length of the LPS is "< +using namespace std; + +int findCandidate(int a[], int size) +{ + int maj_index = 0, count = 1; + for (int i = 1; i < size; i++) { + if (a[maj_index] == a[i]) + count++; + else + count--; + if (count == 0) { + maj_index = i; + count = 1; + } + } + return a[maj_index]; +} + +/* Function to check if the candidate +occurs more than n/2 times */ +bool isMajority(int a[], int size, int cand) +{ + int count = 0; + for (int i = 0; i < size; i++) + + if (a[i] == cand) + count++; + + if (count > size / 2) + return 1; + + else + return 0; +} + +void printMajority(int a[], int size) +{ + int cand = findCandidate(a, size); + + if (isMajority(a, size, cand)) + cout << " " << cand << " "; + + else + cout << "No Majority Element"; +} + +int main() +{ + int a[] = { 1, 3, 3, 1, 2 }; + int size = (sizeof(a)) / sizeof(a[0]); + + printMajority(a, size); + + return 0; +} diff --git a/Make A and B equal.cpp b/Make A and B equal.cpp new file mode 100644 index 0000000..dca9afc --- /dev/null +++ b/Make A and B equal.cpp @@ -0,0 +1,26 @@ +#include +#include +using namespace std; +typedef long long int ll; + +int main() { + // your code goes here + ll p; + cin>>p; + while(p--){ + ll m,a=0,b=0; + cin>>m; + vector x(m,0),y(m,0); + for(ll i=0;i>x[i]; + for(ll i=0;i>y[i]; + a+=(x[i]-y[i]); + b= b+abs(x[i]-y[i]); + } + + if(a!=0)cout<<-1< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - - bool dfs(vector& matchsticks, int target, vector&sides, int idx){ - // Base Case - if(idx == matchsticks.size()){ - if(sides[0] == sides[1] and sides[1] == sides[2] and sides[2] == sides[3]) - return true; - return false; - } - - for(int i = 0; i < 4; i++){ - if(sides[i] + matchsticks[idx] > target) //Optimization 1 - continue; - - int j = i-1; - while(j >= 0){ // Optimization 3 - if(sides[j] == sides[i]){ - break; - } - - j--; - } - - if(j != -1) - continue; - - sides[i] += matchsticks[idx]; - if(dfs(matchsticks, target, sides, idx + 1)) - return true; - sides[i] -= matchsticks[idx]; //backtrack - } - return false; - } - - bool makesquare(vector& matchsticks) { - // Edge Case - if(matchsticks.size() == 0) - return false; - - int sum = 0; - for(int i = 0; i < matchsticks.size(); i++){ - sum += matchsticks[i]; - } - - int target = sum / 4; - - vector sides(4, 0); - - sort(matchsticks.begin(), matchsticks.end(), greater()); // Optimization 2 - - return dfs(matchsticks, target, sides, 0); - } -}; - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - int n; - cin >> n; - - vector matches(n); - - loop(i, 0, n){ - cin >> matches[i]; - } - - Solution mksqr = makesquare(matches); - - if(mksqr) - cout << "TRUE"<< endl; - else - cout << "FALSE" << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<>& grid) { + int ans = 0; + n = grid.size(), m = grid[0].size(); + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (grid[i][j]) ans = max(ans, trav(i, j, grid)); + return ans; + } +private: + int n, m; + int trav(int i, int j, vector>& grid) { + if (i < 0 || j < 0 || i >= n || j >= m || !grid[i][j]) return 0; + grid[i][j] = 0; + return 1 + trav(i-1, j, grid) + trav(i, j-1, grid) + trav(i+1, j, grid) + trav(i, j+1, grid); + } +}; diff --git a/MaximumPerformanceTeam.cpp b/MaximumPerformanceTeam.cpp deleted file mode 100644 index 45866ea..0000000 --- a/MaximumPerformanceTeam.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int maxPerformance(int n, vector& speed, vector& efficiency, int k) { - vector> v; - - priority_queue, greater> pq; - - for (int i = 0; i < n; i++) { - v.push_back({efficiency[i], speed[i]}); - } - - long sum = 0, ans = 0; - - sort(v.begin(), v.end()); - - for(auto i = n-1; i >= 0; i--) { - sum += v[i].second; - pq.push(v[i].second); - if(pq.size() > k) { - sum -= pq.top(); - pq.pop(); - } - - ans = max(ans, sum*v[i].first); - } - - return ans%1000000007; - - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - -bool compare(vector v1, vector v2){ - return v1[1] > v2[1]; -} - -class Solution { -public: - int maximumUnits(vector>& boxTypes, int truckSize) { - int totalUnits = 0, i = 0; - sort(boxTypes.begin(), boxTypes.end(), compare); - - while(truckSize > 0 and i < boxTypes.size()){ - if(boxTypes[i][0] <= truckSize){ - totalUnits += boxTypes[i][0]*boxTypes[i][1]; - truckSize -= boxTypes[i][0]; - } - else{ - int canTake = truckSize; - truckSize -= canTake; - totalUnits += canTake * boxTypes[i][1]; - } - - i++; - } - return totalUnits; - } - -}; - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - // code - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<> merge(vector>& interval) { + vector> res; + if(interval.size()==0) + { + return res; + } + int n=interval.size(); + sort(interval.begin(),interval.end()); + res.push_back(interval[0]); + int j=0; + for(int i=1;i=interval[i][0]) + { + res[j][1]=max(res[j][1],interval[i][1]); + } + else + { + j++; + res.push_back(interval[i]); + } + } + return res; + } +}; diff --git a/MergeArray.java b/MergeArray.java new file mode 100644 index 0000000..bc34c7a --- /dev/null +++ b/MergeArray.java @@ -0,0 +1,34 @@ +import java.lang.*; +public class MergeArrayExample2 +{ +public static void main(String[] args) +{ +int firstArray[] = { 11,22,33,44,55,98,76,54,60}; +int secondArray[] = {66,77,88,99,22,67,21,90,80,70}; +int source_arr[], sourcePos, dest_arr[], destPos, len; +source_arr = firstArray; +dest_arr = secondArray; +sourcePos = 2; +destPos = 4; +len = 3; +// Print elements of source +System.out.print("source_array : "); +for (int i = 0; i < firstArray.length; i++) +System.out.print(firstArray[i] + " "); +System.out.println(""); +System.out.println("sourcePos : " + sourcePos); +// Print elements of destination +System.out.print("dest_array : "); +for (int i = 0; i < secondArray.length; i++) +System.out.print(secondArray[i] + " "); +System.out.println(""); +System.out.println("destPos : " + destPos); +System.out.println("len : " + len); +//invoking arraycopy() method +System.arraycopy(source_arr, sourcePos, dest_arr,destPos, len); +// Print elements of destination after +System.out.print("Resultant array : "); +for (int i = 0; i < secondArray.length; i++) +System.out.print(secondArray[i] + " "); +} +} diff --git a/kthSmallestElementBST.cpp b/MergeInterval.cpp similarity index 57% rename from kthSmallestElementBST.cpp rename to MergeInterval.cpp index d67a828..07a810b 100644 --- a/kthSmallestElementBST.cpp +++ b/MergeInterval.cpp @@ -42,59 +42,93 @@ void file_i_o(){ +/* + intervals[i][0] = start point of i'th interval + intervals[i][1] = finish point of i'th interval - // * Definition for a binary tree node. - struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(0), left(nullptr), right(nullptr) {} - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - }; - -class Solution { -private: +*/ - int res; +/* +bool isOverlap(int &minS, int &maxE, vector &intervals) { + if(minS > intervals[1] or maxE < intervals[0]) { + return false; + } + return true; +} -public: - /*void inorder(TreeNode*root, int& k) { - if(not root) return; - inorder(root -> left, k); - if(--k == 0) res = root -> val; - inorder(root -> right, k); +vector> mergeIntervals(vector> &intervals) { + // Write your code here. - } + int n = intervals.size(); - int kthSmallest(TreeNode* root, int k) { - - inorder(root, k); + vector> res; + vector vis(n, false); - return res; + for(int i = 0; i < n; i++) { + if(vis[i]) { + continue; + } + + vis[i] = true; - }*/ + int minS = intervals[i][0]; + int maxE = intervals[i][1]; + while(true) { + int cnt = 0; - int kthSmallest(TreeNode* root, int k) { - stack s = new LinkedList<>(); + for(int j = 0; j < n; j++) { + if(not vis[j] and isOverlap(minS, maxE, intervals[j])) { + vis[j] = true; + minS = min(minS, intervals[j][0]); + maxE = max(maxE, intervals[j][1]); + cnt++; + } - while(true) { - while(not root) { - s.push(root); - root = root -> left; } - root = s.pop(); - if(--k == 0) return root -> val; - root = root -> right; + if(cnt == 0) break; + + } + + vector interval = {minS, maxE}; + res.push_back(interval); + } -}; + sort(res.begin(), res.end()); + + return res; + +}*/ + + +// Optimized Approach + + +vector > mergeIntervals(vector> &intervals) { + int n = intervals.size(); + + sort(intervals.begin(),intervals.end()); + + vector > res; + + for(int i = 0; i < n; i++) { + int curS = intervals[i][0]; + int curE = intervals[i][1]; + + if(res.size() == 0 or curS > res[res.size()-1][1]) + res.push_back(intervals[i]); + else + res[res.size() - 1][1] = max(res[res.size() - 1][1], curE); + } + + return res; +} diff --git a/MergeTwoSortedLists.cpp b/MergeTwoSortedLists.cpp deleted file mode 100644 index af27900..0000000 --- a/MergeTwoSortedLists.cpp +++ /dev/null @@ -1,122 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { - ListNode *finalHead = NULL, *finalTail = NULL; - - if(list1 == NULL) return list2; - if(list2 == NULL) return list1; - - while(list1 != NULL and list2 != NULL){ - if(finalHead == NULL and finalTail == NULL){ - if(list1->val > list2->val){ - finalHead = list2; - finalTail = list2; - list2 = list2->next; - } - else{ - finalHead = list1; - finalTail = list1; - list1 = list1->next; - } - } - else{ - if(list1->val < list2->val){ - finalTail->next = list1; - finalTail = finalTail->next; - list1 = list1->next; - } - else{ - finalTail->next = list2; - finalTail = finalTail->next; - list2 = list2->next; - } - } - - } - - if(list1 != NULL){ - finalTail -> next = list1; - } - if(list2 != NULL) { - finalTail -> next = list2; - } - - return finalHead; - } -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* middleNode(ListNode* head) { - ListNode *slow = head; - ListNode *fast = head; - - while(fast != nullptr and fast->next != nullptr) { - slow = slow -> next; - fast = fast -> next -> next; - } - return slow; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< a; + for (int i = 0; i <= 30; i++) + if ((num2 >> i) & 1) + a[i] = 1; + if (g <= a.size()){ + g = a.size() - g; + for (auto &e : a){ + if (!g) + break; + --g; + ans -= (1 << e.first); + } + return ans; + } + g -= a.size(); + for (int i = 0; g > 0 and i <= 30; i++){ + if (!a[i]){ + --g; + ans += (1 << i); + } + } + return ans; + } + /* + Solution to Miniminze XOR (https://leetcode.com/contest/weekly-contest-313/problems/minimize-xor/) + */ diff --git a/Missingnumber.cpp b/Missingnumber.cpp new file mode 100644 index 0000000..45f5eee --- /dev/null +++ b/Missingnumber.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +int findMissingNo (int arr[], int len){ + int temp; + temp = ((len+1)*(len+2))/2; + for (int i = 0; i>n; + int arr[n-1]; + for(int i=0; i>arr[i]; + } + int missingNo = findMissingNo(arr,5); + cout<<"Missing Number is: "<= N: + return True + + # Consider this column and try placing + # this queen in all rows one by one + for i in range(N): + + if isSafe(board, i, col): + # Place this queen in board[i][col] + board[i][col] = 1 + + # recur to place rest of the queens + if solveNQUtil(board, col + 1) == True: + return True + + # If placing queen in board[i][col + # doesn't lead to a solution, then + # queen from board[i][col] + board[i][col] = 0 + + # if the queen can not be placed in any row in + # this column col then return false + return False + +# This function solves the N Queen problem using +# Backtracking. It mainly uses solveNQUtil() to +# solve the problem. It returns false if queens +# cannot be placed, otherwise return true and +# placement of queens in the form of 1s. +# note that there may be more than one +# solutions, this function prints one of the +# feasible solutions. +def solveNQ(): + board = [ [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0] + ] + + if solveNQUtil(board, 0) == False: + print ("Solution does not exist") + return False + + printSolution(board) + return True + +# driver program to test above function +solveNQ() + +# This code is contributed by Xplosive Potato diff --git a/N-aryTreePreorderTraversal.cpp b/N-aryTreePreorderTraversal.cpp deleted file mode 100644 index 4e91c17..0000000 --- a/N-aryTreePreorderTraversal.cpp +++ /dev/null @@ -1,111 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution { -public: - - void preorderHelper(Node* root, vector &toReturn){ - toReturn.push_back(root->_val); - for(int i = 0; i < root->_children.size(); i++){ - preorderHelper(root->_children[i], toReturn); - } - } - - vector preorder(Node* root) { - vector toReturn; - - if(root == NULL) - return toReturn; - - preorderHelper(root, toReturn); - - return toReturn; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; +#define N 8 + +void printBoard(int board[N][N]) +{ + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + cout << board[i][j] << " "; + cout << endl; + } +} + +bool isValid(int board[N][N], int row, int col) +{ + for (int i = 0; i < col; i++) // check whether there is queen in the left or not + if (board[row][i]) + return false; + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) + if (board[i][j]) // check whether there is queen in the left upper diagonal or not + return false; + for (int i = row, j = col; j >= 0 && i < N; i++, j--) + if (board[i][j]) // check whether there is queen in the left lower diagonal or not + return false; + return true; +} + +bool solveNQueen(int board[N][N], int col) +{ + if (col >= N) // when N queens are placed successfully + return true; + for (int i = 0; i < N; i++) + { // for each row, check placing of queen is possible or not + if (isValid(board, i, col)) + { + board[i][col] = 1; // if validate, place the queen at place (i, col) + if (solveNQueen(board, col + 1)) // Go for the other columns recursively + return true; + + board[i][col] = 0; // When no place is vacant remove that queen + } + } + return false; // when no possible order is found +} + +bool checkSolution() +{ + int board[N][N]; + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + board[i][j] = 0; // set all elements to 0 + + if (solveNQueen(board, 0) == false) + { // starting from 0th column + cout << "Solution does not exist"; + return false; + } + printBoard(board); + return true; +} + +int main() +{ + checkSolution(); +} diff --git a/ninjaTraining.cpp b/NQueens.cpp similarity index 64% rename from ninjaTraining.cpp rename to NQueens.cpp index 5f30772..ac0de0d 100644 --- a/ninjaTraining.cpp +++ b/NQueens.cpp @@ -43,68 +43,89 @@ void file_i_o(){ +bool notPresentCol(int col, int row, vector& board, int n) { -/*int rec(int days, int prevActivity, int n, vector> &points) { - if(days > n) { - return 0; + for(int i = 0; i < row; i++) { + int idx = i * n + col; + if(board[idx] == 1) + return false; } - int ans = 0; - for(int i = 1; i <= 3; i++) { - if(i == prevActivity) continue; - - int smallAns = points[days - 1][i - 1] + rec(days+1, i, n , points); - ans = max(ans, smallAns); - } + return true; - return ans; } -int ninjaTraining(int n, vector> &points) { - - // Activity -> 1, 2, 3 - return rec(1, 0, n, points); +bool notPresentDiag(int col, int row, vector& board, int n) { -}*/ + int i = row - 1; + int j = col - 1; -// [i][j] -> Merit points on ith day using jth activity + while(i >= 0 and j >= 0) { + int idx = i * n + j; + if(board[idx] == 1) + return false; + + i -= 1; + j -= 1; + } + i = row - 1; + j = col + 1; -int rec(int days, int prevActivity, int n, vector> &points, vector> &dp) { - if(days > n) { - return 0; + while(i >= 0 and j < n) { + int idx = i * n + j; + if(board[idx] == 1) + return false; + + i -= 1; + j += 1; } - // If ans is available + return true; - if(dp[days][prevActivity] != -1) return dp[days][prevActivity]; - int ans = 0; - for(int i = 1; i <= 3; i++) { - if(i == prevActivity) continue; - - int smallAns = points[days - 1][i - 1] + rec(days+1, i, n , points, dp); - ans = max(ans, smallAns); +} + + + + +void rec(int row, int n, vector& board, vector>& config) { + + if(row == n) { + config.push_back(board); + return; + } + + for(int col = 0; col < n; ++col) { + if(notPresentCol(col, row, board, n) and notPresentDiag(col, row, board, n)) { + int idx = row*n + col; + board[idx] = 1; + rec(row+1, n, board, config); + board[idx] = 0; + } } - return dp[days][prevActivity] = ans; } -int ninjaTraining(int n, vector> &points) { - // Activity -> 1, 2, 3 +vector> solveNQueens(int n) { + // Write your code here. + + vector board(n*n, 0); - vector> dp(n+1, vector(4, -1)); + vector> config; + rec(0, n, board, config); - return rec(1, 0, n, points, dp); + return config; + +} -} diff --git a/NarrylevelOrder.cpp b/NarrylevelOrder.cpp deleted file mode 100644 index 715d84e..0000000 --- a/NarrylevelOrder.cpp +++ /dev/null @@ -1,122 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution { - vector> ans; -public: - vector> levelOrder(Node* root) { - if(root == NULL) return {}; - - queueq; - - q.push(root); - - while(not q.empty()) { - int n = q.size(); - - vectorv; - - for(int i = 0; i < n; i++) { - Node* temp = q.front(); - - q.pop(); - - for(auto child : temp->children) { - q.push(child); - } - - v.push_back(temp -> val); - } - - ans.push_back(v); - } - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<= 0 && A[i] >= A[i + 1]) + i--; // Find 1st id i that breaks descending order + if (i >= 0) { // If not entirely descending + int j = A.length - 1; // Start from the end + while (A[j] <= A[i]) + j--; // Find rightmost first larger id j + swap(A, i, j); // Switch i and j + } + reverse(A, i + 1, A.length - 1); // Reverse the descending sequence + } + + public void swap(int[] A, int i, int j) { + int tmp = A[i]; + A[i] = A[j]; + A[j] = tmp; + } + + public void reverse(int[] A, int i, int j) { + while (i < j) + swap(A, i++, j--); + } +} diff --git a/NoOfIslands.cpp b/NoOfIslands.cpp deleted file mode 100644 index 06b1cfa..0000000 --- a/NoOfIslands.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { -public: - - bool isValid(int i, int j, int n, int m, vector> &grid) { - if(i >= 0 and i < n and j >= 0 and j < m and grid[i][j] == '1') - return true; - - return false; - } - - void numIslandsRec(int i, int j, int n, int m, vector >& grid) { - grid[i][j] = '0'; - - if(isValid(i+1, j, n, m, grid)) - numIslandsRec(i+1, j, n, m, grid); - if(isValid(i-1, j, n, m, grid)) - numIslandsRec(i-1, j, n, m, grid); - if(isValid(i, j+1, n, m, grid)) - numIslandsRec(i, j+1, n, m, grid); - if(isValid(i, j-1, n, m, grid)) - numIslandsRec(i, j-1, n, m, grid); - } - - int numIslands(vector>& grid) { - int n = grid.size(); - int m = grid[0].size(); - int as = 0; - for(int i = 0; i < n; i++){ - for(int j = 0; j < m; j++) { - if(grid[i][j] == '1') { - ans++; - numIslandsRec(i, j, n, m, grid); - } - } - } - return ans; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<>& grid) { + int ans=0; + for(int i=0;i>& grid,int i, int j){ + if(i<0||j<0||i==grid.size()||j==grid[0].size()||grid[i][j]=='0') + return; + grid[i][j]='0'; + help(grid,i+1,j); + help(grid,i,j+1); + help(grid,i-1,j); + help(grid,i,j-1); + } +}; diff --git a/Number of Pairs Satisfying Inequality.cpp b/Number of Pairs Satisfying Inequality.cpp new file mode 100644 index 0000000..04126f8 --- /dev/null +++ b/Number of Pairs Satisfying Inequality.cpp @@ -0,0 +1,73 @@ +// Problem: https://leetcode.com/contest/biweekly-contest-88/problems/number-of-pairs-satisfying-inequality/ +// Author: vrintle +// Category: LeetCode Hard + +/* + +Problem statement +----------------- + +You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that: + +0 <= i < j <= n - 1 and +nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff. +Return the number of pairs that satisfy the conditions. + +*/ + +template +class segtree { + public: + vector t; + int n; + T def; + function fx; + void build(int _n, T _def, function _fx) { + n = _n, def = _def, fx = _fx; + t.assign(n * 2, def); + for(int i = n - 1; i; i--) t[i] = fx(t[i * 2], t[i * 2 + 1]); + } + void build(vector& a, T _def, function _fx) { + n = a.size(), def = _def, fx = _fx; + t.assign(n * 2, def); + for(int i = 0; i < n; i++) t[i + n] = a[i]; + for(int i = n - 1; i; i--) t[i] = fx(t[i * 2], t[i * 2 + 1]); + } + void update(int i, T v) { + for(t[i += n] += v; i > 1; ) { + i /= 2; + t[i] = fx(t[i * 2], t[i * 2 + 1]); + } + } + // this query is made on [l, r) + T query(int l, int r) { + T lans = def, rans = def; + for(l += n, r += n; l < r; l /= 2, r /= 2) { + if(l % 2) lans = fx(lans, t[l++]); + if(r % 2) rans = fx(t[--r], rans); + } + return fx(lans, rans); + } +}; + +class Solution { +public: + long long numberOfPairs(vector& nums1, vector& nums2, int diff) { + int n = nums1.size(), N = 1e5; + vector a(n); + auto E = [&](int x) { + return x + N / 2; + }; + segtree Sum; + Sum.build(N, 0, [&](int x, int y) { + return x + y; + }); + long long ans = 0; + for(int i = 0; i < n; i++) { + a[i] = nums1[i] - nums2[i]; + ans += Sum.query(0, E(a[i] + diff) + 1); + Sum.update(E(a[i]), 1); + } + return ans; + } +}; diff --git a/NumberofMatchingSubsequences.cpp b/NumberofMatchingSubsequences.cpp deleted file mode 100644 index 8baa57a..0000000 --- a/NumberofMatchingSubsequences.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -class Solution { -public: - int numMatchingSubseq(string s, vector& words) { - vector> charIndexes(26); - for(int i = 0; i < s.size(); i++) { - charIndexes[s[i] - 'a'].push_back(i); - } - int count = 0; - - for(int i = 0; i < words.size(); i++){ - bool isSubseq = true; - int lastCharIndex = -1; - - for(char w : words[i]) { - auto it = upper_bound(charIndexes[w - 'a'].begin(), charIndexes[w - 'a'].end(), lastCharIndex); - if(it == charIndexes[w - 'a'].end()){ - isSubseq = false; - break; - } - else { - lastCharIndex = *it; - } - } - if(isSubseq) - count++; - } - - return count; - } -}; - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int nums; - - cin >> nums; - - string s; - vector words(nums); - - cin >> s; - for(int i = 0; i < words.size(); i++){ - cin >> words[i]; - } - - Solution ans; - - int result = ans.numMatchingSubseq(s, words); - - cout << result << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& data) { - int nextRbytes = 0; - - for(auto x : data) { - if(nextRbytes == 0) { - if((x >> 5) == 0b110) // number of byte 2 - nextRbytes = 1; - else if((x >> 4) == 0b1110) //number of byte 3 - nextRbytes = 2; - else if((x >> 3) == 0b11110) // number of byte 4 - nextRbytes = 3; - else if((x >> 7) != 0b0) // number of byte 1 - return false; + +bool findOverlap(string &s){ + // Write your code here. + + string a ="", b = ""; + + for(int i = 0; i < s.length()-1; i++) { + if(a.length() == 0) { + if(s[i] == 'A' and s[i+1] == 'B'){ + a = a+'A'+'B'; + i++; } + } + else{ + if(s[i] == 'B' and s[i+1] == 'A') + return true; + } + } - else { - if((x >> 6) != 0b10) return false; - nextRbytes--; + for(int i = 0; i < s.length(); i++) { + if(b.length() == 0) { + if(s[i] == 'B' and s[i+1] == 'A'){ + b = b + 'B'+'A'; + i++; } } + else { + if(s[i] == 'A' and s[i+1] == 'B') + return true; + } + } + + return false; + +} - if(nextRbytes == 0) { - return true; - } - return false; - } -}; @@ -86,6 +93,13 @@ int main(int argc, char const *argv[]) { w(t){ /* Write Code Here */ + string s; + getline(cin, s); + + bool ans = findOverlap(s); + + if(ans) cout << "true" << endl; + else cout << "false" << endl; } @@ -96,4 +110,4 @@ int main(int argc, char const *argv[]) { cerr<<"\n"<< "Coded By : S!r Black-D3vil" <<"\n"; return 0; -} +} \ No newline at end of file diff --git a/PalindromeLinkedList.cpp b/PalindromeLinkedList.cpp deleted file mode 100644 index 2effdeb..0000000 --- a/PalindromeLinkedList.cpp +++ /dev/null @@ -1,136 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - - ListNode* reverseList(ListNode* head) { - if(head == nullptr) return NULL; - - ListNode* p = nullptr, *c = head, *n = head -> next; - while(c != nullptr) { - c -> next = p; - p = c; - c = n; - if(n != nullptr) n = n -> next; - } - - return p; - } - - - void print(ListNode* head) { - while(head) { - cout << head -> val << " "; - head = head -> next; - } - cout << endl; - } - - - bool isPalindrome(ListNode* head) { - ListNode* slow = head; - ListNode*fast = head; - - while(fast -> next != NULL and fast -> next -> next != NULL) { - slow = slow -> next; - fast = fast -> next -> next; - } - - slow -> next = reverseList(slow -> next); - ListNode* start = head, *mid = slow -> next; - - while(mid != nullptr) { - if(mid -> val != start -> val) return false; - - start = start -> next; - mid = mid -> next; - } - - print(head); - slow -> next = reverseList(slow -> next); - print(head); - - return true; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - bool subsetSum(int n, int k, vector& nums) { - - vector prev(k+1, 0), cur(k+1, 0); - - prev[0] = cur[0] = true; - - if(nums[0] <= k) prev[nums[0]] = true; - - for(int ind = 1; ind < n; ind++) { - for(int target = 1; target <= k; target++) { - bool notTake = prev[target]; - bool take = false; - if(nums[ind] <= target) take = prev[target - nums[ind]]; - cur[target] = take | notTake; - } - prev = cur; - } - - return prev[k]; - } - - bool canPartition(vector& nums) { - int totsum = 0; - - for(int i = 0; i < nums.size(); i++) - totsum += nums[i]; - - - if(totsum % 2) return false; - - int target = totsum / 2; - - return subsetSum(nums.size(), target, nums); - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* partition(ListNode* head, int x) { - if(head == nullptr){ - return NULL; - } - ListNode* smallerEle = new ListNode(-1); - ListNode* greaterEle = new ListNode(-1); - smallerEle -> next = head; - greaterEle -> next = head; - - ListNode* smallerEleHead = smallerEle; - ListNode* greaterEleHead = greaterEle; - - while(head != nullptr) { - if(head->val < x) { - smallerEle -> next = head; - smallerEle = smallerEle -> next; - } - else { - greaterEle -> next = head; - greaterEle = greaterEle->next; - } - head = head -> next; - } - - greaterEle -> next = nullptr; - smallerEle -> next = greaterEleHead -> next; - - return smallerEleHead->next; - } -}; - - - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + +// A utility function that returns true if there is +// a subset of arr[] with sum equal to given sum +bool isSubsetSum(int arr[], int n, int sum) +{ + // Base Cases + if (sum == 0) + return true; + if (n == 0 && sum != 0) + return false; + + // If last element is greater than sum, then + // ignore it + if (arr[n - 1] > sum) + return isSubsetSum(arr, n - 1, sum); + + /* else, check if sum can be obtained by any of + the following + (a) including the last element + (b) excluding the last element + */ + return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); +} + +// Returns true if arr[] can be partitioned in two +// subsets of equal sum, otherwise false +bool findPartiion(int arr[], int n) +{ + // Calculate sum of the elements in array + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; + + // If sum is odd, there cannot be two subsets + // with equal sum + if (sum % 2 != 0) + return false; + + // Find if there is subset with sum equal to + // half of total sum + return isSubsetSum(arr, n, sum / 2); +} +int main() +{ + int arr[] = {3, 1, 5, 9, 12}; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function call + if (findPartiion(arr, n) == true) + cout << "Can be divided into two subsets " + "of equal sum"; + else + cout << "Can not be divided into two subsets" + " of equal sum"; + return 0; +} diff --git a/Pascal.cpp b/Pascal.cpp new file mode 100644 index 0000000..cf155e6 --- /dev/null +++ b/Pascal.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; +const int N=42; +int main() +{ + int t; + cin>>t; + + long long int a[N][N]; + a[0][0] = 1; + + for(int i = 1 ; i < N; i++) + { + a[i][0] = 1; + a[i][i] = 1; + + for(int j=1; j>n; + + for(int i=0; i -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { - public: - - int ans = 0; - void helper(TreeNode* root, int sum, unordered_map&ma, long long temp = 0ll) { - - if(root == nullptr) return; - - temp += 1ll*root -> val; - - ma[temp]++; - - if(ma.find(temp - sum) != ma.end()) { - ans += ma[temp - sum]; - if(sum == 0) ans--; - } - - helper(root -> left, sum, ma, temp); - helper(root -> right, sum, ma, temp); - - ma[temp]--; - - if(ma[temp] == 0) ma.erase(temp); - temp = root -> val; - - } - - int pathSum(TreeNode* root, int targetSum) { - if(root == nullptr) return 0; - - unordered_mapma; - - ma[0]++; - - helper(root, targetSum, ma); - - return ans; - } - -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace std; + +void gotoxy(int x, int y) +{ + COORD c = { x, y }; + SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c); +} + + +class LINES +{ +public: + void LINE_HOR(int, int, int, char); + void LINE_VER(int, int, int, char); + void BOX(int, int, int, int, char); + void CLEARUP(void); + void CLEARDOWN(void); +}; + + + +class MENU +{ +public: + void MAIN_MENU(void); +private: + void EDIT_MENU(void); + void INTRODUCTION(void); +}; + + + +class EMPLOYEE +{ +public: + void NEW_EMPLOYEE(void); + void MODIFICATION(void); + void DELETION(void); + void DISPLAY(void); + void LIST(void); + void SALARY_SLIP(void); +private: + void ADD_RECORD(int, char[], char[], char[], int, int, int, char[], char, char, char, float, float); + void MODIFY_RECORD(int, char[], char[], char[], char[], char, char, char, float, float); + void DELETE_RECORD(int); + int LASTCODE(void); + int CODEFOUND(int); + int RECORDNO(int); + int FOUND_CODE(int); + void DISPLAY_RECORD(int); + int VALID_DATE(int, int, int); + + int code, dd, mm, yy; + char name[26], address[31], phone[10], desig[16]; + char grade, house, convense; + float loan, basic; +}; + + + +void MENU::MAIN_MENU(void) +{ + char ch; + LINES L; + L.CLEARUP(); + while (1) + { + system("cls"); + gotoxy(14, 3); + cout << " C++ Project for Payroll Management System"; + L.BOX(25, 7, 57, 9, 218); + L.BOX(10, 5, 71, 21, 218); + L.BOX(11, 6, 70, 20, 219); + gotoxy(29, 8); + cout << "PAYROLL MANAGEMENT SYSTEM"; + gotoxy(30, 11); + cout << "1: NEW EMPLOYEE"; + gotoxy(30, 12); + cout << "2: DISPLAY EMPLOYEE"; + gotoxy(30, 13); + cout << "3: LIST OF EMPLOYEES"; + gotoxy(30, 14); + cout << "4: SALARY SLIP"; + gotoxy(30, 15); + cout << "5: EDIT"; + gotoxy(30, 16); + cout << "0: QUIT"; + gotoxy(30, 18); + cout << "ENTER YOUR CHOICE :"; + gotoxy(5, 23); + + ch = _getch(); + if (ch == 27 || ch == '0') + break; + else if (ch == '1') + { + EMPLOYEE E; + E.NEW_EMPLOYEE(); + } + else if (ch == '2') + { + EMPLOYEE E; + E.DISPLAY(); + } + else if (ch == '3') + { + EMPLOYEE E; + E.LIST(); + } + else if (ch == '4') + { + EMPLOYEE E; + E.SALARY_SLIP(); + } + else if (ch == '5') + EDIT_MENU(); + } + L.CLEARUP(); +} + + + +void MENU::EDIT_MENU(void) +{ + char ch; + LINES L; + L.CLEARDOWN(); + while (1) + { + system("cls"); + L.BOX(28, 8, 49, 10, 218); + L.BOX(10, 5, 71, 21, 218); + L.BOX(11, 6, 70, 20, 219); + gotoxy(31, 9); + cout << "E D I T M E N U"; + gotoxy(30, 13); + cout << "1: DELETE RECORD"; + gotoxy(30, 14); + cout << "2: MODIFY RECORD"; + gotoxy(30, 15); + cout << "0: EXIT"; + gotoxy(30, 17); + cout << "ENTER YOUR CHOICE :"; + ch = _getch(); + if (ch == 27 || ch == '0') + break; + else if (ch == '1') + { + EMPLOYEE E; + E.DELETION(); + } + else if (ch == '2') + { + EMPLOYEE E; + E.MODIFICATION(); + } + } + L.CLEARDOWN(); +} + + +void LINES::LINE_HOR(int column1, int column2, int row, char c) +{ + for (column1; column1 <= column2; column1++) + { + gotoxy(column1, row); + cout << c; + } +} + + + +void LINES::LINE_VER(int row1, int row2, int column, char c) +{ + for (row1; row1 <= row2; row1++) + { + gotoxy(column, row1); + cout << c; + } +} + + + +void LINES::BOX(int column1, int row1, int column2, int row2, char c) +{ + char ch = 218; + char c1, c2, c3, c4; + char l1 = 196, l2 = 179; + if (c == ch) + { + c1 = 218; + c2 = 191; + c3 = 192; + c4 = 217; + l1 = 196; + l2 = 179; + } + else + { + c1 = c; + c2 = c; + c3 = c; + c4 = c; + l1 = c; + l2 = c; + } + gotoxy(column1, row1); + cout << c1; + gotoxy(column2, row1); + cout << c2; + gotoxy(column1, row2); + cout << c3; + gotoxy(column2, row2); + cout << c4; + column1++; + column2--; + LINE_HOR(column1, column2, row1, l1); + LINE_HOR(column1, column2, row2, l1); + column1--; + column2++; + row1++; + row2--; + LINE_VER(row1, row2, column1, l2); + LINE_VER(row1, row2, column2, l2); +} + + +//********************************************************** +// THIS FUNCTION CLEAR THE SCREEN LINE BY LINE UPWARD +//********************************************************** + +void LINES::CLEARUP(void) +{ + for (int i = 25; i >= 1; i--) + { + sleep(20); + gotoxy(1, i); + clreol(); + } +} + + + +void LINES::CLEARDOWN(void) +{ + for (int i = 1; i <= 25; i++) + { + delay(20); + gotoxy(1, i); + clreol(); + } +} + + +//********************************************************** +// THIS FUNCTION ADDS THE GIVEN DATA IN THE EMPLOYEE'S FILE +//********************************************************** + +void EMPLOYEE::ADD_RECORD(int ecode, char ename[26], char eaddress[31], char ephone[10], int d, int m, int y, char edesig[16], char egrade, char ehouse, char econv, float eloan, float ebasic) +{ + fstream file; + file.open("EMPLOYEE.DAT"); + code = ecode; + strcpy(name, ename); + strcpy(address, eaddress); + strcpy(phone, ephone); + dd = d; + mm = m; + yy = y; + strcpy(desig, edesig); + grade = egrade; + house = ehouse; + convense = econv; + loan = eloan; + basic = ebasic; + file.write((char *) this, sizeof(EMPLOYEE)); + file.close(); +} + + +//********************************************************** +// THIS FUNCTION MODIFY THE GIVEN DATA IN THE +// EMPLOYEE'S FILE +//********************************************************** + +void EMPLOYEE::MODIFY_RECORD(int ecode, char ename[26], char eaddress[31], char ephone[10], char edesig[16], char egrade, char ehouse, char econv, float eloan, float ebasic) +{ + int recno; + recno = RECORDNO(ecode); + fstream file; + file.open("EMPLOYEE.DAT", ios::out | ios::ate); + strcpy(name, ename); + strcpy(address, eaddress); + strcpy(phone, ephone); + strcpy(desig, edesig); + grade = egrade; + house = ehouse; + convense = econv; + loan = eloan; + basic = ebasic; + int location; + location = (recno - 1) * sizeof(EMPLOYEE); + file.seekp(location); + file.write((char *) this, sizeof(EMPLOYEE)); + file.close(); +} + + +//********************************************************** +// THIS FUNCTION DELETE THE RECORD IN THE EMPLOYEE FILE +// FOR THE GIVEN EMPLOYEE CODE +//********************************************************** + +void EMPLOYEE::DELETE_RECORD(int ecode) +{ + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + fstream temp; + temp.open("temp.dat", ios::out); + file.seekg(0, ios::beg); + while (!file.eof()) + { + file.read((char *) this, sizeof(EMPLOYEE)); + if (file.eof()) + break; + if (code != ecode) + temp.write((char *) this, sizeof(EMPLOYEE)); + } + file.close(); + temp.close(); + file.open("EMPLOYEE.DAT", ios::out); + temp.open("temp.dat", ios::in); + temp.seekg(0, ios::beg); + while (!temp.eof()) + { + temp.read((char *) this, sizeof(EMPLOYEE)); + if (temp.eof()) + break; + file.write((char *) this, sizeof(EMPLOYEE)); + } + file.close(); + temp.close(); +} + + +//********************************************************** +// THIS FUNCTION RETURNS THE LAST EMPLOYEE'S CODE +//********************************************************** + +int EMPLOYEE::LASTCODE(void) +{ + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + file.seekg(0, ios::beg); + int count = 0; + while (file.read((char *) this, sizeof(EMPLOYEE))) + count = code; + file.close(); + return count; +} + + +//********************************************************** +// THIS FUNCTION RETURNS 0 IF THE GIVEN CODE NOT FOUND +//********************************************************** + +int EMPLOYEE::FOUND_CODE(int ecode) +{ + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + file.seekg(0, ios::beg); + int found = 0; + while (file.read((char *) this, sizeof(EMPLOYEE))) + { + if (code == ecode) + { + found = 1; + break; + } + } + file.close(); + return found; +} + + +//********************************************************** +// THIS FUNCTION RETURNS RECORD NO. OF THE GIVEN CODE +//********************************************************** + +int EMPLOYEE::RECORDNO(int ecode) +{ + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + file.seekg(0, ios::beg); + int recno = 0; + while (file.read((char *) this, sizeof(EMPLOYEE))) + { + recno++; + if (code == ecode) + break; + } + file.close(); + return recno; +} + + +//********************************************************** +// THIS FUNCTION DISPLAYS THE LIST OF THE EMPLOYEES +//********************************************************** + +void EMPLOYEE::LIST(void) +{ + system("cls"); + int row = 6, found = 0, flag = 0; + char ch; + gotoxy(31, 2); + cout << "LIST OF EMPLOYEES"; + gotoxy(30, 3); + cout << "~~~~~~~~~~~~~~~~~~~"; + gotoxy(1, 4); + cout << "CODE NAME PHONE DOJ DESIGNATION GRADE SALARY"; + gotoxy(1, 5); + cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + file.seekg(0, ios::beg); + while (file.read((char *) this, sizeof(EMPLOYEE))) + { + flag = 0; + delay(20); + found = 1; + gotoxy(2, row); + cout << code; + gotoxy(6, row); + cout << name; + gotoxy(31, row); + cout << phone; + gotoxy(40, row); + cout << dd << "/" << mm << "/" << yy; + gotoxy(52, row); + cout << desig; + gotoxy(69, row); + cout << grade; + if (grade != 'E') + { + gotoxy(74, row); + cout << basic; + } + else + { + gotoxy(76, row); + cout << "-"; + } + if (row == 23) + { + flag = 1; + row = 6; + gotoxy(1, 25); + cout << "Press any key to continue or Press to exit"; + ch = getch(); + if (ch == 27) + break; + system("cls"); + gotoxy(31, 2); + cout << "LIST OF EMPLOYEES"; + gotoxy(30, 3); + cout << "~~~~~~~~~~~~~~~~~~~"; + gotoxy(1, 4); + cout << "CODE NAME PHONE DOJ DESIGNATION GRADE SALARY"; + gotoxy(1, 5); + cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; + } + else + row++; + } + if (!found) + { + gotoxy(5, 10); + cout << "\7Records not found"; + } + if (!flag) + { + gotoxy(1, 25); + cout << "Press any key to continue..."; + getche(); + } + file.close(); +} + + +//********************************************************** +// THIS FUNCTION DISPLAYS THE RECORD OF THE EMPLOYEES +//********************************************************** + +void EMPLOYEE::DISPLAY_RECORD(int ecode) +{ + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + file.seekg(0, ios::beg); + while (file.read((char *) this, sizeof(EMPLOYEE))) + { + if (code == ecode) + { + gotoxy(5, 5); + cout << "Employee Code # " << code; + gotoxy(5, 6); + cout << "~~~~~~~~~~~~~"; + gotoxy(5, 7); + cout << "Name : " << name; + gotoxy(5, 8); + cout << "Address : " << address; + gotoxy(5, 9); + cout << "Phone no. : " << phone; + gotoxy(5, 11); + cout << "JOINING DATE"; + gotoxy(5, 12); + cout << "~~~~~~~~~~~~"; + gotoxy(5, 13); + cout << "Day : " << dd; + gotoxy(5, 14); + cout << "Month : " << mm; + gotoxy(5, 15); + cout << "Year : " << yy; + gotoxy(5, 17); + cout << "Designation : " << desig; + gotoxy(5, 18); + cout << "Grade : " << grade; + if (grade != 'E') + { + gotoxy(5, 19); + cout << "House (y/n) : " << house; + gotoxy(5, 20); + cout << "Convense (y/n) : " << convense; + gotoxy(5, 22); + cout << "Basic Salary : " << basic; + } + gotoxy(5, 21); + cout << "Loan : " << loan; + } + } + file.close(); +} + + +//********************************************************** +// THIS FUNCTION GIVE DATA TO ADD IN THE FILE +//********************************************************** + +void EMPLOYEE::NEW_EMPLOYEE(void) +{ + system("cls"); + char ch, egrade, ehouse = 'N', econv = 'N'; + char ename[26], eaddress[31], ephone[10], edesig[16], t1[10]; + float t2 = 0.0, eloan = 0.0, ebasic = 0.0; + int d, m, y, ecode, valid; + gotoxy(72, 2); + cout << "<0>=EXIT"; + gotoxy(28, 3); + cout << "ADDITION OF NEW EMPLOYEE"; + gotoxy(5, 5); + cout << "Employee Code # "; + gotoxy(5, 6); + cout << "~~~~~~~~~~~~~"; + gotoxy(5, 7); + cout << "Name : "; + gotoxy(5, 8); + cout << "Address : "; + gotoxy(5, 9); + cout << "Phone no. : "; + gotoxy(5, 11); + cout << "JOINING DATE"; + gotoxy(5, 12); + cout << "~~~~~~~~~~~~"; + gotoxy(5, 13); + cout << "Day : "; + gotoxy(5, 14); + cout << "Month : "; + gotoxy(5, 15); + cout << "Year : "; + gotoxy(5, 17); + cout << "Designation : "; + gotoxy(5, 18); + cout << "Grade : "; + gotoxy(5, 21); + cout << "Loan : "; + + ecode = LASTCODE() + 1; + if (ecode == 1) + { + ADD_RECORD(ecode, "null", "null", "null", 0, 0, 0, "null", 'n', 'n', 'n', 0.0, 0.0); + DELETE_RECORD(ecode); + } + gotoxy(21, 5); + cout << ecode; + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter the name of the Employee"; + gotoxy(20, 7); + clreol(); + gets(ename); + strupr(ename); + if (ename[0] == '0') + return; + if (strlen(ename) < 1 || strlen(ename) > 25) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly (Range: 1..25)"; + getch(); + } + } while (!valid); + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter Address of the Employee"; + gotoxy(20, 8); + clreol(); + gets(eaddress); + strupr(eaddress); + if (eaddress[0] == '0') + return; + if (strlen(eaddress) < 1 || strlen(eaddress) > 30) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly (Range: 1..30)"; + getch(); + } + } while (!valid); + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter Phone no. of the Employee or Press for none"; + gotoxy(20, 9); + clreol(); + gets(ephone); + if (ephone[0] == '0') + return; + if ((strlen(ephone) < 7 && strlen(ephone) > 0) || (strlen(ephone) > 9)) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly"; + getch(); + } + } while (!valid); + if (strlen(ephone) == 0) + strcpy(ephone, "-"); + char tday[3], tmonth[3], tyear[5]; + int td; + do + { + valid = 1; + do + { + gotoxy(5, 25); + clreol(); + cout << "ENTER DAY OF JOINING"; + gotoxy(13, 13); + clreol(); + gets(tday); + td = atoi(tday); + d = td; + if (tday[0] == '0') + return; + } while (d == 0); + do + { + gotoxy(5, 25); + clreol(); + cout << "ENTER MONTH OF JOINING"; + gotoxy(13, 14); + clreol(); + gets(tmonth); + td = atoi(tmonth); + m = td; + if (tmonth[0] == '0') + return; + } while (m == 0); + do + { + gotoxy(5, 25); + clreol(); + cout << "ENTER YEAR OF JOINING"; + gotoxy(13, 15); + clreol(); + gets(tyear); + td = atoi(tyear); + y = td; + if (tyear[0] == '0') + return; + } while (y == 0); + if (d>31 || d<1) + valid = 0; + else if (((y % 4) != 0 && m == 2 && d>28) || ((y % 4) == 0 && m == 2 && d>29)) + valid = 0; + else if ((m == 4 || m == 6 || m == 9 || m == 11) && d>30) + valid = 0; + else if (y<1990 || y>2020) + valid = 0; + if (!valid) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly"; + getch(); + gotoxy(13, 14); + clreol(); + gotoxy(13, 15); + clreol(); + } + } while (!valid); + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter Designation of the Employee"; + gotoxy(20, 17); + clreol(); + gets(edesig); + strupr(edesig); + if (edesig[0] == '0') + return; + if (strlen(edesig) < 1 || strlen(edesig) > 15) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly (Range: 1..15)"; + getch(); + } + } while (!valid); + do + { + gotoxy(5, 25); + clreol(); + cout << "Enter Grade of the Employee (A,B,C,D,E)"; + gotoxy(20, 18); + clreol(); + egrade = getche(); + egrade = toupper(egrade); + if (egrade == '0') + return; + } while (egrade < 'A' || egrade > 'E'); + if (egrade != 'E') + { + gotoxy(5, 19); + cout << "House (y/n) : "; + gotoxy(5, 20); + cout << "Convense (y/n) : "; + gotoxy(5, 22); + cout << "Basic Salary : "; + do + { + gotoxy(5, 25); + clreol(); + cout << "ENTER IF HOUSE ALLOWANCE IS ALLOTED TO EMPLOYEE OR NOT"; + gotoxy(22, 19); + clreol(); + ehouse = getche(); + ehouse = toupper(ehouse); + if (ehouse == '0') + return; + } while (ehouse != 'Y' && ehouse != 'N'); + do + { + gotoxy(5, 25); + clreol(); + cout << "ENTER IF CONVENCE ALLOWANCE IS ALLOTED TO EMPLOYEE OR NOT"; + gotoxy(22, 20); + clreol(); + econv = getche(); + econv = toupper(econv); + if (econv == '0') + return; + } while (econv != 'Y' && econv != 'N'); + } + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "ENTER LOAN AMOUNT IF ISSUED"; + gotoxy(22, 21); + clreol(); + gets(t1); + t2 = atof(t1); + eloan = t2; + if (eloan > 50000) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7SHOULD NOT GREATER THAN 50000"; + getch(); + } + } while (!valid); + if (egrade != 'E') + { + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "ENTER BASIC SALARY OF THE EMPLOYEE"; + gotoxy(22, 22); + clreol(); + gets(t1); + t2 = atof(t1); + ebasic = t2; + if (t1[0] == '0') + return; + if (ebasic > 50000) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7SHOULD NOT GREATER THAN 50000"; + getch(); + } + } while (!valid); + } + gotoxy(5, 25); + clreol(); + do + { + gotoxy(5, 24); + clreol(); + cout << "Do you want to save (y/n) "; + ch = getche(); + ch = toupper(ch); + if (ch == '0') + return; + } while (ch != 'Y' && ch != 'N'); + if (ch == 'N') + return; + ADD_RECORD(ecode, ename, eaddress, ephone, d, m, y, edesig, egrade, ehouse, econv, eloan, ebasic); +} + + +//********************************************************** +// THIS FUNCTION GIVE CODE FOR THE DISPLAY OF THE RECORD +//********************************************************** + +void EMPLOYEE::DISPLAY(void) +{ + system("cls"); + char t1[10]; + int t2, ecode; + gotoxy(72, 2); + cout << "<0>=EXIT"; + gotoxy(5, 5); + cout << "Enter code of the Employee "; + gets(t1); + t2 = atoi(t1); + ecode = t2; + if (ecode == 0) + return; + system("cls"); + if (!FOUND_CODE(ecode)) + { + gotoxy(5, 5); + cout << "\7Record not found"; + getch(); + return; + } + DISPLAY_RECORD(ecode); + gotoxy(5, 25); + cout << "Press any key to continue..."; + getch(); +} + + +//********************************************************** +// THIS FUNCTION GIVE DATA FOR THE MODIFICATION OF THE +// EMPLOYEE RECORD +//********************************************************** + +void EMPLOYEE::MODIFICATION(void) +{ + system("cls"); + char ch, egrade, ehouse = 'N', econv = 'N'; + char ename[26], eaddress[31], ephone[10], edesig[16], t1[10]; + float t2 = 0.0, eloan = 0.0, ebasic = 0.0; + int ecode, valid; + gotoxy(72, 2); + cout << "<0>=EXIT"; + gotoxy(5, 5); + cout << "Enter code of the Employee "; + gets(t1); + t2 = atoi(t1); + ecode = t2; + if (ecode == 0) + return; + system("cls"); + if (!FOUND_CODE(ecode)) + { + gotoxy(5, 5); + cout << "\7Record not found"; + getch(); + return; + } + gotoxy(72, 2); + cout << "<0>=EXIT"; + gotoxy(22, 3); + cout << "MODIFICATION OF THE EMPLOYEE RECORD"; + DISPLAY_RECORD(ecode); + do + { + gotoxy(5, 24); + clreol(); + cout << "Do you want to modify this record (y/n) "; + ch = getche(); + ch = toupper(ch); + if (ch == '0') + return; + } while (ch != 'Y' && ch != 'N'); + if (ch == 'N') + return; + system("cls"); + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + file.seekg(0, ios::beg); + while (file.read((char *) this, sizeof(EMPLOYEE))) + { + if (code == ecode) + break; + } + file.close(); + gotoxy(5, 5); + cout << "Employee Code # " << ecode; + gotoxy(5, 6); + cout << "~~~~~~~~~~~~~"; + gotoxy(40, 5); + cout << "JOINING DATE : "; + gotoxy(40, 6); + cout << "~~~~~~~~~~~~~~"; + gotoxy(55, 5); + cout << dd << "/" << mm << "/" << yy; + gotoxy(5, 7); + cout << "Name : "; + gotoxy(5, 8); + cout << "Address : "; + gotoxy(5, 9); + cout << "Phone no. : "; + gotoxy(5, 10); + cout << "Designation : "; + gotoxy(5, 11); + cout << "Grade : "; + gotoxy(5, 14); + cout << "Loan : "; + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter the name of the Employee or FOR NO CHANGE"; + gotoxy(20, 7); + clreol(); + gets(ename); + strupr(ename); + if (ename[0] == '0') + return; + if (strlen(ename) > 25) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly (Range: 1..25)"; + getch(); + } + } while (!valid); + if (strlen(ename) == 0) + { + strcpy(ename, name); + gotoxy(20, 7); + cout << ename; + } + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter Address of the Employee or FOR NO CHANGE"; + gotoxy(20, 8); + clreol(); + gets(eaddress); + strupr(eaddress); + if (eaddress[0] == '0') + return; + if (strlen(eaddress) > 30) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly (Range: 1..30)"; + getch(); + } + } while (!valid); + if (strlen(eaddress) == 0) + { + strcpy(eaddress, address); + gotoxy(20, 8); + cout << eaddress; + } + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter Phone no. of the Employee or or FOR NO CHANGE"; + gotoxy(20, 9); + clreol(); + gets(ephone); + if (ephone[0] == '0') + return; + if ((strlen(ephone) < 7 && strlen(ephone) > 0) || (strlen(ephone) > 9)) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly"; + getch(); + } + } while (!valid); + if (strlen(ephone) == 0) + { + strcpy(ephone, phone); + gotoxy(20, 9); + cout << ephone; + } + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "Enter Designation of the Employee or FOR NO CHANGE"; + gotoxy(20, 10); + clreol(); + gets(edesig); + strupr(edesig); + if (edesig[0] == '0') + return; + if (strlen(edesig) > 15) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7Enter correctly (Range: 1..15)"; + getch(); + } + } while (!valid); + if (strlen(edesig) == 0) + { + strcpy(edesig, desig); + gotoxy(20, 10); + cout << edesig; + } + do + { + gotoxy(5, 25); + clreol(); + cout << "Enter Grade of the Employee (A,B,C,D,E) or FOR NO CHANGE"; + gotoxy(20, 11); + clreol(); + egrade = getche(); + egrade = toupper(egrade); + if (egrade == '0') + return; + if (egrade == 13) + { + egrade = grade; + gotoxy(20, 11); + cout << grade; + } + } while (egrade < 'A' || egrade > 'E'); + if (egrade != 'E') + { + gotoxy(5, 12); + cout << "House (y/n) : "; + gotoxy(5, 13); + cout << "Convense (y/n) : "; + gotoxy(5, 15); + cout << "Basic Salary : "; + do + { + gotoxy(5, 25); + clreol(); + cout << "ALLOTED HOUSE ALLOWANCE ? or FOR NO CHANGE"; + gotoxy(22, 12); + clreol(); + ehouse = getche(); + ehouse = toupper(ehouse); + if (ehouse == '0') + return; + if (ehouse == 13) + { + ehouse = house; + gotoxy(22, 12); + cout << ehouse; + } + } while (ehouse != 'Y' && ehouse != 'N'); + do + { + gotoxy(5, 25); + clreol(); + cout << "ALLOTED CONVENCE ALLOWANCE or FOR NO CHANGE"; + gotoxy(22, 13); + clreol(); + econv = getche(); + econv = toupper(econv); + if (econv == '0') + return; + if (econv == 13) + { + econv = convense; + gotoxy(22, 13); + cout << econv; + } + } while (econv != 'Y' && econv != 'N'); + } + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "ENTER LOAN AMOUNT or FOR NO CHANGE"; + gotoxy(22, 14); + clreol(); + gets(t1); + t2 = atof(t1); + eloan = t2; + if (eloan > 50000) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7SHOULD NOT GREATER THAN 50000"; + getch(); + } + } while (!valid); + if (strlen(t1) == 0) + { + eloan = loan; + gotoxy(22, 14); + cout << eloan; + } + if (egrade != 'E') + { + do + { + valid = 1; + gotoxy(5, 25); + clreol(); + cout << "ENTER BASIC SALARY or FOR NO CHANGE"; + gotoxy(22, 15); + clreol(); + gets(t1); + t2 = atof(t1); + ebasic = t2; + if (t1[0] == '0') + return; + if (ebasic > 50000) + { + valid = 0; + gotoxy(5, 25); + clreol(); + cout << "\7SHOULD NOT GREATER THAN 50000"; + getch(); + } + } while (!valid); + if (strlen(t1) == 0) + { + ebasic = basic; + gotoxy(22, 15); + cout << ebasic; + } + } + gotoxy(5, 25); + clreol(); + do + { + gotoxy(5, 18); + clreol(); + cout << "Do you want to save (y/n) "; + ch = getche(); + ch = toupper(ch); + if (ch == '0') + return; + } while (ch != 'Y' && ch != 'N'); + if (ch == 'N') + return; + MODIFY_RECORD(ecode, ename, eaddress, ephone, edesig, egrade, ehouse, econv, eloan, ebasic); + gotoxy(5, 23); + cout << "\7Record Modified"; + gotoxy(5, 25); + cout << "Press any key to continue..."; + getch(); +} + + +//********************************************************** +// THIS FUNCTION GIVE CODE NO. FOR THE DELETION OF THE +// EMPLOYEE RECORD +//********************************************************** + +void EMPLOYEE::DELETION(void) +{ + system("cls"); + char t1[10], ch; + int t2, ecode; + gotoxy(72, 2); + cout << "<0>=EXIT"; + gotoxy(5, 5); + cout << "Enter code of the Employee "; + gets(t1); + t2 = atoi(t1); + ecode = t2; + if (ecode == 0) + return; + system("cls"); + if (!FOUND_CODE(ecode)) + { + gotoxy(5, 5); + cout << "\7Record not found"; + getch(); + return; + } + gotoxy(72, 2); + cout << "<0>=EXIT"; + gotoxy(24, 3); + cout << "DELETION OF THE EMPLOYEE RECORD"; + DISPLAY_RECORD(ecode); + do + { + gotoxy(5, 24); + clreol(); + cout << "Do you want to delete this record (y/n) "; + ch = getche(); + ch = toupper(ch); + if (ch == '0') + return; + } while (ch != 'Y' && ch != 'N'); + if (ch == 'N') + return; + DELETE_RECORD(ecode); + LINES L; + L.CLEARDOWN(); + gotoxy(5, 23); + cout << "\7Record Deleted"; + gotoxy(5, 25); + cout << "Press any key to continue..."; + getch(); +} + + +//********************************************************** +// THIS FUNCTION RETURN 0 IF THE GIVEN DATE IS INVALID +//********************************************************** + +int EMPLOYEE::VALID_DATE(int d1, int m1, int y1) +{ + int valid = 1; + if (d1>31 || d1<1) + valid = 0; + else if (((y1 % 4) != 0 && m1 == 2 && d1>28) || ((y1 % 4) == 0 && m1 == 2 && d1>29)) + valid = 0; + else if ((m1 == 4 || m1 == 6 || m1 == 9 || m1 == 11) && d1>30) + valid = 0; + return valid; +} + + +//********************************************************** +// THIS FUNCTION PRINTS THE SALARY SLIP FOR THE EMPLOYEE +//********************************************************** + +void EMPLOYEE::SALARY_SLIP(void) +{ + system("cls"); + char t1[10]; + int t2, ecode, valid; + gotoxy(72, 2); + cout << "<0>=EXIT"; + gotoxy(5, 5); + cout << "Enter code of the Employee "; + gets(t1); + t2 = atoi(t1); + ecode = t2; + if (ecode == 0) + return; + system("cls"); + if (!FOUND_CODE(ecode)) + { + gotoxy(5, 5); + cout << "\7Record not found"; + getch(); + return; + } + fstream file; + file.open("EMPLOYEE.DAT", ios::in); + file.seekg(0, ios::beg); + while (file.read((char *) this, sizeof(EMPLOYEE))) + { + if (code == ecode) + break; + } + file.close(); + int d1, m1, y1; + struct date d; + getdate(&d); + d1 = d.da_day; + m1 = d.da_mon; + y1 = d.da_year; + char *mon[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "November", "December" }; + LINES L; + L.BOX(2, 1, 79, 25, 219); + gotoxy(31, 2); + cout << "NADEEM AKHTAR, PGDBA - 200754667"; + L.LINE_HOR(3, 78, 3, 196); + gotoxy(34, 4); + cout << "SALARY SLIP"; + gotoxy(60, 4); + cout << "Date: " << d1 << "/" << m1 << "/" << y1; + gotoxy(34, 5); + cout << mon[m1 - 1] << ", " << y1; + L.LINE_HOR(3, 78, 6, 196); + gotoxy(6, 7); + cout << "Employee Name : " << name; + gotoxy(6, 8); + cout << "Designation : " << desig; + gotoxy(67, 8); + cout << "Grade : " << grade; + L.BOX(6, 9, 75, 22, 218); + L.LINE_HOR(10, 71, 20, 196); + int days, hours; + if (grade == 'E') + { + do + { + valid = 1; + gotoxy(10, 21); + cout << "ENTER NO. OF DAYS WORKED IN THE MONTH "; + gotoxy(10, 11); + cout << "No. of Days : "; + gets(t1); + t2 = atof(t1); + days = t2; + if (!VALID_DATE(days, m1, y1)) + { + valid = 0; + gotoxy(10, 21); + cout << "\7ENTER CORRECTLY "; + getch(); + gotoxy(10, 11); + cout << " "; + } + } while (!valid); + do + { + valid = 1; + gotoxy(10, 21); + cout << "ENTER NO. OF HOURS WORKED OVER TIME "; + gotoxy(10, 13); + cout << "No. of hours : "; + gets(t1); + t2 = atof(t1); + hours = t2; + if (hours > 8 || hours < 0) + { + valid = 0; + gotoxy(10, 21); + cout << "\7ENTER CORRECTLY "; + getch(); + gotoxy(10, 13); + cout << " "; + } + } while (!valid); + gotoxy(10, 21); + cout << " "; + gotoxy(10, 11); + cout << " "; + gotoxy(10, 13); + cout << " "; + } + gotoxy(10, 10); + cout << "Basic Salary : Rs."; + gotoxy(10, 12); + cout << "ALLOWANCE"; + if (grade != 'E') + { + gotoxy(12, 13); + cout << "HRA : Rs."; + gotoxy(12, 14); + cout << "CA : Rs."; + gotoxy(12, 15); + cout << "DA : Rs."; + } + else + { + gotoxy(12, 13); + cout << "OT : Rs."; + } + gotoxy(10, 17); + cout << "DEDUCTIONS"; + gotoxy(12, 18); + cout << "LD : Rs."; + if (grade != 'E') + { + gotoxy(12, 19); + cout << "PF : Rs."; + } + gotoxy(10, 21); + cout << "NET SALARY : Rs."; + gotoxy(6, 24); + cout << "CASHIER"; + gotoxy(68, 24); + cout << "EMPLOYEE"; + float HRA = 0.0, CA = 0.0, DA = 0.0, PF = 0.0, LD = 0.0, OT = 0.0, allowance, deduction, netsalary; + if (grade != 'E') + { + if (house == 'Y') + HRA = (5 * basic) / 100; + if (convense == 'Y') + CA = (2 * basic) / 100; + DA = (5 * basic) / 100; + PF = (2 * basic) / 100; + LD = (15 * loan) / 100; + allowance = HRA + CA + DA; + deduction = PF + LD; + } + else + { + basic = days * 30; + LD = (15 * loan) / 100; + OT = hours * 10; + allowance = OT; + deduction = LD; + } + netsalary = (basic + allowance) - deduction; + gotoxy(36, 10); + cout << basic; + if (grade != 'E') + { + gotoxy(22, 13); + cout << HRA; + gotoxy(22, 14); + cout << CA; + gotoxy(22, 15); + cout << DA; + gotoxy(22, 19); + cout << PF; + } + else + { + gotoxy(22, 13); + cout << OT; + } + gotoxy(22, 18); + cout << LD; + gotoxy(33, 15); + cout << "Rs." << allowance; + gotoxy(33, 19); + cout << "Rs." << deduction; + gotoxy(36, 21); + cout << netsalary; + gotoxy(2, 1); + getch(); +} + +void main(void) +{ + MENU menu; + menu.MAIN_MENU(); +} diff --git a/PeakElement.java b/PeakElement.java new file mode 100644 index 0000000..af784ef --- /dev/null +++ b/PeakElement.java @@ -0,0 +1,21 @@ + +// leetcode -162 +class Solution { + public int findPeakElement(int[] arr) { + int start=0; + int end=arr.length-1; + int mid; +// using binary search + while (start -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - int pivotIndex(vector& nums) { - int leftSum = 0; - int rightSum = 0; - int sum = 0; - - for(int i = 0; i < nums.size(); i++){ - sum += nums[i]; - } - - rightSum = sum; - - for(int i = 0; i < nums.size(); i++){ - rightSum -= nums[i]; - if(rightSum == leftSum){ - return i; - } - - leftSum += nums[i]; - } - - return -1; - } -}; - - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n; cin >> n; - - vector nums(n); - - for(int i = 0; i < n; i++){ - cin >> nums[i]; - } - - Solution s; - - int result = s.pivotIndex(nums); - - cout << result << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { -public: - int poorPigs(int buckets, int minutesToDie, int minutesToTest) { - int t = minutesToTest / minutesToDie; - - return ceil(log(buckets)/log(t+1)); - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution { -public: - Node* connect(Node* root) { - if(root == NULL) return root; - - queueq; - q.push(root); - - while(not q.empty()) { - - int size = q.size(); - - if(size == 0) - return root; - - while(size > 0) { - Node* temp; - - if(size > 1) { - temp = q.front(); - q.pop(); - - Node* nextAdd = q.front(); - temp -> next = nextAdd; - } - else { - temp = q.front(); - q.pop(); - } - - if(temp -> left != NULL) - q.push(temp -> left); - - if(temp -> right != NULL) - q.push(temp -> right); - - size--; - } - } - - return root; - - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< + + + + + + + + + +
+ +Survey + + + +
+
+ + + +
+

Post Event Feedback Survey

+ +
+
+ + +Enter your name: + +

+Enter your department: + +

+Tell us a little bit about yourself:
+

+Do you like this event?
+Yes
+No +

+How did you know about this event? +

+Social Media +University +Friends +Google +

+What do you like the most about this event? + + + +

+Feedback form:
+

+
+ +
+

+
+ + +
+
+ + diff --git a/Postevent_update_2.html b/Postevent_update_2.html new file mode 100644 index 0000000..d0f23a3 --- /dev/null +++ b/Postevent_update_2.html @@ -0,0 +1,91 @@ + + + + + + + +Cool Grey Outer Glow Pointer + + +
+ +Survey + + + +
+
+ + + +
+

Post Event Feedback Survey

+ +
+
+ + +Enter your name: + +

+Enter your department: + +

+Tell us a little bit about yourself:
+

+Do you like this event?
+Yes
+No +

+How did you know about this event? +

+Social Media +University +Friends +Google +

+What do you like the most about this event? + + + +

+Feedback form:
+

+
+ +
+

+
+ + +
+
+ + diff --git a/Power_Set_trie.cpp b/Power_Set_trie.cpp new file mode 100644 index 0000000..ce93038 --- /dev/null +++ b/Power_Set_trie.cpp @@ -0,0 +1,29 @@ +//Problem Statement: Given a string, find all the possible subsequences of the string. + +//Examples: + +//Example 1: +//Input: str = "abc" +//Output: a ab abc ac b bc c +//Explanation: Printing all the 7 subsequence for the string "abc". + +#include +using namespace std; +void solve(int i, string s, string &f) { + if (i == s.length()) { + cout << f << " "; + return; + } + //picking + f = f + s[i]; + solve(i + 1, s, f); + //poping out while backtracking + f.pop_back(); + solve(i + 1, s, f); +} +int main() { + string s = "abc"; + string f = ""; + cout<<"All possible subsequences are: "< + + +![image](https://user-images.githubusercontent.com/96205648/193408591-1c9cf31d-b6c8-49ba-9ee4-f9bf832cf686.png) + +

+ + + + + +## :label: Participation Rules 📝 + +➡️ Pull requests can be made to any public repository on GitHub, look for the "hacktoberfest" topic to know whether the project is participating or not. The pull request must contain commits you made yourself. + +➡️ If a maintainer reports your pull request as 🔴 spam , it will not be counted towards your participation in Hacktoberfest. + +➡️ If a maintainer reports behavior that’s not in line with the project’s code of conduct, you will be ineligible to participate. + + +## :label: Rules Regarding Submission of PR :bookmark: +➡️ Participant can contribute anything he wishes for. + +➡️ Make sure to pull request in the respective folder. + +➡️ Your PR must be valid. + +➡️ Don't just copy and paste code from other website/blogs . + +➡️ Submitting someone else work will be reported as 🔴spam. + +➡️ Please read [CONTRIBUTING.md](/CONTRIBUTING.md) for details about the process for submitting pull requests to us. + + + diff --git a/Radixsort.cpp b/Radixsort.cpp new file mode 100644 index 0000000..62099d3 --- /dev/null +++ b/Radixsort.cpp @@ -0,0 +1,128 @@ +// implementation of radix sort using bin/bucket sort +#include +using namespace std; + +// structure for a single linked list to help further in the +// sorting +struct node { + int data; + node* next; +}; + +// function for creating a new node in the linked list +struct node* create(int x) +{ + node* temp = new node(); + temp->data = x; + temp->next = NULL; + + return temp; +} + +// utility function to append node in the linked list +// here head is passed by reference, to know more about this +// search pass by reference +void insert(node*& head, int n) +{ + if (head == NULL) { + head = create(n); + return; + } + + node* t = head; + while (t->next != NULL) + t = t->next; + t->next = create(n); +} + +// utility function to pop an element from front in the list +// for the sake of stability in sorting +int del(node*& head) +{ + if (head == NULL) + return 0; + node* temp = head; + // storing the value of head before updating + int val = head->data; + + // updation of head to next node + head = head->next; + + delete temp; + return val; +} + +// utility function to get the number of digits in the +// max_element +int digits(int n) +{ + int i = 1; + if (n < 10) + return 1; + + while (n > (int)pow(10, i)) + i++; + return i; +} + +void radix_sort(vector& arr) +{ + // size of the array to be sorted + int sz = arr.size(); + + // getting the maximum element in the array + int max_val = *max_element(arr.begin(), arr.end()); + + // getting digits in the maximum element + int d = digits(max_val); + + // creating buckets to store the pointers + node** bins; + + // array of pointers to linked list of size 10 as + // integers are decimal numbers so they can hold numbers + // from 0-9 only, that's why size of 10 + + bins = new node*[10]; + + // initializing the hash array with null to all + for (int i = 0; i < 10; i++) + bins[i] = NULL; + + // first loop working for a constant time only and inner + // loop is iterating through the array to store elements + // of array in the linked list by their digits value + for (int i = 0; i < d; i++) { + for (int j = 0; j < sz; j++) // bins updation + insert(bins[(arr[j] / (int)pow(10, i)) % 10], + arr[j]); + + int x = 0, y = 0; + // write back to the array after each pass + + while (x < 10) { + while (bins[x] != NULL) + arr[y++] = del(bins[x]); + x++; + } + } +} + +// a utility function to print the sorted array +void print(vector arr) +{ + for (int i = 0; i < arr.size(); i++) + cout << arr[i] << " "; + cout << endl; +} + +int main() +{ + vector arr = { 573, 25, 415, 12, 161, 6 }; + + // function call + radix_sort(arr); + print(arr); + + return 0; +} \ No newline at end of file diff --git a/RatInMaze.cpp b/RatInMaze.cpp new file mode 100644 index 0000000..383304a --- /dev/null +++ b/RatInMaze.cpp @@ -0,0 +1,64 @@ +#include +#define N 5 +using namespace std; + +int maze[N][N] = { + {1, 0, 0, 0, 0}, + {1, 1, 0, 1, 0}, + {0, 1, 1, 1, 0}, + {0, 0, 0, 1, 0}, + {1, 1, 1, 1, 1}}; + +int sol[N][N]; // final solution of the maze path is stored here +void showPath() +{ + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + cout << sol[i][j] << " "; + cout << endl; + } +} + +bool isValidPlace(int x, int y) +{ // function to check place is inside the maze and have value 1 + if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) + return true; + return false; +} + +bool solveRatMaze(int x, int y) +{ + if (x == N - 1 && y == N - 1) + { // when (x,y) is the bottom right room + sol[x][y] = 1; + return true; + } + + if (isValidPlace(x, y) == true) + { // check whether (x,y) is valid or not + sol[x][y] = 1; // set 1, when it is valid place + if (solveRatMaze(x + 1, y) == true) // find path by moving right direction + return true; + if (solveRatMaze(x, y + 1) == true) // when x direction is blocked, go for bottom direction + return true; + sol[x][y] = 0; // if both are closed, there is no path + return false; + } + return false; +} + +bool findSolution() +{ + if (solveRatMaze(0, 0) == false) + { + cout << "There is no path"; + return false; + } + showPath(); + return true; +} +int main() +{ + findSolution(); +} \ No newline at end of file diff --git a/Rearrange array elements by sign.cpp b/Rearrange array elements by sign.cpp new file mode 100644 index 0000000..f81030d --- /dev/null +++ b/Rearrange array elements by sign.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector rearrangeArray(vector& nums) { + int x= nums.size(); + vector a(x); + int i=0,j=1; + for(int k=0;k0){ + a[i]=nums[k]; + i+=2; + } + else{ + a[j]=nums[k]; + j+=2; + } + } + return a; + } +}; diff --git a/Rectangle.cpp b/Rectangle.cpp new file mode 100644 index 0000000..5a8402a --- /dev/null +++ b/Rectangle.cpp @@ -0,0 +1,85 @@ +/*Divide the stick in 4 parts codeforces "Pasha and Stick" problem. +Note +There is only one way to divide the stick in the first sample {1, 1, 2, 2}. + +Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work. + + + + +EXAMPLE:- +INPUT 1: +6 + +OUTPUT 1: +1 //divide like(1, 1, 2, 2) + +INPUT 2: +20 + +OUTPUT: +4 //divide like {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7}, {4, 4, 6, 6} + + +stick = l+l+b+b +stick = 2(l+b) +stick/2 = l+b + +*/ + + + +//SOLUTION 1: +#include +using namespace std; + +int main() +{ + long int n; + cin>>n; + + if(n%2==1) // here by default is 1. Not needed to write ==1 + { + cout<<0; + } + n=n/2; + + if(n%2==1) // here by default is 1. Not needed to write ==1 + { + cout< + +int main(){ + int i, n, p, k; + long t; + + scanf("%ld", &t); + if(t%2 !=0){ + printf("0\n"); + } + else{ + if(t%4==0){ + printf("%ld\n", (t/4)-1); + } + else printf("%ld\n", t/4); + } + + return 0; +} +*/ diff --git a/ReduceArrSize2Half.cpp b/ReduceArrSize2Half.cpp deleted file mode 100644 index 2c1cf89..0000000 --- a/ReduceArrSize2Half.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int minSetSize(vector& arr) { - unordered_map m; - - for (int i = 0; i < arr.size(); i++) { - m[arr[i]]++; - } - - multiset> s; - - for(auto n : m) { - s.insert(n.second); - } - - int size = arr.size(); - int cnt = 0; - int ans = 0; - - for(auto it = s.begin(); cnt*2 < size; ++it) { - ans++; - cnt += *it; - } - - return ans; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<next==NULL) + return head; + + ListNode* tmp = head; + ListNode* curr = head->next; + + while(curr!=NULL) { + + if(tmp->val == curr->val) { + + curr=curr->next; + } + + else { + tmp->next = curr; + tmp = curr; + curr = tmp->next; + } + } + tmp->next = NULL; + return head; + } +}; diff --git a/Remove duplicates for subarray ll.java b/Remove duplicates for subarray ll.java new file mode 100644 index 0000000..1ada765 --- /dev/null +++ b/Remove duplicates for subarray ll.java @@ -0,0 +1,20 @@ +class Solution { + public int removeDuplicates(int[] nums) extends Exception { + if(nums.length==0){ + return 0; + } + int x=1,index=0; + for(int i=0;i& nums) { + if(nums.size() == 0) return 0; + int left = 0; + for(int right =1; right< nums.size(); right++){ + if(nums[left] != nums[right]) + left++; + nums[left] = nums[right]; + } + return left+1; + } +}; diff --git a/Reverse alternate levels of a perfect binary tree b/Reverse alternate levels of a perfect binary tree new file mode 100644 index 0000000..50acc4c --- /dev/null +++ b/Reverse alternate levels of a perfect binary tree @@ -0,0 +1,75 @@ + +#include +using namespace std; + +struct Node +{ + char key; + Node *left, *right; +}; + +void preorder(struct Node *root1, struct Node* + root2, int lvl) +{ + if (root1 == NULL || root2==NULL) + return; + + if (lvl%2 == 0) + swap(root1->key, root2->key); + + preorder(root1->left, root2->right, lvl+1); + preorder(root1->right, root2->left, lvl+1); +} + + +void reverseAlternate(struct Node *root) +{ +preorder(root->left, root->right, 0); +} + + +void printInorder(struct Node *root) +{ + if (root == NULL) + return; + printInorder(root->left); + cout << root->key << " "; + printInorder(root->right); +} + +// A utility function to create a new node +Node *newNode(int key) +{ + Node *temp = new Node; + temp->left = temp->right = NULL; + temp->key = key; + return temp; +} + +int main() +{ + struct Node *root = newNode('a'); + root->left = newNode('b'); + root->right = newNode('c'); + root->left->left = newNode('d'); + root->left->right = newNode('e'); + root->right->left = newNode('f'); + root->right->right = newNode('g'); + root->left->left->left = newNode('h'); + root->left->left->right = newNode('i'); + root->left->right->left = newNode('j'); + root->left->right->right = newNode('k'); + root->right->left->left = newNode('l'); + root->right->left->right = newNode('m'); + root->right->right->left = newNode('n'); + root->right->right->right = newNode('o'); + + cout << "Inorder Traversal of given tree\n"; + printInorder(root); + + reverseAlternate(root); + + cout << "\n\nInorder Traversal of modified tree\n"; + printInorder(root); + return 0; +} diff --git a/ReverseInteger.js b/ReverseInteger.js deleted file mode 100644 index 0b1588a..0000000 --- a/ReverseInteger.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * @param {number} x - * @return {number} - */ -const reverse = (x) => { - if(x < 0){ - return -1*reverse(-x); - } - - const solution = (x+"").split('').reverse().join(''); - - return (solution > 2**31-1) ? 0 : solution; - -}; \ No newline at end of file diff --git a/ReverseLinkedList.cpp b/ReverseLinkedList.cpp index 3bb9232..ddeaba0 100644 --- a/ReverseLinkedList.cpp +++ b/ReverseLinkedList.cpp @@ -1,112 +1,16 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ class Solution { public: - // ListNode* reverseList(ListNode* head) { - // if(not head or not head->next){ - // return head; - // } - // ListNode *prev = NULL; - // ListNode *curr = head; - // ListNode *next = head->next; - - - // while(next){ - // curr->next = prev; - // prev = curr; - // curr = next; - // next = next->next; - // } - - // curr->next = prev; - - // return curr; - - // } - - - ListNode* reverseList(ListNode* head) { - if(not head or not head->next) return head; - - auto ans = reverseList(head -> next); - head -> next -> next = head; - head->next = NULL; - - return ans; - } - + ListNode* reverseList(ListNode* head) { + ListNode* current = head; + ListNode *prev = NULL, *next = NULL; + + while (current != NULL) { + next = current->next; + current->next = prev; + prev = current; + current = next; + } + head = prev; + return head; + } }; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - - ListNode* reverse(ListNode* head){ - ListNode* prev = NULL, *next = NULL, *current = head; - while(current != NULL){ - next = current->next; - current->next = prev; - prev = current; - current = next; - } - - return prev; - } - - - // ListNode* reverseBetween(ListNode* head, int left, int right) { - // ListNode* current = head, *prev = NULL; - // int count = 1; - // while(count != left) { - // prev = current; - // current = current->next; - // count++; - // } - - // ListNode* start = current; - // while(count != right){ - // current = current->next; - // count++; - // } - - // ListNode* rest = current->next; - // current->next = NULL; - - // ListNode* newHead = reverse(start); - // if(prev != NULL){ - // prev->next = newHead; - // } - // current = newHead; - // while(current->next != NULL){ - // current = current->next; - // } - - // current->next = rest; - - // if(left == 1){ - // return newHead; - // } - // else{ - // return head; - // } - // } - - - - ListNode* reverseBetween(ListNode* head, int left, int right) { - if(head == NULL or left == right) return head; - - ListNode* prev = NULL, *tail = NULL, *temp = NULL; - ListNode dummy(NULL); - prev = &dummy; - dummy.next = head; - - for(int i = 0; i < left -1; i++){ - prev = prev -> next; - } - - - tail = prev -> next; - for(int i = 0; i < right-left; i++){ - temp = prev -> next; - prev -> next = tail -> next; - tail -> next = tail -> next -> next; - prev -> next -> next = temp; - } - - return dummy.next; - } - - -}; - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<max) { + max = arr[i]; + } + } + return max; + } +} diff --git a/RodCutting.cpp b/RodCutting.cpp new file mode 100644 index 0000000..249f05f --- /dev/null +++ b/RodCutting.cpp @@ -0,0 +1,39 @@ +// A recursive solution for Rod cutting problem +#include +#include +#include +using namespace std; + +// A utility function to get the maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +/* Returns the best obtainable price for a rod of length n +and price[] as prices of different pieces */ +int cutRod(int price[], int index, int n) +{ + // base case + if (index == 0) + { + return n * price[0]; + } + // At any index we have 2 options either + // cut the rod of this length or not cut + // it + int notCut = cutRod(price, index - 1, n); + int cut = INT_MIN; + int rod_length = index + 1; + + if (rod_length <= n) + cut = price[index] + cutRod(price, index, n - rod_length); + + return max(notCut, cut); +} +int main() +{ + int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; + int size = sizeof(arr) / sizeof(arr[0]); + cout << "Maximum Obtainable Value is " + << cutRod(arr, size - 1, size); + getchar(); + return 0; +} \ No newline at end of file diff --git a/Rotate image b/Rotate image new file mode 100644 index 0000000..360af80 --- /dev/null +++ b/Rotate image @@ -0,0 +1,23 @@ +class Solution { +public: + void rotate(vector>& matrix) { + + for(int i=0;i<(matrix.size()/2);i++) + { + for(int j=0;j -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - void rotate(vector>& matrix) { - int row = matrix.size(); - for(int i = 0; i < row; i++) { - for(int j = 0; j < i; j++) { - swap(matrix[i][j], matrix[j][i]); - } - } - - for(int i = 0; i < row; i++) { - reverse(matrix[i].begin(), matrix[i].end()); - } - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +#include +using namespace __gnu_pbds; +using namespace std; +#define ff first +#define ss second +#define endl "\n" +#define ll long long +#define ld long double +#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) +#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define ump unordered_map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x, y) fixed<>x; while(x--) +// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); +typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void file_i_o(){ + ios_base::sync_with_stdio(0); + cin.tie(0); + cout.tie(0); + /* #ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); + #endif */ +} + +// Bruteforce Approach + +/*int helper(vector &height, vector &width, int n, int &maxHeight, int &maxWidth) { + int maxEnvelopes = 0; + + // Recursively try to find all way to russian doll envelope inside it + for(int i = 0; i < n; i++) { + if(height[i] < maxHeight and width[i] < maxWidth) { + maxEnvelopes = max(maxEnvelopes, 1 + helper(height, width, n, height[i], width[i])); + } + + } + + return maxEnvelopes; +} + + +int findMaxEnvelopes(vector &height, vector &width, int n) { + // Write your code here. + + // Maximum height and width of envelopes that can be placed + int maxHeight = INT_MAX; + int maxWidth = INT_MAX; + + // recursively find maximum number of envelopes that can russian doll + + return helper(height, width, n, maxHeight, maxWidth); + +}*/ + + + +// DP Approach + + +/*int findMaxEnvelopes(vector&height, vector&width, int n){ + + vector> envelopes(n, bector(2)); + + for(int i = 0; i < n; i++){ + + envelopes[i][0] = height[i]; + envelopes[i][1] = width[i]; + + } + + sort(envelopes.begin(),envelopes.end(), [](vector &v1, vector &v2) -> bool { + if(v1[0] < v2[0] or (v1[0] == v2[0] and v1[1] > v2[1])) { + return true; + } + return false; + }); + + vector maxEnvelopes(n); + + int res = 0; + + for(int i = 1; i < n; i++){ + maxEnvelopes[i] = 1; + for(int j = i-1; j >= 0; j--){ + + if(envelopes[i][1] > envelopes[j][1]){ + + maxEnvelopes[i] = max(maxEnvelopes[i], maxEnvelopes[j]+1); + + } + + result = max(result, maxEnvelopes[i]); + + } + } + + return result; + +}*/ + + + +// Approach 3 Dynamic Programming and Binary Search + +/* + Time Complexity : O(N * log(N)) + Space Complexity : O(N) + + Where 'N' is the number of envelopes. +*/ + + +int longestIncreasingSubsequence(vector &arr, int n) { + + // Here tail[i] will be last element of incresing sequence of length 'i'. + vector tail(n); + + tail[0] = arr[0]; + int length = 1; + + for(int i = 1; i < n; i++) { + + // Binary search to find position in 'tail' array. + int j = lower_bound(tail.begin(), tail.begin() + length, arr[i]) - tail.begin(); + + if(j == length) { + tail[length++] = arr[i]; + } + else { + tail[j] = arr[i]; + } + } + + return length; +} + +int findMaxEnvelopes(vector &height, vector &width, int n) { + + // Store height and width of each envelop in matrix 'envelopes'. + vector> envelopes(n, vector(2)); + for(int i = 0; i < n; i++) { + envelopes[i][0] = height[i]; + envelopes[i][1] = width[i]; + } + + // Sort matrix 'envelopes' in increasing order of their height and if height are equal then arrange in decreasing order of width. + sort(envelopes.begin(), envelopes.end(), [](vector &v1, vector &v2)->bool{ + if(v1[0] < v2[0] or (v1[0] == v2[0] and v1[1] > v2[1])) { + return true; + } + return false; + }); + + // Copy second column of matrix 'envelopes' after sorting. + vector arr(n); + for(int i = 0; i < n; i++) { + arr[i] = envelopes[i][1]; + } + + return longestIncreasingSubsequence(arr, n); +} + + + + + + + + + +int main(int argc, char const *argv[]) { + + file_i_o(); + + clock_t start, end; + start = clock(); + + w(t){ + + /* Write Code Here */ + + } + + end = clock(); + + double time_taken=double(end-start)/double(CLOCKS_PER_SEC); + cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - bool binary_search(vector> &matrix, int &target, int row) { - int l = 0; - int r = matrix[0].size()-1; - - while(l <= r) { - int mid = l + (r - l) / 2; - - if(matrix[row][mid] == target) - return true; - - else if(matrix[row][mid] > target) - r = mid - 1; - - else - l = mid + 1; - } - - return false; - } - -/* - bool searchMatrix(vector>& matrix, int target) { - int n = matrix.size(); - for(int i = 0; i < n; i++) { - if(binary_search(matrix, target, i)) { - return true; - } - } - return false; - }*/ - - - - - bool searchMatrix(vector>& matrix, int target) { - int m = matrix.size(); - if(m == 0) return false; - - int n = matrix[0].size(); - int i = 0, j = n-1; - - while(i < m and j >= 0){ - if(matrix[i][j] == target) - return true; - else if(matrix[i][j] > target) - j--; - else - i++; - } - return false; - } - - - -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& nums, int target) { + int start = 0; + int end = nums.size() - 1; + + while(start <=end){ + int mid = start + (end - start)/2; + + if(nums[mid] < target) + start = mid + 1; + else + end = mid - 1; + + } + return start; + } +}; diff --git a/lengthOfLongestSubstring.cpp b/SearchRowColumnSortedMatrix.cpp similarity index 85% rename from lengthOfLongestSubstring.cpp rename to SearchRowColumnSortedMatrix.cpp index ddc12d9..f845df9 100644 --- a/lengthOfLongestSubstring.cpp +++ b/SearchRowColumnSortedMatrix.cpp @@ -42,31 +42,23 @@ void file_i_o(){ -class Solution { -public: - int lengthOfLongestSubstring(string s) { - - int count[256] = {0}; - int l = 0; - int r = 0; - int ans = 0; - - while(r < s.length()) { - count[s[r]]++; - while(count[s[r]] > 1) { - count[s[l]]--; - l++; - } - - ans = max(ans, r-l+1); - r++; - } - - return ans; - - } -}; +pair search(vector> matrix, int x) { + // Write your code here. + int rows = matrix.size(); + + int cols = matrix[0].size(); + int row = 0, col = cols-1; + + while(row < rows and col > -1) { + int cur = matrix[row][col]; + if(cur == x) return {row, col}; + if(x > cur) row++; + else col--; + } + + return {-1, -1}; +} diff --git a/Search_2DMatrix_II.cpp b/Search_2DMatrix_II.cpp new file mode 100644 index 0000000..f03d124 --- /dev/null +++ b/Search_2DMatrix_II.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + int row = matrix.size(); + int col = matrix[0].size(); + + int rowIndex = 0; + int colIndex = col-1; + + while(rowIndex=0){ + + int element = matrix[rowIndex][colIndex]; + + if(element == target){ + return 1; + } + + if(element < target){ + rowIndex++; + } + else{ + colIndex--; + } + } + return 0; + } +}; \ No newline at end of file diff --git a/SetMatrixZero.java b/SetMatrixZero.java new file mode 100644 index 0000000..2a08cbe --- /dev/null +++ b/SetMatrixZero.java @@ -0,0 +1,19 @@ +class Solution { + public void setZeroes(int[][] matrix) { + int col0 = 1, rows = matrix.length, cols = matrix[0].length; + + for (int i = 0; i < rows; i++) { + if (matrix[i][0] == 0) col0 = 0; + for (int j = 1; j < cols; j++) + if (matrix[i][j] == 0) + matrix[i][0] = matrix[0][j] = 0; + } + + for (int i = rows - 1; i >= 0; i--) { + for (int j = cols - 1; j >= 1; j--) + if (matrix[i][0] == 0 || matrix[0][j] == 0) + matrix[i][j] = 0; + if (col0 == 0) matrix[i][0] = 0; + } + } +} diff --git a/Smallest Subtree with all the Deepest Nodes b/Smallest Subtree with all the Deepest Nodes new file mode 100644 index 0000000..b7d714d --- /dev/null +++ b/Smallest Subtree with all the Deepest Nodes @@ -0,0 +1,84 @@ + +#include +using namespace std; + +// Structure of a Node +struct TreeNode { + + int val; + TreeNode* left; + TreeNode* right; + + TreeNode(int data) + { + this->val = data; + left = NULL; + right = NULL; + } +}; + +int find_ht(TreeNode* root) +{ + if (!root) + return 0; + + // If current node is a leaf node + if (root->left == NULL + && root->right == NULL) + return 1; + + return max(find_ht(root->left), + find_ht(root->right)) + + 1; +} + +void find_node(TreeNode* root, TreeNode*& req_node) +{ + if (!root) + return; + + // Stores height of left subtree + int left_ht = find_ht(root->left); + + // Stores height of right subtree + int right_ht = find_ht(root->right); + + // If height of left subtree exceeds + // that of the right subtree + if (left_ht > right_ht) { + + // Traverse left subtree + find_node(root->left, req_node); + } + + // If height of right subtree exceeds + // that of the left subtree + else if (right_ht > left_ht) { + find_node(root->right, req_node); + } + + // Otherwise + else { + + // Return current node + req_node = root; + return; + } +} + +// Driver Code +int main() +{ + struct TreeNode* root + = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + + TreeNode* req_node = NULL; + + find_node(root, req_node); + + cout << req_node->val; + + return 0; +} diff --git a/Spiral Matrix II.java b/Spiral Matrix II.java new file mode 100644 index 0000000..d05a4b5 --- /dev/null +++ b/Spiral Matrix II.java @@ -0,0 +1,23 @@ +class Matrix { + public int[][] generateMatrix(int n) { + int[][] result = new int[n][n]; + int cnt = 1; + int dir[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + int d = 0; + int row = 0; + int col = 0; + while (cnt <= n * n) { + result[row][col] = cnt++; + int r = Math.floorMod(row + dir[d][0], n); + int c = Math.floorMod(col + dir[d][1], n); + + // change direction if next cell is non zero + if (result[r][c] != 0) d = (d + 1) % 4; + + row += dir[d][0]; + col += dir[d][1]; + } + return result; + } +} + diff --git a/SplitArrConsecuSubseq.cpp b/SplitArrConsecuSubseq.cpp deleted file mode 100644 index 1691f14..0000000 --- a/SplitArrConsecuSubseq.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - bool isPossible(vector& nums) { - map m, m1; - for(int i = 0; i < nums.size(); i++) { - m[nums[i]]++; - } - - for(auto i : nums) { - if(m[i] == 0) continue; - m[i]--; - if(m1[i-1] > 0) { - m1[i-1]--; - m1[i]++; - } - else if(m[i+1] != 0 and m[i+2] !=0){ - m[i+1]--; - m[i+2]--; - m1[i+2]++; - } - else{ - return false; - } - } - - return true; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< n) return m; + if((unsigned long long int)m*m < n) return sqrtN(m+1, e, n); -class Solution { -public: - bool isHappy(int n) { - if(n < 7 and n != 1) return false; - if(n == 1) return true; - - int ans = 0; - - while(n != 0) { - ans += pow(n%10, 2); - n /= 10; - } - - return isHappy(ans); - } -}; + return sqrtN(s, m-1, n); +} + + + +int sqrtN(long long int N) { + // Write your code here. + if(N == 0) return 0; + + return sqrtN(1, N, N); +} @@ -72,13 +72,14 @@ int main(int argc, char const *argv[]) { clock_t start, end; start = clock(); - int n; - cin >> n; + w(t){ - Solution s; + long long int N; + cin >> N; - cout << s.isHappy(n) << endl; + cout << sqrtN(N) << endl; + } end = clock(); diff --git a/SquaresOfSortedArray.java b/SquaresOfSortedArray.java new file mode 100644 index 0000000..f10752f --- /dev/null +++ b/SquaresOfSortedArray.java @@ -0,0 +1,22 @@ +//Problem Link:- https://leetcode.com/problems/squares-of-a-sorted-array/ + +//Solution Of the Problem: + +class Solution { + public int[] sortedSquares(int[] nums) { + for(int i=0;i=0 && nums[k]>key){ + nums[k+1] = nums[k]; + k=k-1; + } + nums[k+1] = key; + } + return nums; + } +} \ No newline at end of file diff --git a/StringMultiply.cpp b/StringMultiply.cpp deleted file mode 100644 index ae148b8..0000000 --- a/StringMultiply.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - string multiply(string num1, string num2) { - int len1 = num1.size(); - int len2 = num2.size(); - - if(num1 == "0" or num2 == "0") return "0"; - - vector v(len1+len2, 0); - - for(int i = len1-1; i >= 0; i--) { - for(int j = len2-1; j >= 0; j--) { - v[i+j+1] += (num1[i]-'0') * (num2[j] - '0'); - v[i+j] += v[i+j+1] /10; - v[i+j+1] %= 10; - } - } - - int i = 0; - - while(i < v.size() and v[i] == 0) i++; - - string res = ""; - while(i < v.size()) { - res += v[i] + '0'; - i++; - } - - return res; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - string num1, num2; - getline(cin, num1); - getline(cin, num2); - - Solution ans; - - cout << ans.multiply(num1, num2) << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - -class Solution { -public: - int myAtoi(string s) { - if(s.length()==0) return 0; - - int i = 0; - while(i < s.size() and s[i] == ' ') - i++; - s = s.substr(i); - - int sign = +1; - long ans = 0; - if(s[0] == '-') sign = -1; - - int MAX = INT_MAX, MIN = INT_MIN; - i = (s[0] == '+' or s[0] == '-') ? 1:0; - - while(i < s.length()) { - if(s[0] == ' ' or not isdigit(s[i])) break; - - ans = ans*10+s[i]-'0'; - if(sign == -1 and -1*ans < MIN) return MIN; - if(sign == +1 and ans > MAX) return MAX; - i++; - } - return int(sign*ans); - } - -}; - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + +int subArraySum(int arr[], int n, int sum) +{ + + int currentSum = arr[0], start = 0, i; + + + for (i = 1; i <= n; i++) { + + while (currentSum > sum && start < i - 1) { + currentSum = currentSum - arr[start]; + start++; + } + + + if (currentSum == sum) { + cout << "Sum found between indexes " << start + << " and " << i - 1; + return 1; + } + + + if (i < n) + currentSum = currentSum + arr[i]; + } + + + cout << "No subarray found"; + return 0; +} + + +int main() +{ + int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; + int n = sizeof(arr) / sizeof(arr[0]); + int sum = 23; + subArraySum(arr, n, sum); + return 0; +} + + diff --git a/Subtract 12 Operation.cpp b/Subtract 12 Operation.cpp new file mode 100644 index 0000000..792b714 --- /dev/null +++ b/Subtract 12 Operation.cpp @@ -0,0 +1,29 @@ +#include +#include +using namespace std; +#define int long long + + + int n,a[20000],s; + void solve(){ + cin>> n;s=0; + for(int i=1;i<=n;++i) cin >> a[i]; + for(int i=n;i>1;--i) + if(a[i]>0){ + a[i-1]-=a[i]/2; + a[i]=a[i]%2; + if(a[i]==1&&(a[i-1]%2==1||((i==2)&&a[1]>0))){ + a[i]=-1; + a[i-1]--; + } + } + for(int i=1;i<=n;++i) s+=abs(a[i]); + cout << s << endl; + } + + signed main(){ + int T; + cin >> T; + while(T--) solve(); + } + diff --git a/Sudoku python.py b/Sudoku python.py new file mode 100644 index 0000000..a6c4da7 --- /dev/null +++ b/Sudoku python.py @@ -0,0 +1,36 @@ +class Solution(object): + def isValidSudoku(self, board): + """ + :type board: List[List[str]] + :rtype: bool + """ + for i in range(9): + row = {} + column = {} + block = {} + row_cube = 3 * (i//3) + column_cube = 3 * (i%3) + for j in range(9): + if board[i][j]!='.' and board[i][j] in row: + return False + row[board[i][j]] = 1 + if board[j][i]!='.' and board[j][i] in column: + return False + column[board[j][i]] = 1 + rc= row_cube+j//3 + cc = column_cube + j%3 + if board[rc][cc] in block and board[rc][cc]!='.': + return False + block[board[rc][cc]]=1 + return True +ob1 = Solution() +print(ob1.isValidSudoku([ + ["5","3",".",".","7",".",".",".","."], + ["6",".",".","1","9","5",".",".","."], + [".","9","8",".",".",".",".","6","."], + ["8",".",".",".","6",".",".",".","3"], + ["4",".",".","8",".","3",".",".","1"], + ["7",".",".",".","2",".",".",".","6"], + [".","6",".",".",".",".","2","8","."], + [".",".",".","4","1","9",".",".","5"], + [".",".",".",".","8",".",".","7","9"]])) diff --git a/SudokuSolver.cpp b/SudokuSolver.cpp new file mode 100644 index 0000000..3a737d3 --- /dev/null +++ b/SudokuSolver.cpp @@ -0,0 +1,104 @@ +#include +#define N 9 +using namespace std; + +int grid[N][N] = { + {6, 5, 0, 8, 7, 3, 0, 9, 0}, + {0, 0, 3, 2, 5, 0, 0, 0, 8}, + {9, 8, 0, 1, 0, 4, 3, 5, 7}, + {1, 0, 5, 0, 0, 0, 0, 0, 0}, + {4, 0, 0, 0, 0, 0, 0, 0, 2}, + {0, 0, 0, 0, 0, 0, 5, 0, 3}, + {5, 7, 8, 3, 0, 1, 0, 2, 6}, + {2, 0, 0, 0, 4, 8, 9, 0, 0}, + {0, 9, 0, 6, 2, 5, 0, 8, 1}}; + +bool isPresentInCol(int col, int num) +{ // check whether num is present in col or not + + for (int row = 0; row < N; row++) + if (grid[row][col] == num) + return true; + + return false; +} + +bool isPresentInRow(int row, int num) +{ // check whether num is present in row or not + + for (int col = 0; col < N; col++) + if (grid[row][col] == num) + return true; + return false; +} + +bool isPresentInBox(int boxStartRow, int boxStartCol, int num) +{ // check whether num is present in 3x3 box or not + + for (int row = 0; row < 3; row++) + for (int col = 0; col < 3; col++) + if (grid[row + boxStartRow][col + boxStartCol] == num) + return true; + return false; +} + +void sudokuGrid() +{ // print the sudoku grid after solve + for (int row = 0; row < N; row++) + { + cout << "[ "; + for (int col = 0; col < N; col++) + { + + cout << grid[row][col] << " "; + } + cout << "]" << endl; + } + cout << endl; +} + +bool findEmptyPlace(int &row, int &col) +{ // get empty location and update row and column + for (row = 0; row < N; row++) + for (col = 0; col < N; col++) + if (grid[row][col] == 0) // marked with 0 is empty + return true; + return false; +} + +bool isValidPlace(int row, int col, int num) +{ + // when item not found in col, row and current 3x3 box + return !isPresentInRow(row, num) && !isPresentInCol(col, num) && !isPresentInBox(row - row % 3, col - col % 3, num); +} + +bool solveSudoku() +{ + int row, col; + if (!findEmptyPlace(row, col)) + return true; // when all places are filled + for (int num = 1; num <= 9; num++) + { + // valid numbers are 1 - 9 + if (isValidPlace(row, col, num)) + { + // check validation, if yes, put the number in the grid + grid[row][col] = num; + if (solveSudoku()) + // recursively go for other rooms in the grid + return true; + // the core of backtracking + grid[row][col] = 0; + // turn to unassigned space when conditions are not satisfied + } + } + return false; +} + +int main() +{ + if (solveSudoku() == true) + sudokuGrid(); + else + cout << "No solution exists"; +} \ No newline at end of file diff --git a/Sum of Prefix Scores of Strings.cpp b/Sum of Prefix Scores of Strings.cpp new file mode 100644 index 0000000..459f4cc --- /dev/null +++ b/Sum of Prefix Scores of Strings.cpp @@ -0,0 +1,61 @@ +// Problem: https://leetcode.com/contest/weekly-contest-311/problems/sum-of-prefix-scores-of-strings/ +// Author: vrintle +// Category: LeetCode Hard + +/* + +Problem statement +----------------- + +You are given an array words of size n consisting of non-empty strings. + +We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i]. + +For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc". +Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i]. + +Note that a string is considered as a prefix of itself. + +*/ + +struct Trie { + map mp; + int cnt; + Trie() { + cnt = 0; + } +}; + +class Solution { +public: + vector sumPrefixScores(vector& words) { + Trie *root = new Trie(); + int n = words.size(); + for(int i = 0; i < n; i++) { + Trie *t = root; + for(auto& e: words[i]) { + if(t->mp.find(e) == t->mp.end()) { + t->mp[e] = new Trie(); + } + t = t->mp[e]; + } + t->cnt++; + } + function dfs = [&](Trie *t) { + for(auto& e: t->mp) { + t->cnt += dfs(e.second); + } + return t->cnt; + }; + dfs(root); + vector ans(n); + for(int i = 0; i < n; i++) { + Trie *t = root; + for(auto& e: words[i]) { + t = t->mp[e]; + ans[i] += t->cnt; + } + } + return ans; + } +}; diff --git a/Sum of nodes at level k.cpp b/Sum of nodes at level k.cpp new file mode 100644 index 0000000..76d7a33 --- /dev/null +++ b/Sum of nodes at level k.cpp @@ -0,0 +1,69 @@ +/*Question: +Given a binary tree with N nodes and an integer K, the task is to find the sum of all the nodes +present at the Kth level. +*/ +#include +#include +using namespace std; +struct node { //Create self referential structure with 2 pointers for each node + int data; //data denotes the value present in a node + struct node* left; + struct node* right; +}; + +struct node* CreateNode(int data)//This function creates a subtree with left and right nodes for every node +{ + struct node* temp = new struct node; + temp->data = data; + temp->left = nullptr; + temp->right = nullptr; + return temp; +}; + int sumatlevelk(struct node* root,int k)//This is a slight modification of BFS +{ + if (root == NULL)//if tree is empty + return 0; + queue que; + que.push(root);//Push the root inside the queue + int level = 0;//This denotes the level that will be updated at every iteration + int sum = 0;//Initialize the sum + int f = 0; + while (!que.empty()) {//Loop until queue is empty + int size = que.size(); + for(int i=0;idata;//Increment sum + } + else { + if (ptr->left)//If left node exists + que.push(ptr->left);//Put it in queue as it acts as the root node for left subtree + if (ptr->right)//If right node exists + que.push(ptr->right);//Push it in queue as it acts as root node for right subtree + } + } + level++;//Increment level when the nodes of a particular level are processed + if (f == 1) + break; + } + return sum; +} +int main() +{ + struct node* root = new struct node; + cout<<"Enter level at which you want to get the sum"<<'\n'; + int k; + cin>>k; + root = CreateNode(50); + root->left = CreateNode(30); + root->right = CreateNode(70); + root->left->left = CreateNode(20); + root->left->right = CreateNode(40); + root->right->left = CreateNode(60); + int ans = sumatlevelk(root, k); + cout << ans; + + return 0; +} \ No newline at end of file diff --git a/KthSmallLargeElem.cpp b/SumofTwoArray.cpp similarity index 80% rename from KthSmallLargeElem.cpp rename to SumofTwoArray.cpp index e979598..db87709 100644 --- a/KthSmallLargeElem.cpp +++ b/SumofTwoArray.cpp @@ -40,37 +40,53 @@ void file_i_o(){ } -vector kthSmallLarge(vector &arr, int n, int k) { + + + +vector findArraySum(vector&a, int n, vector&b, int m) { // Write your code here. - vector result(2); - // Min_Heap - priority_queue, greater> min_heap(arr.begin(), arr.end()); + reverse(a.begin(), a.end()); + reverse(b.begin(), b.end()); - // pop from min_heap k-1 times + int carry = 0; + vectorans; - for(int i = 1; i < k; i++){ - min_heap.pop(); - } + for(int i = 0; i < max(n, m); i++) { + int sum = carry; - result[0] = min_heap.top(); + if(i < n) { + sum += a[i]; + } + if(i < m) { + sum += b[i]; + } - // Max_Heap + ans.push_back(sum%10); - priority_queue max_heap(arr.begin(), arr.end()); + if(sum >= 10) { + carry = 1; + } + else{ + carry = 0; + } + } - for(int i = 1; i < k; i++){ - max_heap.pop(); - } + if(carry > 0) { + ans.push_back(carry); + } + + reverse(ans.begin(), ans.end()); - result[1] = max_heap.top(); + return ans; - return result; } + + int main(int argc, char const *argv[]) { file_i_o(); diff --git a/TargetSum.java b/TargetSum.java new file mode 100644 index 0000000..d882f67 --- /dev/null +++ b/TargetSum.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/target-sum/ +public class TargetSum { + static int count; + public static void main(String[] args) { + int[] nums = {1, 1, 1, 1, 1}; + System.out.println(findTargetSumWays(nums, 3)); + } + public static int findTargetSumWays(int[] nums, int target){ + count = 0; + TargetSum(nums, target, 0, 0); + + return count; + } + public static void TargetSum(int[] nums, int target, int index, int val){ + if(index == nums.length){ + if(target == val){ + count++; + } + return; + } + + TargetSum(nums, target, index+1, val+nums[index]); + TargetSum(nums, target, index+1, val-nums[index]); + } +} \ No newline at end of file diff --git a/TemperatureConversion.cpp b/TemperatureConversion.cpp new file mode 100644 index 0000000..d3057e1 --- /dev/null +++ b/TemperatureConversion.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; +int main() { + float kelvin; + int celcuis; + int c; + + cout << "Please enter if you want to enter the value of temp in 1(for Kelvin " + "to celsuis) and 2(for celcuis to kelvin)"; + cin >> c; + + switch (c) { + case 1: + cout << "Please Enter The Tempratue in Kelvin : "; + cin >> kelvin; + + cout << "The Tempratue in Celsius is : " << kelvin - 274.15 << 'C' << endl; + cout << "The approx value in int is : " << int(kelvin - 274.15) << 'C'; + break; + + case 2: + cout << "Please Enter The Tempratue in Celsius : "; + cin >> celcuis; + + cout << "The Tempratue in Kelvin is : " << celcuis + 274.15 << 'k' << endl; + cout << "The approx value in Celcuis is : " << int(celcuis + 274.15) << 'k'; + break; + default: + cout << "Please Enter A valid value : "; + break; + } + return 0; +} diff --git a/RangeSumQuery.cpp b/Time2BurnTree.cpp similarity index 54% rename from RangeSumQuery.cpp rename to Time2BurnTree.cpp index fa70af0..1d47118 100644 --- a/RangeSumQuery.cpp +++ b/Time2BurnTree.cpp @@ -43,89 +43,93 @@ void file_i_o(){ +/************************************************************ + + Following is the Binary Tree node structure + + class BinaryTreeNode + { + public : + T data; + BinaryTreeNode *left; + BinaryTreeNode *right; + + BinaryTreeNode(T data) + { + this -> data = data; + left = NULL; + right = NULL; + } + }; + +************************************************************/ + +class customPair { + public : + bool foundStart; + int maxPath; + + customPair(int foundStart, int maxPath) { + this->foundStart = foundStart; + this->maxPath = maxPath; + } +}; +int ans = -1; -class NumArray { -public: - - int n; - vector seg; - - - int build(const vector &nums, int left, int right, int node){ - int middle; - int leftSum, rightSum; +customPair helper(BinaryTreeNode* root, int start) { + customPair result = customPair(false, -1); - if(left == right) return seg[node] = nums[left]; + if(root == NULL) { + result.foundStart = false; + result.maxPath = 0; - middle = (left + right) / 2; + return result; + } - leftSum = build(nums, left, middle, 2*node+1); - rightSum = build(nums, middle+1, right, 2*node+2); + customPair leftCall = helper(root -> left, start); + customPair rightCall = helper(root -> right, start); - return seg[node] = leftSum + rightSum; + if(root -> data == start) { + ans = max(leftCall.maxPath, rightCall.maxPath); + result.foundStart = true; + result.maxPath = 1; + return result; } + if(leftCall.foundStart or rightCall.foundStart) { + ans = max(ans, leftCall.maxPath+rightCall.maxPath); + if(leftCall.foundStart){ + result.foundStart = true; + result.maxPath = leftCall.maxPath + 1; + return result; + } - int sumRange(int left, int right, int ss, int se, int node) { - int leftSum; - int rightSum; + result.foundStart = true; - int middle; + result.maxPath = rightCall.maxPath + 1; - if(right < ss or left > se) return 0; - if(left <= ss and se <= right) return seg[node]; - - middle = (ss+se)/2; + return result; + } - leftSum = sumRange(left, right, ss, middle, 2*node+1); - rightSum = sumRange(left, right, middle+1, se, 2*node+2); + result.foundStart = false; + result.maxPath = max(leftCall.maxPath, rightCall.maxPath) + 1; - return leftSum+rightSum; + return result; } -int update(int index, int newVal, int ss, int se, int node) { - int leftSum; - int rightSum; - int middle; +int timeToBurnTree(BinaryTreeNode* root, int start) { + // Write your code here - if(index < ss or index > se) return seg[node]; - if(ss == se) return seg[node] = newVal; + ans = -1; - middle = (ss+se)/2; + helper(root, start); - leftSum = update(index, newVal, ss, middle, 2*node+1); - rightSum = update(index, newVal, middle+1, se, 2*node+2); - - return seg[node] = leftSum+rightSum; -} - - - - NumArray(vector& nums) { - n = nums.size(); - seg.resize(4*n); - build(nums, 0, n-1, 0); - } - - void update(int index, int val) { - update(index, val, 0, n-1, 0); - } + return ans; - int sumRange(int left, int right) { - return sumRange(left, right, 0, n-1, 0); - } -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray* obj = new NumArray(nums); - * obj->update(index,val); - * int param_2 = obj->sumRange(left,right); - */ - +} diff --git a/TrainglePattern.java b/TrainglePattern.java new file mode 100644 index 0000000..5a77509 --- /dev/null +++ b/TrainglePattern.java @@ -0,0 +1,27 @@ +/* + * + * * + * * + * * +* * +*/ +public class TrianglePattern { + public static void main(String[] args) { + // Write code here + int rows = 5; + for (int i = 1; i <= rows; i++) { + for (int j = rows; j > i; j--) { + System.out.print(" "); + } + System.out.print("*"); + for (int j = 1; j < (i - 1) * 2; j++) { + System.out.print(" "); + } + if (i == 1) { + System.out.print("\n"); + } else { + System.out.print("*" + "\n"); + } + } + } +} diff --git a/Trapping Rain Water.cpp b/Trapping Rain Water.cpp new file mode 100644 index 0000000..58bdee6 --- /dev/null +++ b/Trapping Rain Water.cpp @@ -0,0 +1,18 @@ +class Solution { // 4 ms, faster than 89.31% +public: + int trap(vector& height) { + int n = height.size(); + vector leftMax(n), rightMax(n); + for (int i = 1; i < n; ++i) + leftMax[i] = max(height[i-1], leftMax[i-1]); + for (int i = n-2; i >= 0; --i) + rightMax[i] = max(height[i+1], rightMax[i+1]); + + int ans = 0; + for (int i = 0; i < n; ++i) { + int waterLevel = min(leftMax[i], rightMax[i]); + if (waterLevel >= height[i]) ans += waterLevel - height[i]; + } + return ans; + } +}; diff --git a/coinChange.cpp b/Trie.cpp similarity index 69% rename from coinChange.cpp rename to Trie.cpp index f601c16..80ee1df 100644 --- a/coinChange.cpp +++ b/Trie.cpp @@ -1,7 +1,7 @@ #include -#include +// #include #include -using namespace __gnu_pbds; +// using namespace __gnu_pbds; using namespace std; #define ff first #define ss second @@ -26,7 +26,7 @@ using namespace std; #define mk(arr,n,type) type *arr = new type[n]; #define w(t) int x; cin>>x; while(x--) // mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; +// typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; void file_i_o(){ @@ -42,34 +42,37 @@ void file_i_o(){ +/* + Your Trie object will be instantiated and called as such: + Trie* obj = new Trie(); + obj->insert(word); + bool check2 = obj->search(word); + bool check3 = obj->startsWith(prefix); + */ -class Solution { -public: - - int dp[10010]; - int fxn(int amount, vector& coins) { +class Trie { - if(amount == 0) return 0; +public: - if(dp[amount] != -1) return dp[amount]; + /** Initialize your data structure here. */ + Trie() { - int ans = INT_MAX; + } - for(int coin : coins) { - if(amount - coin >= 0) - ans = min(ans + 0LL, fxn(amount - coin, coins) + 1LL); - } + /** Inserts a word into the trie. */ + void insert(string word) { - return dp[amount] = ans; } - int coinChange(vector& coins, int amount) { - memset(dp, -1, sizeof(dp)); + /** Returns if the word is in the trie. */ + bool search(string word) { - int ans = fxn(amount, coins); + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + bool startsWith(string prefix) { - return ans == INT_MAX ? -1 : ans; } }; @@ -77,7 +80,6 @@ class Solution { - int main(int argc, char const *argv[]) { file_i_o(); @@ -85,11 +87,9 @@ int main(int argc, char const *argv[]) { clock_t start, end; start = clock(); - w(t){ - - /* Write Code Here */ + - } + end = clock(); diff --git a/Trie.exe b/Trie.exe new file mode 100644 index 0000000..18e4c9b Binary files /dev/null and b/Trie.exe differ diff --git a/Trim given Binary Tree for any subtree containing only 0s b/Trim given Binary Tree for any subtree containing only 0s new file mode 100644 index 0000000..3e3bb63 --- /dev/null +++ b/Trim given Binary Tree for any subtree containing only 0s @@ -0,0 +1,72 @@ + +#include +using namespace std; + +class TreeNode { + +public: + int data; + TreeNode* left; + TreeNode* right; + TreeNode(int val) + { + data = val; + left = NULL; + right = NULL; + } +}; + +void inorderPrint(TreeNode* root) +{ + if (root == NULL) + return; + inorderPrint(root->left); + cout << root->data << " "; + inorderPrint(root->right); +} + +TreeNode* TrimTree(TreeNode* root) +{ + if (!root) + return nullptr; + + root->left = TrimTree(root->left); + root->right = TrimTree(root->right); + + // We only trim if the node's value is 0 + // and children are null + if (root->data == 0 && root->left == nullptr + && root->right == nullptr) { + + // We trim the subtree by returning nullptr + return nullptr; + } + + // Otherwise we leave the node the way it is + return root; +} + +// Driver code +int main() +{ + /* + 1 + / \ + 0 1 + / \ / \ + 0 0 0 1 + */ + + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(0); + root->right = new TreeNode(1); + root->left->left = new TreeNode(0); + root->left->right = new TreeNode(0); + root->right->left = new TreeNode(0); + root->right->right = new TreeNode(1); + + TreeNode* ReceivedRoot = TrimTree(root); + cout << endl; + inorderPrint(ReceivedRoot); + +} diff --git a/Two Sum IV - Input is a BST.cpp b/Two Sum IV - Input is a BST.cpp new file mode 100644 index 0000000..426fd07 --- /dev/null +++ b/Two Sum IV - Input is a BST.cpp @@ -0,0 +1,109 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +#define VALID_MIN -10000 +#define VALID_MAX 10000 +class Solution { +public: + bool FindTargetTwo(struct TreeNode* pstLeft, struct TreeNode* pstRight, int nK) +{ + if(pstLeft->val + pstRight->val == nK) return true; + + if(pstLeft->val + pstRight->val > nK) + { + if(pstLeft->left && FindTargetTwo(pstLeft->left, pstRight, nK)) return true; + + if(pstRight->left && FindTargetTwo(pstLeft, pstRight->left, nK)) return true; + } + else + { + if(pstLeft->right && FindTargetTwo(pstLeft->right, pstRight, nK)) return true; + + if(pstRight->right && FindTargetTwo(pstLeft, pstRight->right, nK)) return true; + } + + return false; +} + +bool FindTargetOne(struct TreeNode* pstRoot, int nK) +{ + if(pstRoot->val == nK) return true; + + if(pstRoot->val > nK) + { + if(pstRoot->left && FindTargetOne(pstRoot->left, nK)) return true; + } + else + { + if(pstRoot->right && FindTargetOne(pstRoot->right, nK)) return true; + } + + return false; +} + +bool FindTargetInner(struct TreeNode* pstRoot, int nK, short sMin, short sMax) +{ + if(pstRoot->left == NULL && pstRoot->right == NULL) return false; + + // find minimum of input BST + if(sMin < VALID_MIN) + { + struct TreeNode* pstTmp = pstRoot; + while(pstTmp->left) pstTmp = pstTmp->left; + sMin = pstTmp->val; + if(nK <= sMin * 2) return false; + } + + // check relation of pstRoot->val & sMin + if(nK == pstRoot->val + sMin) return true; + if(nK < pstRoot->val + sMin) return pstRoot->left && FindTargetInner(pstRoot->left, nK, sMin, SHRT_MAX); + + // find maximum of input BST + if(sMax > VALID_MAX) + { + struct TreeNode* pstTmp = pstRoot; + while(pstTmp->right) pstTmp = pstTmp->right; + sMax = pstTmp->val; + if(nK >= sMax * 2) return false; + } + + // check relation of pstRoot->val & sMax + if(nK == pstRoot->val + sMax) return true; + if(nK > pstRoot->val + sMax) return pstRoot->right && FindTargetInner(pstRoot->right, nK, SHRT_MIN, sMax); + + // if one value is current root, check the other one + if(nK < pstRoot->val * 2) + { + if(pstRoot->left) + { + if(FindTargetOne(pstRoot->left, nK-pstRoot->val)) return true; + + if(FindTargetInner(pstRoot->left, nK, sMin, SHRT_MAX)) return true; + } + } + else if(nK > pstRoot->val * 2) + { + if(pstRoot->right) + { + if(FindTargetOne(pstRoot->right, nK-pstRoot->val)) return true; + + if(FindTargetInner(pstRoot->right, nK, SHRT_MIN, sMax)) return true; + } + } + + // check both left & right leaf + return pstRoot->left && pstRoot->right && FindTargetTwo(pstRoot->left, pstRoot->right, nK); +} + +bool findTarget(struct TreeNode* root, int k){ + return FindTargetInner(root, k, SHRT_MIN, SHRT_MAX); +} +}; diff --git a/Twosums.cpp b/Twosums.cpp new file mode 100644 index 0000000..08359e9 --- /dev/null +++ b/Twosums.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + vectorresult; + for(int i =0;i a(n); + int p2=0,p3=0,p5=0; + a[0]=1; + + for(int i=1;i dp(n); + dp[0] = 1; + int x = 0, y = 0, z = 0; + for (int i = 1; i < n; i++) + { + dp[i] = min({2 * dp[x], 3 * dp[y], 5 * dp[z]}); + x += (dp[i] == 2 * dp[x]); + y += (dp[i] == 3 * dp[y]); + z += (dp[i] == 5 * dp[z]); + } + return dp[n - 1]; + } +}; diff --git a/Ugly_numbers.java b/Ugly_numbers.java new file mode 100644 index 0000000..ac0b3f0 --- /dev/null +++ b/Ugly_numbers.java @@ -0,0 +1,53 @@ +// Java program to find nth ugly number +class GFG { + + /*This function divides a by greatest + divisible power of b*/ + static int maxDivide(int a, int b) + { + while (a % b == 0) + a = a / b; + return a; + } + + /* Function to check if a number + is ugly or not */ + static int isUgly(int no) + { + no = maxDivide(no, 2); + no = maxDivide(no, 3); + no = maxDivide(no, 5); + + return (no == 1) ? 1 : 0; + } + + /* Function to get the nth ugly + number*/ + static int getNthUglyNo(int n) + { + int i = 1; + + // ugly number count + int count = 1; + + // check for all integers + // until count becomes n + while (n > count) { + i++; + if (isUgly(i) == 1) + count++; + } + return i; + } + + /* Driver Code*/ + public static void main(String args[]) + { + int no = getNthUglyNo(150); + + // Function call + System.out.println("150th ugly " + + "no. is " + no); + } +} + diff --git a/Unique Paths III.cpp b/Unique Paths III.cpp new file mode 100644 index 0000000..96f2bff --- /dev/null +++ b/Unique Paths III.cpp @@ -0,0 +1,55 @@ +#define sz(x) int(x.size()) +vector>grid2; +vector>visited; +int n , m; +int startsi,startsj; +int empty_cnt_l = 0,empty_cnt_g = 0; +bool is_valid(int i , int j) +{ + return i >= 0 && i < n && j >=0 && j < m && grid2[i][j] != -1 && (!visited[i][j]); +} + +int rec2(int r ,int c) +{ + if(!is_valid(r , c)) + return 0; + + + if(grid2[r][c] == 2) + return empty_cnt_l == empty_cnt_g; + + visited[r][c] = 1; + empty_cnt_l++; + int ans = rec2(r , c + 1) + rec2(r , c - 1) + rec2(r + 1 , c) + rec2(r - 1 ,c); + empty_cnt_l-- ,visited[r][c] = 0; + return ans; +} +class Solution { + public: + int uniquePathsIII(vector>& grid){ + n = sz(grid),m=sz(grid[0]); + empty_cnt_l = 0,empty_cnt_g = 0; + grid2.assign(n,vector(m,0)); + + grid2 = grid; + + visited.assign(n,vector(m,0)); + + grid2=grid; + + for(int i = 0 ; i < n;i++) + { + for(int j = 0 ; j < m ;j++) + { + if(grid[i][j] == 1) + startsi =i,startsj = j; + + else if(grid[i][j] == 0) + empty_cnt_g++; + } + } + empty_cnt_g++; + //cout_2d(grid2); + return rec2(startsi, startsj); + } +}; \ No newline at end of file diff --git a/Valid Parentheses.cpp b/Valid Parentheses.cpp new file mode 100644 index 0000000..66764da --- /dev/null +++ b/Valid Parentheses.cpp @@ -0,0 +1,47 @@ +class Solution { + vector my_stack; +public: + bool isValid(string s) { + if (s.size() % 2 != 0) + return false; + if (s.size() == 0) + return true; + for (int i = 0; i < s.size(); i++) + { + my_stack.push_back(s[i]); + if (my_stack[my_stack.size() - 1] == '}') + { + if (my_stack.size() > 1){ + if(my_stack[my_stack.size() - 2] == '{') + { + my_stack.pop_back(); + my_stack.pop_back(); + } + } + } + else if (my_stack[my_stack.size() - 1] == ')') + { + if (my_stack.size() > 1){ + if(my_stack[my_stack.size() - 2] == '(') + { + my_stack.pop_back(); + my_stack.pop_back(); + } + } + } + else if (my_stack[my_stack.size() - 1] == ']') + { + if (my_stack.size() > 1){ + if(my_stack[my_stack.size() - 2] == '[') + { + my_stack.pop_back(); + my_stack.pop_back(); + } + } + } + } + if (!my_stack.empty()) + return false; + return true; + } +}; diff --git a/ValidPair b/ValidPair new file mode 100755 index 0000000..01b925e Binary files /dev/null and b/ValidPair differ diff --git a/maxAreaOfIsland.cpp b/ValidPair.cpp similarity index 67% rename from maxAreaOfIsland.cpp rename to ValidPair.cpp index 969dde6..1ed4c0a 100644 --- a/maxAreaOfIsland.cpp +++ b/ValidPair.cpp @@ -41,56 +41,59 @@ void file_i_o(){ +/* +bool isValidPair(vector &arr, int n, int k, int m) { + // Write your code here. + + if(n%2 == 1) return false; + + for(int i = 0; i < n; i++) { + + if(arr[i] == -1) continue; + + for(int j = i+1; j < n; j++) { + + if(arr[j] == -1) continue; + + if((arr[i] + arr[j]) % k == m) { + arr[i] = -1; + arr[j] = -1; + break; + } + } + } -class Solution { -public: + for(int i = 0; i < n; i++) { + if(arr[i] != -1) return false; + } - bool isValid(int i, int j, int n, int m, vector>& grid) { - if(i >= 0 and i < n and j >= 0 and j < m and grid[i][j] == 1) - return true; + return true; +}*/ - return false; - } - void dfs(vector>& grid, int i, int j, int n, int m, int &area) { +bool isValidPair(vector &arr, int n, int k, int m) { + + unordered_map freq; - area++; - grid[i][j] = 0; + if(n%2 == 1) return false; - if(isValid(i+1, j, n, m, grid)) { - dfs(grid, i+1, j, n, m, area); - } - if(isValid(i-1, j, n, m, grid)) { - dfs(grid, i-1, j, n, m, area); - } - if(isValid(i, j+1, n, m, grid)) { - dfs(grid, i, j+1, n, m, area); - } - if(isValid(i, j-1, n, m, grid)) { - dfs(grid, i, j-1, n, m, area); - } + for(int i = 0; i < n; i++) { + freq[arr[i]%k]++; } - int maxAreaOfIsland(vector>& grid) { + for(auto it = freq.begin(); it != freq.end(); it++) { + int A = it->first; - int n = grid.size(); - int m = grid[0].size(); - int ans = 0; + int x = (m - A+k)%k; - for(int i = 0; i < n; i++) { - for(int j = 0; j < m; j++) { - if(grid[i][j] == 1) { - int area = 0; - dfs(grid, i, j, n, m, area); - ans = max(ans, area); - } - } - } + if(freq[x] != freq[A]) return false; + } + + return true; + +} - return ans; - } -}; @@ -106,6 +109,26 @@ int main(int argc, char const *argv[]) { /* Write Code Here */ + int n; + cin >> n; + + vector arr(n); + + for(int i = 0; i < n; i++) { + cin >> arr[i]; + } + + int k, m; + cin >> k >> m; + + if(isValidPair(arr, n, k, m)){ + cout << 'true' << endl; + } + else { + cout << 'false' << endl; + } + + } end = clock(); @@ -115,4 +138,4 @@ int main(int argc, char const *argv[]) { cerr<<"\n"<< "Coded By : S!r Black-D3vil" <<"\n"; return 0; -} +} \ No newline at end of file diff --git a/ValidateBST.cpp b/ValidateBST.cpp deleted file mode 100644 index 65b3b60..0000000 --- a/ValidateBST.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - // Definition for a binary tree node. - struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(0), left(nullptr), right(nullptr) {} - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - }; - -class Solution { -public: - - bool isBST(TreeNode* root, long minVal, long maxVal) { - if(not root) return true; - - long val = (long)root->val; - - return (val > minVal and val < maxVal and isBST(root->left, minVal, val) and isBST(root->right, val, maxVal)); - } - - bool isValidBST(TreeNode* root) { - return isBST(root, LONG_MIN, LONG_MAX); - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +void main() +{ + int a; + printf(" Code \t Products \n 106 - Haldiram Ratmali Sev \n 206 - Haldiram instant bhel \n 306 - Fuse chocolate \n 406 - Mixed Fruit Juice \n 506 - Lassi"); + printf("\n Enter the code = "); + scanf("%d",&a); + + switch(a) + { + case 106: + + printf("\n Haldiram Ratmali Sev"); + + break; + + case 206: + + printf("\n Haldiram instant bhel"); + + break; + case 306: + + printf("\n Fuse chocolate"); + + + break; + case 406: + + printf("\n Mixed Fruit Juice"); + break; + case 506: + + printf("\n Lassi"); + break; + default:printf("\n The coin is lost"); + break; + + } + + +} diff --git a/Word Break II.py b/Word Break II.py new file mode 100644 index 0000000..4e6e245 --- /dev/null +++ b/Word Break II.py @@ -0,0 +1,23 @@ +# https://leetcode.com/problems/word-break-ii/description/ + +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: + + def recur(idx, str_): + if idx >= len(s): + recur.res.append(str_.strip()) + return + + for i in range(idx, len(s)): + if s[idx:i+1] in wordDict: + temp = str_ + str_ += s[idx:i+1] + ' ' + recur(i+1, str_) + str_ = temp + + return + + recur.res = [] + + recur(0, '') + return recur.res \ No newline at end of file diff --git a/WordLadder.cpp b/WordLadder.cpp deleted file mode 100644 index ebeee78..0000000 --- a/WordLadder.cpp +++ /dev/null @@ -1,152 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - bool able(string s,string t){ - if(s.length()!=t.length()) - return false; - int c=0; - for(int i=0;i> &g,vector parent[],int n,int sr,int ds){ - vector dist(n,1005); - queue q; - q.push(sr); - parent[sr]={-1}; - dist[sr]=0; - while(!q.empty()){ - int x=q.front(); - q.pop(); - for(int u:g[x]){ - if(dist[u]>dist[x]+1){ - dist[u]=dist[x]+1; - q.push(u); - parent[u].clear(); - parent[u].push_back(x); - } - else if(dist[u]==dist[x]+1) - parent[u].push_back(x); - } - } - } - void shortestPaths(vector> &Paths, vector &path, vector parent[],int node){ - if(node==-1){ - Paths.push_back(path); - return ; - } - for(auto u:parent[node]){ - path.push_back(u); - shortestPaths(Paths,path,parent,u); - path.pop_back(); - } - } - vector> findLadders(string beginWord, string endWord, vector& wordList) { - int n=wordList.size(),sr=-1,ds=-1; - vector> ANS; - for(int i=0;i> g(n,vector()),Paths; - vector parent[n],path; - for(int i=0;i now; - for(int i=0;i -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - veector Freq(string s) { - vector freq(26, 0); - - for (int i = 0; i < s.size(); i++) { - freq[s[i] - 'a']++; - } - - return freq; - } - - vector wordSubsets(vector& words1, vector& words2) { - vector ans; - vectorMax_Freq_w2(26, 0); - - for(auto &x : words2) { - vector freq = Freq(x); - for(int i = 0; i < 26; i++) { - Max_Freq_w2 = max(freq[i], Max_Freq_w2[i]); - } - } - - for(auto &x : words1) { - vector freq = Freq(x); - bool flag = true; - - for(int i = 0; i < 26; i++) { - if(freq[i] < Max_Freq_w2[i]){ - flag = false; - break; - } - } - if(flag) ans.push_back(x); - } - return ans; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<left = root; + return newRoot; + } + + int depth = 0; + queue q{{root}}; + + while (!q.empty()) { + ++depth; + for (int sz = q.size(); sz > 0; --sz) { + TreeNode* node = q.front(); + q.pop(); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + if (depth == d - 1) { + TreeNode* cachedLeft = node->left; + TreeNode* cachedRight = node->right; + node->left = new TreeNode(v); + node->right = new TreeNode(v); + node->left->left = cachedLeft; + node->right->right = cachedRight; + } + } + if (depth == d - 1) + break; + } + + return root; + } +}; diff --git a/asteroidCollision.cpp b/asteroidCollision.cpp deleted file mode 100644 index 407c5ab..0000000 --- a/asteroidCollision.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector asteroidCollision(vector& a) { - stack s; - int n = a.size(); - for(int i =0; i < n; ++i){ - if(a[i] > 0 || s.empty()) s.push(a[i]); - else{ - while(s.size() && s.top() > 0 && s.top() < abs(a[i])) s.pop(); - if(s.size() && s.top() == abs(a[i])) s.pop(); - else if(s.empty() || s.top() < 0) s.push(a[i]); - } - } - vector ans; - while(s.size()){ - ans.push_back(s.top()); s.pop(); - } - reverse(ans.begin(), ans.end()); - return ans; - } -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector averageOfLevels(TreeNode* root) { - vector avg; - - queue q; - - q.push(root); - - while(not q.empty()) { - int n = q.size(); - - double sum = 0; - - double cnt = n; - - for(int i = 0; i < n; i++) { - TreeNode* temp = q.front(); - q.pop(); - - if(temp -> left != nullptr) q.push(temp -> left); - - if(temp -> right != nullptr) q.push(temp -> right); - - sum += temp -> val; - - } - - avg.push_back(sum/cnt); - } - - return avg; - - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - bool backspaceCompare(string s, string t) { - stack s1, s2; - string str1, str2; - - for(int i = 0; i < s.size(); i++) { - if(s[i] == '#' and not s1.empty()) - s1.pop(); - else if(s[i] != '#') - s1.push(s[i]); - } - for(int i = 0; i < t.size(); i++) { - if(t[i] == '#' and not s2.empty()) - s2.pop(); - else if(t[i] != '#') - s2.push(t[i]); - } - while(not s1.empty()) { - str1.push_back(s1.top()); - s1.pop(); - } - while(not s2.empty()){ - str2.push_back(s2.top()); - s2.pop(); - } - - return str1 == str2; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - string s, t; - getline(cin, s); - getline(cin, t); - - Solution ans; - - cout << ans.backspaceCompare(s, t) << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int bagOfTokensScore(vector& tokens, int power) { - sort(tokens.begin(), tokens.end()); - int score = 0; - int ans = 0; - - int i = 0, j = tokens.size()-1; - - while(i <= j) { - if(tokens[i] <= power) { - score += 1; - if(ans < score) { - ans = score; - } - - power -= tokens[i]; - i++; - } - else if(score > 0) { - power += tokens[j]; - score -= 1; - j--; - } - - else { - break; - } - } - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<> &matrix, int target) + { + // nrows---> Number of rows, mcols---> Number of columns + int nrows = matrix.size(); + int mcols = matrix[0].size(); // Because, No. of columns = length of any particular row + + int start = 0; + int end = nrows * mcols - 1; + int mid = (start + end) / 2; // Finding mid index + + while (start <= end) + { + mid = (start + end) / 2; + + int element = matrix[mid / mcols][mid % mcols]; // Finding the element at mid index + + if (element == target) + { + return true; + } + else if (element < target) + { + start = mid + 1; + } + else //(element > target) + { + end = mid - 1; + } + } + return 0; + } +}; \ No newline at end of file diff --git a/bst.c b/bst.c new file mode 100644 index 0000000..bcb7216 --- /dev/null +++ b/bst.c @@ -0,0 +1,243 @@ +// BST +#include +#include + +typedef struct tree +{ + struct tree *lchild; + int info; + struct tree *rchild; + +} tree; + +void create(tree **r, int n) +{ + + tree *p; + + if ((*r) == NULL) + { + p = (tree *)malloc(sizeof(tree)); + p->lchild = p->rchild = NULL; + p->info = n; + *r = p; // imprtant step + return; + } + else if ((*r)->info > n && (*r)->info != n) + create(&(*r)->lchild, n); + + else if ((*r)->info < n && (*r)->info != n) + create(&(*r)->rchild, n); + + else + { + printf("duplicate element entered \n"); + return; + } +} + +void inorder(tree *r) +{ + if (r == NULL) + return; + + inorder(r->lchild); + printf("%d ", r->info); + inorder(r->rchild); +} + +void preorder(tree *r) +{ + if (r == NULL) + return; + + printf("%d ", r->info); + preorder(r->lchild); + preorder(r->rchild); +} + +void postorder(tree *r) +{ + if (r == NULL) + return; + + postorder(r->lchild); + postorder(r->rchild); + printf("%d ", r->info); +} + +void delete (tree **r, int key) +{ + tree *p, *j = (*r); + + while (j != NULL) + { + if (key == j->info) + break; + + p = j; + + if (key < j->info) + { + j = j->lchild; + } + + else if (key > j->info) + j = j->rchild; + + else + { + printf("not found"); + return; + } + } + if ((j->lchild == NULL && j->rchild == NULL) && ((*r)->lchild != NULL || (*r)->rchild != NULL)) + { + printf("deleted element is leaf node \n"); + + if (p->info > key) + p->lchild = NULL; + else + p->rchild = NULL; + + free(j); + } + else if ((*r)->lchild == NULL && (*r)->rchild == NULL) + { + printf("only root element\n"); + free(j); + } + else if (j->lchild!=NULL || j->rchild!=NULL) + { + + } +} + +tree* search(tree *r, int key) +{ + while (r != NULL) + { + if (key == r->info) + return r; + + + if (key < r->info) + { + r = r->lchild; + } + + else if (key > r->info) + r = r->rchild; + + else + { + printf("not found"); + return NULL; + } + } + + return r; +} +int inorderpre(tree *r) +{ + r=r->lchild; + tree *p; + while (r != NULL) + { + p = r; + r = r->rchild; + } + + return p->info; +} + +int inordersucc(tree *r) +{ + r=r->rchild; + tree *p; + while (r != NULL) + { + p = r; + r = r->lchild; + } + + return p->info; +} + +int height(tree *r) +{ + tree *p = r; + int h1 = -1, h2 = -1 ; + + while (r != NULL) + { + r = r->lchild; + h1++; + } + + while (p != NULL) + { + p = p->rchild; + h2++; + } + + if (h1 >= h2) + return h1; + + else + return h2; +} + +int main() +{ + tree *root = NULL; + int n, ch, key; + + do + { + printf("\n1)Insert \n2)inorder \n3)preorder \n4)postorder \n5)delete \n6)height \n7)inorder succ \n8)inorder pred \n"); + printf("enter your choice : "); + scanf("%d", &ch); + + if (ch == 1) + { + printf("enter the digit to insert : "); + scanf("%d", &n); + create(&root, n); + } + + if (ch == 2) + { + inorder(root); + printf("\n"); + } + + if (ch == 3) + preorder(root); + + if (ch == 4) + postorder(root); + + if (ch == 5) + { + printf("enter element to delete : "); + scanf("%d", &key); + delete (&root, key); + } + if (ch == 6) + printf("height of tree is : %d\n",height(root)); + + if(ch==7) + { + printf("Enter element of which you want to find inoder pred: "); + scanf("%d",&key); + + printf("inorder pred is : %d\n",inorderpre(search(root,key))); + } + if(ch==8) + break; + + } while (1); + + return 0; +} \ No newline at end of file diff --git a/bst_linked.c b/bst_linked.c new file mode 100644 index 0000000..9a82977 --- /dev/null +++ b/bst_linked.c @@ -0,0 +1,131 @@ +#include +#include + +typedef struct tree +{ + struct tree *lchild; + int info; + struct tree *rchild; +} tree; + +void create(tree **r, int n) +{ + tree *p=(*r),*j; + if (*r == NULL) + { + p = (tree *)malloc(sizeof(tree)); + p->lchild = p->rchild = NULL; + p->info=n; + *r = p; + return; + } + while (p != NULL) + { + j = p; + + if (p->info>n) + p = p->lchild; + + else if (n > p->info) + p = p->rchild; + + else + { + printf("DUplicate element \n"); + return; + } + } + + if (p == NULL) + { + p = (tree *)malloc(sizeof(tree)); + p->lchild = p->rchild = NULL; + p->info=n; + + if(j->info>n) + { + j->lchild=p; + return; + } + else + { + j->rchild=p; + return; + } + } +} + +void inorder(tree *r) +{ + if (r == NULL) + return; + + inorder(r->lchild); + printf("%d ", r->info); + inorder(r->rchild); +} + +void preorder(tree *r) +{ + if (r == NULL) + return; + + printf("%d ", r->info); + preorder(r->lchild); + preorder(r->rchild); +} + +void postorder(tree *r) +{ + if (r == NULL) + return; + + postorder(r->lchild); + postorder(r->rchild); + printf("%d ", r->info); + +} + +int main() +{ + tree *root = NULL; + int n, ch, key; + + do + { + printf("\n1)Insert \n2)inorder \n3)preorder \n4)postorder \n5)delete \n6)exit \n"); + printf("enter your choice : "); + scanf("%d", &ch); + + if (ch == 1) + { + printf("enter the digit to insert : "); + scanf("%d", &n); + create(&root, n); + } + + if (ch == 2) + { + inorder(root); + printf("\n"); + } + + if (ch == 3) + preorder(root); + + if (ch == 4) + postorder(root); + + if (ch == 5) + { + printf("enter element to delete : "); + scanf("%d", &key); + // delete (&root, key); + } + if (ch == 6) + break; + + } while (1); + + return 0; +} \ No newline at end of file diff --git a/bubble_sort.cpp b/bubble_sort.cpp new file mode 100644 index 0000000..12aa9ac --- /dev/null +++ b/bubble_sort.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; +int main() +{ + int arr[50], tot, i, j, k, elem, index; + cout<<"Enter the Size for Array: "; + cin>>tot; + cout<<"Enter "<>arr[i]; + for(i=1; ij; k--) + arr[k] = arr[k-1]; + break; + } + } + } + else + continue; + arr[index] = elem; + } + cout<<"\nThe New Array (Sorted Array):\n"; + for(i=0; i +using namespace std; +int main() +{ + int n; + cin >> n; + int a[n]; + for (int i = 0; i < n; ++i) + cin >> a[i]; + + for (int i = 0; i < n; i++) + { + bool swapped = false; + for (int j = 0; j < n - i - 1; j++) + { + if (a[j + 1] < a[j]) + { + swapped = true; + swap(a[j + 1], a[j]); + } + } + if (!swapped) + { + break; + } + } + for (int i = 0; i < n; i++) + cout << a[i] << " "; +} \ No newline at end of file diff --git a/calculateDigit.cpp b/calculateDigit.cpp new file mode 100644 index 0000000..013abb5 --- /dev/null +++ b/calculateDigit.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +int main() +{ + int t; + cin>>t; + + while(t--) + { + + int n; + cin>>n; + + int digit_sum=0; + while(n > 0) + { + int last_digit=n%10; + digit_sum += last_digit; + n=n / 10; + } +/* Use can use also the folowing while loop + while👎 + { + digit_sum+=n%10; + n=n/10; + } + +*/ + cout<& nums) { + int n = nums.size(); + int dp[n+1]; + dp[0] = 0; + dp[1] = 0; + dp[2] = (nums[0]==nums[1]); + if(n>=3){ + if(nums[0]==nums[1] && nums[1]==nums[2]){ + dp[3] = true; + } + else if(nums[2] == nums[1]+1 && nums[1] == nums[0] + 1){ + dp[3] = true; + }else{ + dp[3] = false; + } + + } + + if(n>=4){ + for(int i = 4;i<=n;i++){ + bool a=false,b=false,c=false; + if(nums[i-1]==nums[i-2]) a = dp[i-2]; + if(nums[i-1]==nums[i-2] && nums[i-2] == nums[i-3]) b = dp[i-3]; + if(nums[i-1]-1==nums[i-2] && nums[i-2]-1 == nums[i-3]) c = dp[i-3]; + + dp[i] = a||b||c; + } + } + return dp[n]; + + } diff --git a/checkInclusion.cpp b/checkInclusion.cpp deleted file mode 100644 index 11e599f..0000000 --- a/checkInclusion.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - bool checkInclusion(string s1, string s2) { - int m[26] = {0}; - for(char c : s1) - m[c-'a']++; - int i = 0, j = 0, total_chars = s1.size(); - while(j < s2.size()) { - if(m[s2.at(j++) - 'a']-- > 0) - total_chars--; - if(total_chars == 0) return true; - if(j - i == s1.size() and m[s2.at(i++) - 'a']++ >= 0) - total_chars++; - } - return false; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + +// define the size of incidence matrix +#define size 4 + +// function to find star graph +bool checkStar(int mat[][size]) +{ + // initialize number of vertex + // with deg 1 and n-1 + int vertexD1 = 0, vertexDn_1 = 0; + + // check for S1 + if (size == 1) + return (mat[0][0] == 0); + + // check for S2 + if (size == 2) + return (mat[0][0] == 0 && mat[0][1] == 1 && + mat[1][0] == 1 && mat[1][1] == 0 ); + + // check for Sn (n>2) + for (int i = 0; i < size; i++) + { + int degreeI = 0; + for (int j = 0; j < size; j++) + if (mat[i][j]) + degreeI++; + + if (degreeI == 1) + vertexD1++; + else if (degreeI == size-1) + vertexDn_1++; + } + + return (vertexD1 == (size-1) && + vertexDn_1 == 1); +} + +// driver code +int main() +{ + int mat[size][size] = { {0, 1, 1, 1}, + {1, 0, 0, 0}, + {1, 0, 0, 0}, + {1, 0, 0, 0}}; + + checkStar(mat) ? cout << "Star Graph" : + cout << "Not a Star Graph"; + return 0; +} diff --git a/circular_delete.c b/circular_delete.c new file mode 100644 index 0000000..2a232f6 --- /dev/null +++ b/circular_delete.c @@ -0,0 +1,137 @@ +// Circular Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +} * Head; +void create(int A[], int n) +{ + int i; + struct Node *t, *last; + Head = (struct Node *)malloc(sizeof(struct Node)); + Head->data = A[0]; + Head->next = Head; + last = Head; + + for (i = 1; i < n; i++) + { + t = (struct Node *)malloc(sizeof(struct Node)); + t->data = A[i]; + t->next = last->next; + last->next = t; + last = t; + } +} +void Display(struct Node *h) +{ + do + { + printf("%d ", h->data); + h = h->next; + } while (h != Head); + printf("\n"); +} +void RDisplay(struct Node *h) +{ + static int flag = 0; + if (h != Head || flag == 0) + { + flag = 1; + printf("%d ", h->data); + RDisplay(h->next); + } + flag = 0; +} +int Length(struct Node *p) +{ + int len = 0; + do + { + len++; + p = p->next; + + } while (p != Head); + return len; +} +void Insert(struct Node *p, int index, int x) +{ + struct Node *t; + int i; + if (index < 0 || index > Length(p)) + return; + + if (index == 0) + { + t = (struct Node *)malloc(sizeof(struct Node)); + t->data = x; + if (Head == NULL) + { + Head = t; + Head->next = Head; + } + else + { + while (p->next != Head) + p = p->next; + p->next = t; + t->next = Head; + Head = t; + } + } + else + { + for (i = 0; i < index - 1; i++) + p = p->next; + t = (struct Node *)malloc(sizeof(struct Node)); + t->data = x; + t->next = p->next; + p->next = t; + } +} +int Delete(struct Node *p, int index) +{ + struct Node *q; + int i, x; + + if (index < 0 || index > Length(Head)) + return -1; + if (index == 1) + { + while (p->next != Head) + p = p->next; + x = Head->data; + if (Head == p) + { + free(Head); + Head = NULL; + } + else + { + p->next = Head->next; + free(Head); + Head = p->next; + } + } + else + { + for (i = 0; i < index - 2; i++) + p = p->next; + q = p->next; + p->next = q->next; + x = q->data; + free(q); + } + return x; +} +int main() +{ + int A[] = {2, 3, 4, 5, 6}; + create(A, 5); + + Delete(Head, 8); + + RDisplay(Head); + return 0; +} \ No newline at end of file diff --git a/clone_graph.cpp b/clone_graph.cpp new file mode 100644 index 0000000..37a4cfc --- /dev/null +++ b/clone_graph.cpp @@ -0,0 +1,20 @@ +// runtime 22ms +// author -> Sarthak Aggarwal + +class Solution { +public: + Node* cloneGraph(Node* node) { + if (!node) { + return NULL; + } + if (copies.find(node) == copies.end()) { + copies[node] = new Node(node -> val, {}); + for (Node* neighbor : node -> neighbors) { + copies[node] -> neighbors.push_back(cloneGraph(neighbor)); + } + } + return copies[node]; + } +public: + unordered_map copies; +}; \ No newline at end of file diff --git a/coinchange2.cpp b/coinchange2.cpp deleted file mode 100644 index a5409f8..0000000 --- a/coinchange2.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { -public: - - int dp[310][10010]; - - int fxn(int ind, int amount, vector& coins) { - - if(amount == 0) return 1; - - if(ind < 0) return 0; - - if(dp[ind][amount] != -1) return dp[ind][amount]; - - int ans = 0; - - for(int coin_amount = 0; coin_amount <= amount; coins_amount += coins[ind]) { - if(amount - coin >= 0) - ans += fxn(ind-1, amount - coin_amount, coins);; - } - - return dp[ind][amount] = ans; - } - - int coinChange(vector& coins, int amount) { - memset(dp, -1, sizeof(dp)); - - return fxn(coins.size()-1, amount, coins); - } - -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + + +void findNumbers(vector& ar, int sum, + vector >& res, vector& r, + int i) +{ + + if (sum == 0) { + res.push_back(r); + return; + } + + + while (i < ar.size() && sum - ar[i] >= 0) { + + + r.push_back(ar[i]); + + + findNumbers(ar, sum - ar[i], res, r, i); + i++; + + // Remove number from list (backtracking) + r.pop_back(); + } +} + + +vector > combinationSum(vector& ar, + int sum) +{ + sort(ar.begin(), ar.end()); + + + ar.erase(unique(ar.begin(), ar.end()), ar.end()); + + vector r; + vector > res; + findNumbers(ar, sum, res, r, 0); + + return res; +} + +int main() +{ + vector ar; + ar.push_back(2); + ar.push_back(4); + ar.push_back(6); + ar.push_back(8); + int n = ar.size(); + + int sum = 8; + vector > res = combinationSum(ar, sum); + + + if (res.size() == 0) { + cout << "Empty"; + return 0; + } + + + for (int i = 0; i < res.size(); i++) { + if (res[i].size() > 0) { + cout << " ( "; + for (int j = 0; j < res[i].size(); j++) + cout << res[i][j] << " "; + cout << ")"; + } + } + return 0; +} diff --git a/combinationSum.cpp b/combinationSum.cpp deleted file mode 100644 index feea09e..0000000 --- a/combinationSum.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { - vector> ans; -public: - void solve(int i, vector& candidates, vector& temp, int target) { - if(target == 0) { - ans.push_back(temp); - return; - } - - if(target < 0) return; - - if(i == candidates.size()) return; - - solve(i+1, candidates, temp, target); - - temp.push_back(candidates[i]); - solve(i, candidates, temp, target-candidates[i]); - temp.pop_back(); - - } - - vector> combinationSum(vector& candidates, int target) { - ans.clear(); - - vector temp; - - solve(0, candidates, temp, target); - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<>= 1, ++len); + ans = ((ans << len) % mod + i) % mod; + } + return ans; + } +}; diff --git a/CourseScheduleII.cpp b/countSmallerNumber.cpp similarity index 60% rename from CourseScheduleII.cpp rename to countSmallerNumber.cpp index dcc7575..2486eb9 100644 --- a/CourseScheduleII.cpp +++ b/countSmallerNumber.cpp @@ -39,51 +39,100 @@ void file_i_o(){ #endif */ } +// Brute Force Approach +/*vectorcountNumber(int n, vector &arr) { + // Write your code here. + vector count(n, 0); + + for(int i = 0; i < n; i++) { + for(int j = i+1; j < n; j++) { + if(arr[j] < arr[i]) + count[i]++; + } + } + + return count; + +}*/ + + +// Optimize Approach +// Merge Sort +void merge(vector> &arr1, int si, int ei, int si1, int ei1, vector &ans) { + int temp = 0; + int i = si; + int j = si1; -class Solution { -public: + int ctr = 0; - bool dfs(vector>& graph, vector& colors, vector& res, int i) { - colors[i] = 1; + vector>temp1(ei1-si + 5); - for(auto neighbor : graph[i]) { - if(colors[neighbor] == 1) return true; - if(colors[neighbor] == 0) { - if(dfs(graph, colors, res, neighbor)) return true; - } + while(i <= ei and j <= ei1) { + if(arr1[i][0] > arr1[j][0]) { + temp1[ctr++] = arr1[j]; + j++; + temp++; } + else { + ans[arr1[i][1]] += temp; + + temp1[ctr++] = arr1[i]; + i++; + } + } + + while(i <= ei) { + ans[arr1[i][1]] += temp; + temp1[ctr++] = arr1[i++]; + } + + while(j <= ei1) { + temp1[ctr++] = arr1[j++]; + } + + for(int i = 0l; i < ctr; i++) { + arr1[i + si] = temp1[i]; + } +} + - colors[i] = 2; - res.push_back(i); - return false; +void merge_s(vector> &arr1, int l, int r, vector &ans) { + if(l >= r) { + return; } + int mid = l + (r-l)/2; + + merge_s(arr1, l, mid, ans); + merge_s(arr1, mid+1, r, ans); + merge(arr1, l, mid, mid + 1, r, ans); +} + - vector findOrder(int numCourses, vector>& prerequisites) { - vector colors(numCourses, 0), res; - vector> graph(numCourses); - // Build Graph - for(auto pre : prerequisites) { - graph[pre[0]].push_back(pre[1]); - } +vectorcountNumber(int n, vector &arr) { + // Write your code here. - for(int i = 0; i < numCourses; i++) { - if(not colors[i]) { - if(dfs(graph, colors, res, i)) return {}; - } - } + vector>arr1(n); - return res; - } -}; + for(int i = 0; i < n; i++) { + arr1[i] = {arr[i], i}; + } + + vector ans(n); + + merge_s(arr1, 0, n-1, ans); + + return ans; + +} diff --git a/countSolutions.cpp b/countSolutions.cpp new file mode 100644 index 0000000..8c8fc7c --- /dev/null +++ b/countSolutions.cpp @@ -0,0 +1,94 @@ +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +/* + * Complete the 'countSolutions' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. INTEGER a + * 2. INTEGER b + * 3. INTEGER c + * 4. INTEGER d + */ + +int countSolutions(int a, int b, int c, int d) { + +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string q_temp; + getline(cin, q_temp); + + int q = stoi(ltrim(rtrim(q_temp))); + + for (int q_itr = 0; q_itr < q; q_itr++) { + string first_multiple_input_temp; + getline(cin, first_multiple_input_temp); + + vector first_multiple_input = split(rtrim(first_multiple_input_temp)); + + int a = stoi(first_multiple_input[0]); + + int b = stoi(first_multiple_input[1]); + + int c = stoi(first_multiple_input[2]); + + int d = stoi(first_multiple_input[3]); + + int result = countSolutions(a, b, c, d); + + fout << result << "\n"; + } + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/countVowelPermutation.cpp b/countVowelPermutation.cpp deleted file mode 100644 index be43614..0000000 --- a/countVowelPermutation.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { - -unordered_map> m; -int MOD = 1e9+7; - -public: - - int helper(int n, int i, char prev, vector> &dp) { - if(i > n) return 0; - - if(i == n) { - switch(prev) { - case 'a' : - return 1; - case 'e' : - return 2; - case 'i' : - return 4; - case 'o' : - return 2; - case 'u' : - return 1; - default : - return 5; - } - } - - int idx = prev - 'a'; - - if(dp[i][idx] != -1) { - return dp[i][idx]; - } - - long long ans = 0; - for(auto next : m[prev]) { - ans += helper(n, i+1, next, dp) %MOD; - } - - return dp[i][idx] = ans%MOD; - - } - - int countVowelPermutation(int n) { - m['c'] = {'a', 'e', 'i', 'o', 'u'}; - m['a'] = {'e'}; - m['e'] = {'a', 'i'}; - m['i'] = {'a', 'e', 'o', 'u'}; - m['o'] = {'i', 'u'}; - m['u'] = {'a'}; - - vector> dp(vector>(n+2, vector(27, -1))); - - return helper(n, 1, 'c', dp); - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n; - cin >> n; - - Solution result; - - cout << result.countVowelPermutation(n) << endl; - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +struct Node +{ + int data; + struct Node *next; +} *first = NULL; +void create(int A[], int n) +{ + int i; + struct Node *t, *last; + first = (struct Node *)malloc(sizeof(struct Node)); + first->data = A[0]; + first->next = NULL; + last = first; + for (i = 1; i < n; i++) + { + t = (struct Node *)malloc(sizeof(struct Node)); + t->data = A[i]; + t->next = NULL; + last->next = t; + last = t; + } +} +int count(struct Node *p) +{ + int l = 0; + while (p) + { + l++; + p = p->next; + } + return l; +} +int Rcount(struct Node *p) +{ + if (p != NULL) + return Rcount(p->next) + 1; + else + return 0; +} +int sum(struct Node *p) +{ + int s = 0; + while (p != NULL) + { + s += p->data; + p = p->next; + } + return s; +} +int Rsum(struct Node *p) +{ + if (p == NULL) + return 0; + else + return Rsum(p->next) + p->data; +} +int main() +{ + int A[] = {3, 5, 7, 10, 25, 8, 32, 2}; + create(A, 8); + printf("Count %d\n", count(first)); + printf("Sum %d\n", sum(first)); + return 0; +} \ No newline at end of file diff --git a/cutRod.cpp b/cutRod.cpp new file mode 100644 index 0000000..afd594c --- /dev/null +++ b/cutRod.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +using namespace __gnu_pbds; +using namespace std; +#define ff first +#define ss second +#define endl "\n" +#define ll long long +#define ld long double +#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) +#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define ump unordered_map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x, y) fixed<>x; while(x--) +// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); +typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void file_i_o(){ + ios_base::sync_with_stdio(0); + cin.tie(0); + cout.tie(0); + /* #ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); + #endif */ +} + + + + +int cutRod(vector &price, int n) { + // Write your code here. + + vector> v; + for(int i = 0; i < n; i++) { + double d = (price[i]*1.0)/(i+1); + v.push_back({d, i+1}); + } + + sort(v.begin(), v.end()); + + int i = n-1; + int ans = 0; + int size = n; + + while(size > 0) { + if(v[i].second <= size) { + ans += price[v[i].second-1]; + size = size-v[i].second; + } + + else { + i--; + } + } + + return ans; + + +} + + + + + + +int main(int argc, char const *argv[]) { + + file_i_o(); + + clock_t start, end; + start = clock(); + + w(t){ + + /* Write Code Here */ + + } + + end = clock(); + + double time_taken=double(end-start)/double(CLOCKS_PER_SEC); + cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -class Solution { -public: - string decodeString(string s) { - stack st; - - for(int i = 0; i < s.size(); i++) { - if(s[i] != ']') - st.push(s[i]); - else { - string str = ""; - while(st.top() != '[') { - str = st.top()+str; - st.pop(); - } - st.pop(); - - string number = ""; - while(not st.empty() and isdigit(st.top())) { - number = st.top()+number; - st.pop(); - } - int freq = stoi(number); - - while(freq--) { - for(int j = 0; j < str.length(); j++) - st.push(str[j]); - } - } - } - - string ans = ""; - while(not st.empty()) { - ans = st.top() + ans; - st.pop(); - } - - return ans; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* deleteDuplicates(ListNode* head) { - - ListNode* dummy = new ListNode(0, head); - - ListNode* prev = dummy; - - while(head != nullptr) { - - if(head -> next != nullptr and head -> val == head -> next -> val) { - while(head -> next != nullptr and head -> val == head -> next -> val) { - head = head -> next; - } - prev -> next = head -> next; - } - else { - prev = prev -> next; - } - - head = head -> next; - } - - return dummy -> next; - - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<next = newNode, tail = tail->next; + size++; + return true; + } + bool deQueue() { + if (isEmpty()) return false; + head = head->next; + size--; + return true; + } + int Front() { + return isEmpty() ? -1 : head->val; + } + int Rear() { + return isEmpty() ? -1 : tail->val; + } + bool isEmpty() { + return size == 0; + } + bool isFull() { + return size == maxSize; + } +private: + int maxSize, size = 0; + Node *head = new Node(0), *tail = new Node(0); +}; diff --git a/diagonalSort.cpp b/diagonalSort.cpp deleted file mode 100644 index 9569277..0000000 --- a/diagonalSort.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - void countSort(vector>& mat, int r, int c) { - int m = mat.size(); - int n = mat[0].size(); - - int i = r; - int j = c; - - vectormap(101); - while(i < m and j < n) { - map[mat[i][j]]++; - i++; - j++; - } - - i = r; - j = c; - - for(int k = 1; k < map.size(); k++) { - while(map[k] > 0) { - mat[i][j] = k; - map[k]--; - i++; - j++; - } - } - - - } - vector> diagonalSort(vector>& mat) { - int m = mat.size(); - int n = mat[0].size(); - - for(int i = 0; i < m; i++) { - countSort(mat, i, 0); - } - for(int j = 0; j < n; j++) { - countSort(mat, 0, j); - } - - return mat; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - int n, m; - cin >> n >> m; - vector>mat(m, vector(n)); - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +struct Matrix +{ + int A[10]; + int n; +}; +void Set(struct Matrix *m, int i, int j, int x) +{ + if (i == j) + m->A[i - 1] = x; +} +int Get(struct Matrix m, int i, int j) +{ + if (i == j) + return m.A[i - 1]; + else + return 0; +} +void Display(struct Matrix m) +{ + int i, j; + for (i = 0; i < m.n; i++) + { + for (j = 0; j < m.n; j++) + { + if (i == j) + printf("%d ", m.A[i]); + else + printf("0 "); + } + printf("\n"); + } +} +int main() +{ + struct Matrix m; + m.n = 4; + + Set(&m, 1, 1, 5); + Set(&m, 2, 2, 8); + Set(&m, 3, 3, 9); + Set(&m, + 4, 4, 12); + printf("%d \n", Get(m, 2, 2)); + Display(m); + return 0; +} \ No newline at end of file diff --git a/diameterOfBinaryTree.cpp b/diameterOfBinaryTree.cpp deleted file mode 100644 index dc9ef3e..0000000 --- a/diameterOfBinaryTree.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int ans = 0; - int heightBT(TreeNode* root) { - if(root == nullptr) return 0; - int lh = heightBT(root -> left); - int rh = heightBT(root -> right); - - ans = max(ans, lh + rh + 1); - - return max(lh, rh) + 1; - - } - - - int diameterOfBinaryTree(TreeNode* root) { - - int diameter = heightBT(root); - - return ans -1; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +class Solution { +public: + int singleNumber(vector& nums) { + //approach 1 + int xorresult = 0; + for(int i =0;i +using namespace std; +#include + + +#define V 9 + +int minDistance(int dist[], bool sptSet[]) +{ + + + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; + + return min_index; +} + + +void printSolution(int dist[]) +{ + cout << "Vertex \t Distance from Source" << endl; + for (int i = 0; i < V; i++) + cout << i << " \t\t\t\t" << dist[i] << endl; +} + + +void dijkstra(int graph[V][V], int src) +{ + int dist[V]; + + bool sptSet[V]; + for (int i = 0; i < V; i++) + dist[i] = INT_MAX, sptSet[i] = false; + + + dist[src] = 0; + + + for (int count = 0; count < V - 1; count++) { + + int u = minDistance(dist, sptSet); + + + sptSet[u] = true; + + + for (int v = 0; v < V; v++) + + + if (!sptSet[v] && graph[u][v] + && dist[u] != INT_MAX + && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + + printSolution(dist); +} + + +int main() +{ + + + int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; + + dijkstra(graph, 0); + + return 0; +} diff --git a/double_triangle_pattern.c b/double_triangle_pattern.c new file mode 100644 index 0000000..fa70c5c --- /dev/null +++ b/double_triangle_pattern.c @@ -0,0 +1,44 @@ +#include +void main() +{ + int i,j,n,s,a,b,l,p,t,num=0; + printf("enter the odd number of rows:"); + scanf("%d",&n); + if(n%2==0) + { + printf("invalid input"); + } + else + { + a=(n+1)/2; + b=a+1; + for(i=a;i>=1;i--) + { + for(s=(a-i);s>=1;s--) + { + printf(" "); + } + for(j=(2*i-1);j>=1;j--) + { + printf("*"); + } + printf("\n"); + } + for(l=b;l<=n;l++) + { + for(p=(n-l);p>=1;p--) + { + printf(" "); + } + for(t=l;t>=(l-2*num-2);t--) + { + printf("*"); + + } + num++; + printf("\n"); + } + + } + +} diff --git a/duplicateArray.cpp b/duplicateArray.cpp deleted file mode 100644 index a3dd7e9..0000000 --- a/duplicateArray.cpp +++ /dev/null @@ -1,133 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -int findDuplicate(vector &arr, int n){ - // Write your code here. - - // Approach 1 - - /*sort(arr.begin(), arr.end()); - - for(int i = 0; i < arr.size(); i++){ - if(arr[i] == arr[i+1]) - return arr[i]; - } - - return -1;*/ - - - // Approach 2 - - /*for(int i = 0; i < arr.size(); i++){ - int idx = abs(arr[i]) - 1; - if(arr[idx] < 0) { - return idx + 1; - } - else { - arr[idx] = -1*arr[idx]; - } - } - - return -1;*/ - - - // Hare and Tortoise method - - int tortoise = arr[0]; - int hare = arr[0]; - - do { - // hare pointer move twice as tortoise - - tortoise = arr[tortoise]; - hare = arr[arr[hare]]; - - - } - // find the intersection pt of two runners. - while(tortoise != hare); - // to find the entrance to the cycle torrtoise begins from start of array - tortoise = arr[0]; - while(tortoise != hare) { - // This time both runner move with same speed - - tortoise = arr[tortoise]; - hare = arr[hare]; - - } - // return the entrance to the cycle - return hare; - -} - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - int n; - cin >> n; - - vector arr(n); - - for(int i = 0; i < n; i++) { - cin >> arr[i]; - } - - cout << findDuplicate(arr, n) << endl; - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; +map m; +int main() +{ + int n,a,ans=0; + cin>>n; + while(n--) + { + cin>>a; + if(m[a]==0) + { + m[a]++; + ans++; + } + } + cout< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - int fib(int n) { - int a = 0, b= 1, c; - if(n <= 1) return n; - - for(int i = 2; i <= n; i++) { - c = a+b; - a = b; - b = c; - } - - return c; - - } -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n; - - cin >> n; - - Solution result; - - cout << result.fib(n) << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - - vector found_patterns(string pattern) { - if(pattern.size() == 0) return {}; - - vector v; - - int idx = 0; - - unordered_mapmp; - - - for(int i = 0; i < pattern.size(); i++) { - if(mp.find(pattern[i]) == mp.end()) { - mp.insert({pattern[i], idx++}); - v.push_back(mp[pattern[i]]); - } - else{ - v.push_back(mp[pattern[i]]); - } - } - - return v; - } - - vector findAndReplacePattern(vector& words, string pattern) { - vector v = found_patterns(pattern); - - int n = words.size(); - - vector ans; - - for(int i = 0; i < n; i++) { - vector pattern_word = found_patterns(words[i]); - if(v == pattern_word) - ans.push_back(words[i]); - } - - return ans; - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - // int findPeakElement(vector& nums) { //O(N) - // int n = nums.size(); - - // if(n == 1) return 0; - - // else if(n == 2) { - // int x = (nums[0] >= nums[1]) ? 0 : 1; - // return x; - // } - - // else { - // if(nums[0] >= nums[1]) return 0; - - // if(nums[n-1] >= nums[n-2]) return n-2; - - // for(int i = 0; i < n-1; i++) { - // if(arr[i] >= arr[i-1] and arr[i] >= arr[i+1]) return i; - // } - // } - - // } - - int findPeakElement(vector& nums) { - int n = nums.size(); - int low = 0; - int high = n-1; - - if(nums.size() == 1) return 0; - - while(low <= high) { - int mid = low + (high - low) / 2; - - if(mid == 0 or nums[mid] >= nums[mid-1] and (mid == nums.size()-1 or nums[mid] >= nums[mid+1])) { - return mid; - } - - else if(nums[mid] <= nums[mid+1]) { - low = mid + 1; - } - else { - high = mid - 1; - } - } - - return -1; - } - -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - int n; - cin >> n; - - vector nums(n); - - for(int i = 0; i < n; i++) { - cin >> nums[i]; - } - - Solution ans; - - cout << ans.findPeakElement(nums); - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< &ans) { + if(i >= j) { + string permutation = ""; + for(int k = 0; k < s.length(); k++) { + permutation += (s[k]); + } + ans.push_back(permutation); + return; + } -class Solution { -public: - int rob(vector& nums) { - int n = nums.size(); - + for(int k = i; k <= j; k++) { + swap(s[i], s[k]); + findPermutationsHelper(s, i + 1, j, ans); - int prev = nums[0]; - int prev2 = 0; + swap(s[i], s[k]); + } +} - for(int i = 0; i < n; i++) { - int take = nums[i]; - if(i > 1) take += prev2; - int notTake = 0 + prev; +vector findPermutations(string &s) { + // Write your code here. - int curi = max(take, notTake); - prev2 = prev; - prev = curi; - } + vector ans; - return prev; - } -}; + findPermutationsHelper(s, 0, s.length()-1, ans); + return ans; +} @@ -82,11 +85,7 @@ int main(int argc, char const *argv[]) { clock_t start, end; start = clock(); - w(t){ - - /* Write Code Here */ - } end = clock(); diff --git a/threeSum.cpp b/findTriplets.cpp similarity index 65% rename from threeSum.cpp rename to findTriplets.cpp index 4124fe3..87ff18a 100644 --- a/threeSum.cpp +++ b/findTriplets.cpp @@ -42,45 +42,68 @@ void file_i_o(){ -class Solution { -public: - vector> threeSum(vector& nums) { - - sort(nums.begin(), nums.end()); +vector> findTriplets(vectorarr, int n, int K) { + // Write your code here. + + // Brute Force Approach + + /*vector> ans; + + sort(arr.begin(), arr.end()); + + for(int i = 0; i < n-3; i++) { + for(int j = i+1; j < n-2; j++) { + for(int k = j+1; k < n-1; k++) { + if(arr[j] == arr[j+1]) continue; + if(arr[i] + arr[j] + arr[k] == k) { + vectortemp; + temp.push_back(arr[i]); + temp.push_back(arr[j]); + temp.push_back(arr[k]); + ans.push_back(temp); + } + } + } + } + + return ans;*/ + + + sort(arr.begin(), arr.end()); vector> res; - for(int i = 0; i < nums.size(); i++) { - if(i == 0 or (i > 0 and nums[i] != nums[i - 1])) { + for(int i = 0; i < arr.size(); i++) { + if(i == 0 or (i > 0 and arr[i] != arr[i - 1])) { int lo = i+1; - int hi = nums.size()-1; - int sum = 0 - nums[i]; + int hi = arr.size()-1; + int sum = K - arr[i]; while(lo < hi) { - if(nums[lo] + nums[hi] == sum) { + if(arr[lo] + arr[hi] == sum) { vector temp; - temp.push_back(nums[i]); - temp.push_back(nums[lo]); - temp.push_back(nums[hi]); + temp.push_back(arr[i]); + temp.push_back(arr[lo]); + temp.push_back(arr[hi]); res.push_back(temp); - while(lo < hi and nums[lo] == nums[lo+1]) lo++; - while(lo < hi and nums[hi] == nums[hi-1]) hi--; + while(lo < hi and arr[lo] == arr[lo+1]) lo++; + while(lo < hi and arr[hi] == arr[hi-1]) hi--; - lo++; hi--; + lo++; + hi--; } - else if(nums[lo] + nums[hi] < sum) lo++; + else if(arr[lo] + arr[hi] < sum) lo++; else hi--; } } } return res; - - } -}; + +} diff --git a/firstUniqChar.cpp b/firstUniqChar.cpp deleted file mode 100644 index 6bc4126..0000000 --- a/firstUniqChar.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int firstUniqChar(string s) { - - vector count(26, 0); - - for(char c : s) { - count[c - 'a'] += 1; - } - - for(int i = 0; i < s.length(); i++) { - - if(count[s[i] - 'a'] == 1) return i; - - } - - return -1; - - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - string s; - - getline(cin, s); - - Solution ans; - - cout << ans.firstUniqChar(s); - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& strs) { - - string ans = ""; +int binarySearch(vector &arr, int s, int e) { + if(s > e) return INT_MAX; + int m = (s+e)/2; - int n = strs.size(); + if(arr[m] == m) return min(m, binarySearch(arr, s, m-1)); - if(n == 0) return ans; + if(arr[m] > m) return binarySearch(arr, s, m-1); + + return binarySearch(arr, m+1, e); +} - sort(begin(strs), end(strs)); - string a = strs[0]; - string b = strs[n - 1]; +int equalIndex(vector &arr, int n) { + // Write your code here. + int ans = binarySearch(arr, 0, n-1); - for(int i = 0; i < a.size(); i++) { - if(a[i] == b[i]) ans += a[i]; - else break; - } + if(ans == INT_MAX) return -1; - return ans; - } -}; + return ans; +} diff --git a/flattenBinaryTree2LL.cpp b/flattenBinaryTree2LL.cpp deleted file mode 100644 index a783698..0000000 --- a/flattenBinaryTree2LL.cpp +++ /dev/null @@ -1,109 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ - -// Morris Traversal - -class Solution { -public: - void flatten(TreeNode* root) { - - TreeNode* curr = root; - TreeNode* prev = NULL; - - while(curr != nullptr) { - - if(curr->left != nullptr) { - prev = curr->left; - while(prev->right) - prev = prev->right; - prev->right = curr->right; - curr->right = curr->left; - curr->left = nullptr; - } - curr = curr->right; - } - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< - #include - #include - using namespace __gnu_pbds; - using namespace std; - #define ff first - #define ss second - #define endl "\n" - #define ll long long - #define ld long double - #define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) - #define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) - #define pb push_back - #define mp make_pair - #define pii pair - #define vi vector - #define mii map - #define ump unordered_map - #define pqb priority_queue - #define pqs priority_queue > - #define setbits(x) __builtin_popcountll(x) - #define zrobits(x) __builtin_ctzll(x) - #define mod 1000000007 - #define inf 1e18 - #define ps(x, y) fixed<>x; while(x--) - // mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); - typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - - void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ - } - - - int flipBits(int* arr, int n){ -int count=0, maxcount=0, x=0; - - for(int i=0; imaxcount) - - maxcount=count; - - if(count<0) - - count=0; - - } - - return maxcount+x; - } - - - - - - - - - int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n; - cin >> n; - - int arr[n]; - for(int i = 0; i < n; i++) { - cin >> arr[i]; - } - - cout << flipBits(arr, n) << endl; - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +using namespace std; + +void printfloodfill(int[][] maze, int row, int col, string psf, bool visited[][]) +{ + //base case + if ((row < 0) || (col < 0) || row >= n || col >= m || maze[row][col] == 1 || visited[row][col] == true) + { + return; + } + if (row == size() && col ==) + { + cout << psf << endl; + return; + } + + visited[row][col] = true; + printfloodfill(maze, row - 1, col, psf + "T", visited); + printfloodfill(maze, row, col - 1, psf + "L", visited); + printfloodfill(maze, row + 1, col, psf + "D", visited); + printfloodfill(maze, row, col + 1, psf + "R", visited); + visited[row][col] = false; +} + +int main() +{ + int n, m; + cin >> n >> m; + int arr[n][m]; + vector> arr(n, vector(m)); + + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + + { + cin >> arr[i][j]; + } + } + + bool visited[n][m]; + printfloodfill(arr, 0, 0, "", visited); +} diff --git a/fourSum.java b/fourSum.java new file mode 100644 index 0000000..b8a8ebd --- /dev/null +++ b/fourSum.java @@ -0,0 +1,53 @@ +import java.util.*; + +public class fourSum { + public List> fourSumLC(int[] nums, int target) { + ArrayList> result = new ArrayList>(); + + if (nums == null || nums.length == 0) + return result; + + int l = nums.length; + + Arrays.sort(nums); + + for (int i = 0; i < l; i++) { + + int target_3 = target - nums[i]; + + for (int j = i + 1; j < l; j++) { + + int target_2 = target_3 - nums[j]; + + int front = j + 1; + int back = l - 1; + + while(front < back) { + + int two_sum = nums[front] + nums[back]; + + if (two_sum < target_2) front++; + + else if (two_sum > target_2) back--; + + else { + + List quad = new ArrayList<>(); + quad.add(nums[i]); + quad.add(nums[j]); + quad.add(nums[front]); + quad.add(nums[back]); + result.add(quad); + + while (front < back && nums[front] == quad.get(2)) ++front; + + while (front < back && nums[back] == quad.get(3)) --back; + } + } + while(j + 1 < l && nums[j + 1] == nums[j]) ++j; + } + while (i + 1 < l && nums[i + 1] == nums[i]) ++i; + } + return result; + } +} diff --git a/frequenciesOfElementsInArray.cpp b/frequenciesOfElementsInArray.cpp new file mode 100644 index 0000000..35fc6db --- /dev/null +++ b/frequenciesOfElementsInArray.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +void printFrequencies (int arr[], int n) { + int frequency = 1, i = 1; + while (i < n) { + while (i < n && arr[i-1] == arr[i]) { + frequency++; + i++; + } + cout << arr[i-1] <<' ' << frequency << '\n'; + i++; + frequency = 1; + if (n == 1 || arr[n-1] != arr[n-2]) { + cout << arr[n-1] <<' ' << '1' << '\n'; + } + } +} + +int main() { + int n; cin >> n; + int arr[n]; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + printFrequencies (arr, n); + return 0; +} diff --git a/frequencyofcharacters_string.java b/frequencyofcharacters_string.java new file mode 100644 index 0000000..9179264 --- /dev/null +++ b/frequencyofcharacters_string.java @@ -0,0 +1,21 @@ +#include +using namespace std; + +int main() +{ + string str = "C++ Programming is awesome"; + char checkCharacter = 'a'; + int count = 0; + + for (int i = 0; i < str.size(); i++) + { + if (str[i] == checkCharacter) + { + ++ count; + } + } + + cout << "Number of " << checkCharacter << " = " << count; + + return 0; +} diff --git a/generate_paranthesis.cpp b/generate_paranthesis.cpp new file mode 100644 index 0000000..319381a --- /dev/null +++ b/generate_paranthesis.cpp @@ -0,0 +1,31 @@ +#include + +using namespace std; +class Solution { +public: + vector generateParenthesis(int n) { + int obc=0; + int cbc=0; + vectorv; + ans(v,n,obc,cbc,""); + return v; + + } + void ans(vector&v,int n,int obc,int cbc,string s){ + + if(obc==n&&(cbc==n)){ + + v.push_back(s); + return ; + } + +if(obccbc){ + + ans(v,n,obc,cbc+1,s+")"); + } + + } +}; \ No newline at end of file diff --git a/get maze.cpp b/get maze.cpp new file mode 100644 index 0000000..a2c7bd7 --- /dev/null +++ b/get maze.cpp @@ -0,0 +1,56 @@ + +//use eulers tree to understand +// sc=starting col +// sr=starting row +// dc =destination col +// dr =destination row +// v & h= vertical and horizontal + +#include +#include +using namespace std; + +vector getpath(int sr, int sc, int dr, int dc) +{ + if (sr == dr && sc == dc) //base case + { + vector base; + base.push_back(""); + return base; + } + vector ans; + if (sc + 1 <= dc) // condition to not go outside the maze + { + vector hpath = getpath(sr, sc + 1, dr, dc); //moving in horizontsl means rigth side + for (string s : hpath) + { + ans.push_back("h" + s); + } + } + if (sr + 1 <= dr) // condition to not go outside the maze + { + vector vpath = getpath(sr + 1, sc, dr, dc); //moving in vertical direction means downwards + for (string s : vpath) + { + ans.push_back("v" + s); + } + } + return ans; +} +void display(vector &a) //display the output +{ + + for (int i = 0; i < a.size(); i++) + { + cout << a[i]; + cout << " "; + } +} + +int main() +{ + int n, m; + cin >> n >> m; + vector answer = getpath(0, 0, n - 1, m - 1); + display(answer); +} \ No newline at end of file diff --git a/goodNodesBT.cpp b/goodNodesBT.cpp deleted file mode 100644 index 40dc6ad..0000000 --- a/goodNodesBT.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { - int cnt = 0; -public: - - void inorder(TreeNode* root, int max) { - if(root == nullptr) return; - - if(max < root -> val) { - max = root -> val; - } - - inorder(root -> left, max); - - if(root -> val >= max) { - cnt++; - max = root -> val; - } - - inorder(root -> right, max); - - } - - int goodNodes(TreeNode* root) { - int max = root -> val; - - inorder(root, max); - - return cnt; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + +int main (){ + int n; + cin>>n; + int a[n]; + for (int i=0;i>a[i]; + sort(a,a+n); + for (int i=0;i +#include +#include +int main() +{ + int guess,nguess=1,num; + srand(time(0)); + num=rand()%100+1; + do + { + printf("Guess the right number between 1 to 100 : \n"); + scanf("%d",&guess); + if(guess>num) + { + printf("LOWER NUMBER PLEASE : \n"); + } + else if(num>guess) + { + printf("GREATER NUMBER PLEASE : \n"); + } + else + { + printf("*CONGRATULATION !!! YOU GUESS THE RIGHT NUMBER. \n"); + printf("*YOU GUESS THE RIGHT NUMBER IN %d ATTEMPTS \n",nguess); + } + nguess++; + } + while(guess!=num); + +} diff --git a/hammingWeight.cpp b/hammingWeight.cpp deleted file mode 100644 index a24d323..0000000 --- a/hammingWeight.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int hammingWeight(uint32_t n) { - long long int x = (uint32_t)n; - - int count = 0; - - while(x) { - x = x & x - 1; - count++; - } - - return count; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< visited; + + while(true){ + tmp = 0; + while(n > 0){ + tmp += pow((n%10), 2); + n/=10; + } + n = tmp; + if(n == 1){ + break; + }else if(visited.find(n)!=visited.end()){ + return false; + } + visited.insert(n); + } + return true; + } +}; diff --git a/help_classmates.cpp b/help_classmates.cpp new file mode 100644 index 0000000..69b705a --- /dev/null +++ b/help_classmates.cpp @@ -0,0 +1,177 @@ +// GeeksForGeeks QUESTION : + +/* +Professor X wants his students to help each other in the chemistry lab. +He suggests that every student should help out a classmate who scored less marks than him in chemistry +and whose roll number appears after him. +But the students are lazy and they don't want to search too far. +They each pick the first roll number after them that fits the criteria. +Find the marks of the classmate that each student picks. + +Note: one student may be selected by multiple classmates. + +Example 1: +Input: N = 5, arr[] = {3, 8, 5, 2, 25} +Output: 2 5 2 -1 -1 +Explanation: + 1. Roll number 1 has 3 marks. The first person + who has less marks than him is roll number 4, + who has 2 marks. + 2. Roll number 2 has 8 marks, he helps student + with 5 marks. + 3. Roll number 3 has 5 marks, he helps student + with 2 marks. + 4. Roll number 4 and 5 can not pick anyone as + no student with higher roll number has lesser + marks than them. This is denoted by -1. +Output shows the marks of the weaker student that +each roll number helps in order. ie- 2,5,2,-1,-1 + +*/ + +// { Driver Code Starts +//Initial Template for C++ + +#include +#include +#include +using namespace std; + + + // } Driver Code Ends +//User function Template for C++ + +class Solution{ + + public: + /* + // Brute Force Approach + // Time complexity = O(N^2) + // Steps: + // 1) Initialise a vector helper to store the next greater number of arr[i] at each index i + // 2) Travel arr and for every element at index i + // Initialise a bool variable to false + // Run a loop from i+1 to n check if the current element is greater than current element, set bool var to true + // Then break the loop and store that element in vector helper + // If after running through the loop bool variable is false, store -1 in vector helper + // 3) Return the helper vector + + vector help_classmate(vector arr, int n) + { + // Your code goes here + + vector helper; + bool put = false; + for(int i=0 ; i help_classmate(vector arr, int n) + { + // Your code here + vector v; + stack s; + bool pushed; + for(int i=n-1 ; i>=0 ; i--) + { + if(s.empty() == true) + { + v.push_back(-1); + s.push(arr[i]); + } + else + { + pushed = false; + int x; + while(s.empty()==false ) + { + x = s.top(); + if(x < arr[i]) + { + v.push_back(x); + s.push(arr[i]); + pushed = true; + break; + } + else + { + if(s.empty() == false) + { + s.pop(); + } + } + } + if(s.empty()==true && pushed == false) + { + v.push_back(-1); + s.push(arr[i]); + } + + + } + } + + reverse(v.begin(),v.end()); + return v; + } +}; + +// { Driver Code Starts. + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + vector array(n); + for (int i = 0; i < n; ++i) + { + cin>>array[i]; + } + Solution obj; + vector result = obj.help_classmate(array,n); + for (int i = 0; i < n; ++i) + { + cout< +#include +#include + +using namespace std; + +class Solution { +public: + bool increasingTriplet(vector& nums) { + int l=nums.size(); + if(l<3) return false; + int min1=INT_MAX,min2=INT_MAX; + + for(int i=0;i -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector inorderTraversal(TreeNode* root) { - stack st; - TreeNode* node = root; - - vectorinorder; - - while(true) { - if(node != nullptr) { - st.push(node); - node = node -> left; - } - - else { - if(st.empty() == true) break; - node = st.top(); - st.pop(); - inorder.push_back(node -> val); - node = node -> right; - } - } - - return inorder; - } -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -#include -using namespace std; - - - -vector split(string s) { - string ans = ""; - vector v; - for(int i = 0; i < s.size(); i++) { - if(s[i] == 32) { - v.push_back(ans); - ans = ""; - } else { - ans += s[i]; - } - } - v.push_back(ans); - return v; -} - -string process(string s) { - string ans = ""; - for(int i = 0; i < s.size(); i++) { - if(s[i] >= 'a' && s[i] <= 'z' or s[i] >= 'A' && s[i] <= 'Z' or s[i] >= '0' && s[i] <= '9' ) { - ans += s[i]; - } - } - return ans; -} - -string StringChallenge(string sen) { - - vector v = split(sen); - - for(int i = 0; i < v.size(); i++) { - v[i] = process(v[i]); - } - sort(v.begin(), v.end(), [&](string a, string b) { - return a.size() > b.size(); - }); - - return v[0]; - -} - - - -int main(void) { - - string temp = "hello wrold &hdjlnv"; - cout << StringChallenge(temp); - return 0; - -} \ No newline at end of file diff --git a/invertTree.cpp b/invertTree.cpp deleted file mode 100644 index 6996a76..0000000 --- a/invertTree.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - void help(TreeNode* root) { - if(root == nullptr) return; - - help(root -> left); - help(root -> right); - - swap(root -> left, root -> right); - } - - TreeNode* invertTree(TreeNode* root) { - help(root); - - return root; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - bool isPowerOfTwo(int n) { - if(n <= 0) return false; - - return(n&(n-1)) == 0; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - int n; - cin >> n; - - Solution s; - - cout << s.isPowerOfTwo(n) << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isSameTree(TreeNode* p, TreeNode* q) { - if(p == nullptr or q == nullptr) return (p == q); - - return (p -> val == q->val) and isSameTree(p -> left, q -> left) and isSameTree(p -> right, q -> right); - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - bool ans = false; - - bool match(TreeNode* root, TreeNode* subRoot) { - if(root != nullptr and subRoot != nullptr) { - bool a = match(root -> left, subRoot -> left); - bool b = match(root -> right, subRoot -> right); - - if((root -> val == subRoot -> val) and a and b) return true; - - else return false; - } - - else if(root == nullptr and subRoot == nullptr) return true; - - else return false; - } - - void inorder(TreeNode* root, TreeNode* subRoot) { - if(root != nullptr) { - inorder(root -> left, subRoot); - - bool x = match(root, subRoot); - - if(x) { - ans = x; - } - - inorder(root -> right, subRoot); - - } - - } - - bool isSubtree(TreeNode* root, TreeNode* subRoot) { - inorder(root, subRoot); - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< + + + + + + + + + + + Hello, world! + + + + + + + + + + + + + +
+
+

Current Time Is:

+

This is a simple hero unit, a simple jumbotron-style component for calling extra attention + to featured content or information.

+
+

We are here to show you time for different countries:

+ Browse times +
+
+ + + + + \ No newline at end of file diff --git a/kadaneAlgorithm b/kadaneAlgorithm new file mode 100755 index 0000000..27f2298 Binary files /dev/null and b/kadaneAlgorithm differ diff --git a/kadaneAlgorithm.cpp b/kadaneAlgorithm.cpp new file mode 100644 index 0000000..5b13005 --- /dev/null +++ b/kadaneAlgorithm.cpp @@ -0,0 +1,32 @@ +// Time Complexity = O(n) +/* + It calculates the maximum sum subarray ending at a particular position by using the maximum sum subarray ending at the previous position +*/ + +#include +using namespace std; + +int largestSubarraySum(int *arr, int n) +{ + int currentSum = 0; + int largestSum = 0; + for (int i = 0; i < n; i++) + { + currentSum += arr[i]; + if (currentSum < 0) // Does not calculates negative as it will only cause reduction in maximum sum + currentSum = 0; // Instead of -ve it adds 0 for it + largestSum = max(largestSum, currentSum); + } + + return largestSum; +} + +int main() +{ + system("CLS"); + int arr[] = {-10, 20, -30, 40, 50, 60, -70, 80, -90}; + int n = sizeof(arr) / sizeof(int); + cout << largestSubarraySum(arr, n); + + return 0; +} diff --git a/korasuls_strongly_connected.cpp b/korasuls_strongly_connected.cpp new file mode 100644 index 0000000..3f00da5 --- /dev/null +++ b/korasuls_strongly_connected.cpp @@ -0,0 +1,98 @@ +#include +using namespace std; + + +void topo_dfss(int it, vector adj[],stack &st,vector&vis) +{ + vis[it] = 1; + + for(auto i : adj[it]){ + if(!vis[i]) + topo_dfss(i,adj,st,vis); + } + + st.push(it); +} + +void topo_dfs(vector adj[],vector &topo,int n) +{ + stack st; + vector vis(n,0); + + for(int i =0; i adj[],vector&t,vector &vt) +{ + t[it] = 1; + + for(auto i : adj[it]){ + if(!t[i]) + dfs(i,adj,t,vt); + } + + vt.push_back(it); +} + +void kos(vector adj[],vectortopo, int n, vector &strong) +{ + vector t(n,0); + vector transpose[n]; + + for(int i = 0; i topo) +{ + int n = topo.size(); + + for (int i = 0; i < n; i++) + { + cout<>n>>v; + vector adj[n]; + + for(int i = 0; i>u>>V; + adj[u].push_back(V); + } + + // step 1 -> topo sort pehle + vector topo,strong; + topo_dfs(adj,topo,n); + print(topo); + // step 2 do dfs acc to topo sort + kos(adj,topo,n,strong); + print(strong); + + return 0; +} \ No newline at end of file diff --git a/kthSmallest.cpp b/kthSmallest.cpp deleted file mode 100644 index 5d6d3c2..0000000 --- a/kthSmallest.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - int kthSmallest(vector>& matrix, int k) { - priority_queue pq; - for(int i=0; i < matrix.size(); i++) { - for(int j = 0; j < matrix[0].size(); j++) { - pq.push(matrix[i][j]); - if(pq.size() > k) - pq.pop(); - } - } - - return pq.top(); - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& wordList) { + + unordered_map> mp; + unordered_map bank,visited; + vector mywordList; + + mywordList.push_back(beginWord); + bank[beginWord]=true; + for(auto it:wordList){ + bank[it]=true; + mywordList.push_back(it); + } + + for(int i=0;i q; + q.push(beginWord); + visited[beginWord]=true; + int level=2; + + while(!q.empty()) + { + int n=q.size(); + for(int i=0;i -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int lastStoneWeight(vector& stones) { - priority_queue pq; - - for(int i=0; i 1) { - int x = pq.top(); - pq.pop(); - int y = pq.top(); - pq.pop(); - - if(x > y) pq.push(x-y); - } - - return pq.empty() ? 0 : pq.top(); - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - int n; - cin >> n; - - vector stones(n); - - for(int i = 0; i < n; i++) { - cin >> stones[i]; - } - - Solution ans; - - cout << ans.lastStoneWeight(stones) << endl; - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int lengthOfLIS(vector& nums) { - - - - /*int ans = 1; - - int n = nums.size(); - - vector dp(n, 1); - - for(int i = 0; i < n; i++) { - for(int j = i - 1; j >= 0; j--) { - if(nums[j] < nums[i]) { - dp[i] = max(dp[i], dp[j] + 1); - ans = max(ans, dp[i]); - } - } - } - - return ans;*/ - - - - vector res; - - for(int i = 0; i < nums.size(); i++) { - auto it = lower_bound(res.begin(), res.end(), nums[i]); - if(it == res.end()) res.push_back(nums[i]); - else *it = nums[i]; - } - - return res.size(); - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - void permute(string s, int i, string temp, vector& ans) { - // Base Case - - if(i >= s.length()) { - ans.push_back(temp); - return; - } - - if(s[i] >= '0' and s[i] <= '9') { - temp.push_back(s[i]); - permute(s, i+1, temp, ans); - } - - else { - temp.push_back(tolower(s[i])); - permute(s, i+1, temp, ans); - - // Backtrack - - temp.pop_back(); - - temp.push_back(toupper(s[i])); - permute(s, i+1, temp, ans); - } - - } - - vector letterCasePermutation(string s) { - vector ans; - - permute(s, 0, "", ans); - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +using namespace std; + +class Node { + public: + int data; + Node* next; + + + Node(int d) { + this->data = d; + this->next = NULL; + } + + ~Node() { + int value = this->data; + if(this->next != NULL) { + delete next; + next = NULL; + } + cout << " memory is free for node with data " << value << endl; + } + +}; + +void insertNode(Node* &tail, int element, int d) { + + + + if(tail == NULL) { + Node* newNode = new Node(d); + tail = newNode; + newNode -> next = newNode; + } + else{ + + + Node* curr = tail; + + while(curr->data != element) { + curr = curr -> next; + } + + + Node* temp = new Node(d); + temp -> next = curr -> next; + curr -> next = temp; + + } + +} + +void print(Node* tail) { + + Node* temp = tail; + + + if(tail == NULL) { + cout << "List is Empty "<< endl; + return ; + } + + do { + cout << tail -> data << " "; + tail = tail -> next; + } while(tail != temp); + + cout << endl; +} + +void deleteNode(Node* &tail, int value) { + + + if(tail == NULL) { + cout << " List is empty, please check again" << endl; + return; + } + else{ + + Node* prev = tail; + Node* curr = prev -> next; + + while(curr -> data != value) { + prev = curr; + curr = curr -> next; + } + + prev -> next = curr -> next; + + + if(curr == prev) { + tail = NULL; + } + + + else if(tail == curr ) { + tail = prev; + } + + curr -> next = NULL; + delete curr; + + } + +} + +bool isCircularList(Node* head) { + + if(head == NULL) { + return true; + } + + Node* temp = head -> next; + while(temp != NULL && temp != head ) { + temp = temp -> next; + } + + if(temp == head ) { + return true; + } + + return false; + +} + +bool detectLoop(Node* head) { + + if(head == NULL) + return false; + + map visited; + + Node* temp = head; + + while(temp !=NULL) { + + + if(visited[temp] == true) { + return true; + } + + visited[temp] = true; + temp = temp -> next; + + } + return false; + +} + + +int main() { + + Node* tail = NULL; + + + + if(isCircularList(tail)) { + cout << " Linked List is Circular in nature" << endl; + } + else{ + cout << "Linked List is not Circular " << endl; + } + + return 0; +} + diff --git a/longest cycle in graph.cpp b/longest cycle in graph.cpp new file mode 100644 index 0000000..c493543 --- /dev/null +++ b/longest cycle in graph.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + + int maxLength = -1; + + void getcycle(vector &edges,int si,vector& visit,vector& store){ + if(si == -1)return ; + if(visit[si]){ + int count = -1; + for(int i =0;i& edges) { + + vector visit(edges.size(),0); + + for(int i =0;i store; + getcycle(edges,i,visit,store); + + } + + return maxLength; + + } +}; diff --git a/longest-increasing-subsequence-ii.cpp b/longest-increasing-subsequence-ii.cpp new file mode 100644 index 0000000..f89aa28 --- /dev/null +++ b/longest-increasing-subsequence-ii.cpp @@ -0,0 +1,56 @@ +template +class SegmentTree{ +private: + int n; + vector segtree; +public: + SegmentTree(int n){ + this->n = n; + segtree.resize(4 * n + 1); + } + T op(T x, T y){ + return max(x, y); + } + void updateVal(int x, int l, int r, int idx, T val){ + if (l > idx or r < idx) + return; + if (l == r) + { + segtree[x] = val; + return; + } + int mid = (l + r) / 2LL; + updateVal(2 * x, l, mid, idx, val); + updateVal(2 * x + 1, mid + 1, r, idx, val); + segtree[x] = op(segtree[2 * x], segtree[2 * x + 1]); + } + void update(int idx, T val){ + updateVal(1, 1, n, idx, val); + } + T cal(int x, int l, int r, int L, int R){ + if (L <= l and R >= r) + return segtree[x]; + if (L > r or R < l) + return 0; + int mid = (l + r) / 2LL; + return op(cal(2 * x, l, mid, L, R), cal(2 * x + 1, mid + 1, r, L, R)); + } + T query(int l, int r){ + return l > r ? 0 : cal(1, 1, n, l, r); + } +}; +class Solution { +public: + int lengthOfLIS(vector& nums, int k) { + const int M = 1e5 + 1; + SegmentTree dp(M); + for (auto &e : nums) + { + int x = dp.query(e - k, e - 1) + 1; + int y = dp.query(e, e); + if (y < x) + dp.update(e, x); + } + return dp.query(1, M); + } +}; diff --git a/CubeSumPair.cpp b/longestMountain.cpp similarity index 80% rename from CubeSumPair.cpp rename to longestMountain.cpp index fc48cb1..4c5c3d9 100644 --- a/CubeSumPair.cpp +++ b/longestMountain.cpp @@ -40,36 +40,42 @@ void file_i_o(){ } -bool isPerfectCube(int N) { - for(int i = 1; i*i*i <= N; i++) { - if(i*i*i == N) return true; - } - return false; -} -int countCubeSumPairs(int n) { +int longestMountain(int *arr, int n) { // Write your code here. - int cnt = 0; - if(isPerfectCube(n)) { - cnt++; + if(n < 3) return 0; + + vector inc(n, 1); + vector dec(n, 1); + + for(int i = 1; i < n; i++) { + if(arr[i] > arr[i - 1]) + inc[i] += inc[i - 1]; } - for(int A = 1; A*A*A <= n; A++) { - int toCheck = n-(A*A*A); - if(isPerfectCube(toCheck)) { - cnt++; - } + for(int i = n-2; i >= 0; i--) { + if(arr[i] > arr[i+1]) + dec[i] += dec[i + 1]; + } + + int ans = 0; + + for(int i = 1; i < n-1; i++) { + if(inc[i] > 1 and dec[i] > 1) + ans = max(ans, inc[i] + dec[i] - 1); } - return cnt; + return ans; } + + int main(int argc, char const *argv[]) { file_i_o(); @@ -77,14 +83,11 @@ int main(int argc, char const *argv[]) { clock_t start, end; start = clock(); - - int n; - - cin >> n; - - cout << countCubeSumPairs(n) << endl; + w(t){ + /* Write Code Here */ + } end = clock(); diff --git a/longest_substring_without_repeating_characters.cpp b/longest_substring_without_repeating_characters.cpp new file mode 100644 index 0000000..d1e1547 --- /dev/null +++ b/longest_substring_without_repeating_characters.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +// This function returns true if all characters in str[i..j] +// are distinct, otherwise returns false +bool areDistinct(string str, int i, int j) +{ + + // Note : Default values in visited are false + vector visited(26); + + for (int k = i; k <= j; k++) { + if (visited[str[k] - 'a'] == true) + return false; + visited[str[k] - 'a'] = true; + } + return true; +} + +// Returns length of the longest substring +// with all distinct characters. +int longestUniqueSubsttr(string str) +{ + int n = str.size(); + int res = 0; // result + for (int i = 0; i < n; i++) + for (int j = i; j < n; j++) + if (areDistinct(str, i, j)) + res = max(res, j - i + 1); + return res; +} + +// Driver code +int main() +{ + string str = "geeksforgeeks"; + cout << "The input string is " << str << endl; + int len = longestUniqueSubsttr(str); + cout << "The length of the longest non-repeating " + "character substring is " + << len; + return 0; +} \ No newline at end of file diff --git a/majority_element2.cpp b/majority_element2.cpp new file mode 100644 index 0000000..ab5ca02 --- /dev/null +++ b/majority_element2.cpp @@ -0,0 +1,21 @@ +#include + +using namespace std; + +class Solution { +public: + vector majorityElement(vector& nums) { + vectorans; + int n=nums.size(); + unordered_mapmp; + for(int i=0;i(n/3)){ +ans.push_back(x.first); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/matrix_chain_mult.cpp b/matrix_chain_mult.cpp new file mode 100644 index 0000000..d08f8f0 --- /dev/null +++ b/matrix_chain_mult.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +int MatrixChainOrder(int p[], int i, int j) +{ + if (i == j) + return 0; + int k; + int mini = INT_MAX; + int count; + + for (k = i; k < j; k++) + { + count = MatrixChainOrder(p, i, k) + + MatrixChainOrder(p, k + 1, j) + + p[i - 1] * p[k] * p[j]; + + mini = min(count, mini); + } + + return mini; +} + +// Driver Code +int main() +{ + int arr[] = { 1, 2, 3, 4, 3 }; + int N = sizeof(arr) / sizeof(arr[0]); + + // Function call + cout << "Minimum number of multiplications is "<< MatrixChainOrder(arr, 1, N - 1); + return 0; +} + diff --git a/matrix_to_spiral_matrix.cpp b/matrix_to_spiral_matrix.cpp new file mode 100644 index 0000000..c14ea59 --- /dev/null +++ b/matrix_to_spiral_matrix.cpp @@ -0,0 +1,131 @@ +// C++ program to Convert given Matrix +// into sorted Spiral Matrix +#include +using namespace std; + +const int MAX = 1000; + +// Function to convert the array to Spiral +void ToSpiral(int m, int n, + int Sorted[], int a[MAX][MAX]) +{ + // For Array pointer + int index = 0; + + // k - starting row index + // m - ending row index + // l - starting column index + // n - ending column index + int k = 0, l = 0; + + while (k < m && l < n) + { + + // Print the first row + // from the remaining rows + for (int i = l; i < n; ++i) + { + a[k][i] = Sorted[index]; + index++; + } + + k++; + + // Print the last column + // from the remaining columns + for (int i = k; i < m; ++i) + { + a[i][n - 1] = Sorted[index]; + index++; + } + n--; + + // Print the last row + // from the remaining rows + if (k < m) + { + for (int i = n - 1; i >= l; --i) + { + a[m - 1][i] = Sorted[index]; + index++; + } + m--; + } + + // Print the first column + // from the remaining columns + if (l < n) + { + for (int i = m - 1; i >= k; --i) + { + a[i][l] = Sorted[index]; + index++; + } + l++; + } + } +} + +// Function to convert 2D array to 1D array +void convert2Dto1D(int y[MAX][MAX], + int m, int n,int x[]) +{ + + int index = 0; + + // Store value 2D Matrix To 1D array + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + x[index] = y[i][j]; + index++; + } + } +} + +// Function to print the Matrix +void PrintMatrix(int a[MAX][MAX], + int m, int n) +{ + + // Print Spiral Matrix + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + cout << a[i][j] << " "; + } + cout << endl; + } +} + + +// Function to Convert given Matrix +// into sorted Spiral Matrix +void convertMatrixToSortedSpiral( + int y[MAX][MAX], int m, int n) +{ + int a[MAX][MAX] = {0}; + int x[m * n]; + + convert2Dto1D(y, m, n,x); + sort(x, x + n * m); + ToSpiral(m, n, x, a); + PrintMatrix(a, m, n); +} + +// Driver code +int main() +{ + int m = 4, n = 3; + int y[MAX][MAX] = { + { 2, 5, 12 }, + { 22, 45, 55 }, + { 1, 6, 8 }, + { 13, 56, 10 }}; + + convertMatrixToSortedSpiral(y, m, n); + + return 0; +} \ No newline at end of file diff --git a/tree2str.cpp b/maxMinWindow.cpp similarity index 94% rename from tree2str.cpp rename to maxMinWindow.cpp index 8fe0801..e3ade8b 100644 --- a/tree2str.cpp +++ b/maxMinWindow.cpp @@ -42,7 +42,16 @@ void file_i_o(){ - + +vector maxMinWindow(vector a, int n) { + // Write your code here. + + + +} + + + @@ -67,3 +76,4 @@ int main(int argc, char const *argv[]) { return 0; } + diff --git a/maxProductSubArr.cpp b/maxProductSubArr.cpp deleted file mode 100644 index ca35463..0000000 --- a/maxProductSubArr.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int maxProduct(vector& nums) { - int maxp = INT_MIN, prod = 1; - - for(int i = 0; i < nums.size(); i++) { - prod *= nums[i]; - maxp = max(maxp, prod); - if(prod == 0) prod = 1; - } - - prod = 1; - - for(int i = nums.size()-1; i >= 0; i--) { - prod *= nums[i]; - maxp = max(maxp, prod); - if(prod == 0) prod = 1; - } - - return maxp; - - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<mp; - - for(int i = 0; i < s.size(); i++) { - mp[s[i]]++; - maxFreq = max(maxFreq, mp[s[i]]); - - if((i-st+1)-maxFreq > k) { - mp[s[st]]--; - st++; - } - maxi = max(maxi, i-st+1); - } - - return maxi; - } -}; + +long long maxSubarraySum(int arr[], int n) +{ + /* + Don't write main(). + Don't read input, it is passed as function argument. + No need to print anything. + Taking input and printing output is handled automatically. + */ + + long long ans = 0; + long long sum = 0; + + for(int i = 0; i < n; i++) { + sum += arr[i]; + ans = max(ans, sum); + + if(sum < 0) sum = 0; + } + + return ans; + +} + + + diff --git a/maxSumSubmatrix.cpp b/maxSumSubmatrix.cpp deleted file mode 100644 index b7ac253..0000000 --- a/maxSumSubmatrix.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int maxSumSubmatrix(vector>& matrix, int k) { - int res = INT_MIN, rows = matrix.size(), cols = matrix[0].size(); - for(int l = 0; l < cols; l++) { - vector sums(rows); - for(int r = l; r < cols; r++) { - for(int i = 0; i < rows; i++) - sums[i] += matrix[i][r]; - sets = {0}; - int run_sum = 0; - for(int sum : sums) { - run_sum += sum; - auto it = s.lower_bound(run_sum - k); - if(it != end(s)) - res = max(res, run_sum - *it); - s.insert(run_sum); - } - } - } - return res; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< maxXorQueries(vector &arr, vector >&queries) { + + +/*vector maxXorQueries(vector &arr, vector> &queries){ + + int n = arr.size(); int m = queries.size(); vector result(m, -1); - for(int i = 0; i < m; i++) { - for(int j = 0; j < n; j++){ - if(arr[i] <= queries[i][1]) - result[i] = max(result[i], arr[j]^queries[i][0]); - } - } + for(int i=0; i < m; i++) { + + for(int j=0; j < n; j++) { + if(arr[j] <= queries[i][1]) { + result[i] = max(result[i], arr[j]^queries[i][0]); + } + } + + } + + return result; + +}*/ + - return result; -} -// optimized solution +// Optimized Solution vector maxXorQueries(vector &arr, vector> &queries) { + +// Number of Queries int m = queries.size(); + vector result(m, -1); + // Sort Arr in Non-decreasing order + sort(arr.begin(), arr.end()); - for(int i = 0; i < m; i++){ - if(queries[i][1] < arr[0]) + // Finding answer of each queries + + for(int i = 0; i < m; i++) { + + // If answer to rhis query is -1 + if(queries[i][1] < arr[0]) { continue; + } + int left = 0; int right = upper_bound(arr.begin(), arr.end(), queries[i][1]) - arr.begin(); int ans = 0; int cur = 0; - for(int j = 30; j >= 0; j--){ + for(int j = 30; j >= 0; j--) { + // if jth bit is set in queries[i][0] (i.e 'Xi') if(queries[i][0] & (1 << j)) { - if(not(arr[left] & (1 << j))){ + if(not arr[left] & (1 << j)) { ans = ans | (1 << j); - right = lower_bound(begin() + left, arr.begin() + right, cur + (1 << j)) - arr.begin(); + right = lower_bound(arr.begin() + left, arr.end() + right, cur + (1 << j)) - arr.begin(); } - else{ + else { cur = cur | (1 << j); } } + else { + // if jth bit is not set in queries[i][0] (i.e 'Xi') + if(arr[right - 1] & (1 << j)) { ans = ans | (1 << j); cur = cur | (1 << j); - left = lower_bound(begin() + left, arr.begin() + right, cur) - arr.begin(); + left = lower_bound(arr.begin() + left, arr.end() + right, cur) - arr.begin(); } } } @@ -95,11 +121,15 @@ vector maxXorQueries(vector &arr, vector> &queries) { } return result; + } -int main(int argc, char const *argv[]) -{ + + + + +int main(int argc, char const *argv[]) { file_i_o(); diff --git a/maxfreqofelement.cpp b/maxfreqofelement.cpp new file mode 100644 index 0000000..3545e1d --- /dev/null +++ b/maxfreqofelement.cpp @@ -0,0 +1,58 @@ +#include //in this we have created a map to store the freq..and created a minheap and output the elemnts having more freq +using namespace std; + +typedef pair pi; + +void PrintTopKfrequentNums(vector &arr, int k) +{ + + //created a map becoz numbers r repeating ... map stores the the freq of a particular number + + /* input: (10->no. of ele + 2 2 2 1 1 1 3 3 4 + 2->key) + Map will store the input like this ...with which it will be easier to store freq + + no. freq + 1 -> 3 + 2 -> 3 + 3 -> 2 + 4 -> 1 + + */ + + unordered_map mp; + for (auto e : arr) + { + mp[e]++; + } + + priority_queue, greater> minh; + for (auto e : mp) //iterating the map from 1st to last + { + minh.push(make_pair(e.second, e.first)); // pair becoz we r pushing both freq and no. + + if (minh.size() > k) + minh.pop(); + } + + while (!minh.empty()) + { + cout << minh.top().second << " "; //printing the no. with highest freq + minh.pop(); + } + cout << endl; +} + +int main() +{ + int n, k; + cin >> n >> k; + vector arr(n); + + for (int i = 0; i < n; ++i) + cin >> arr[i]; + + PrintTopKfrequentNums(arr, k); + return 0; +} \ No newline at end of file diff --git a/maximize_array.cpp b/maximize_array.cpp new file mode 100644 index 0000000..1745aca --- /dev/null +++ b/maximize_array.cpp @@ -0,0 +1,22 @@ +#include + +using namespace std; +class Solution { +public: + int maxSubArray(vector& nums) { + + int n=nums.size(); + int sum=0; + int maxi=INT_MIN; + for(int i=0;i&w,unordered_map&m,vector&score){ + if(n<0) return 0; + bool flag=true; + int sr=0; + for(auto x:w[n]){ + if(!m[x]) flag=false; + m[x]--;sr+=score[x-'a']; + } + int a=0,b=0; + if(flag) a=sr+solve(n-1,w,m,score); + for(auto x:w[n]) m[x]++; + b=solve(n-1,w,m,score); + return max(a,b); + } + int maxScoreWords(vector& words, vector& letters, vector& score) { + unordered_mapm; + for(auto x: letters) m[x]++; + return solve(words.size()-1,words,m,score); + } +}; diff --git a/BSTIterator.cpp b/maximumMeetings.cpp similarity index 61% rename from BSTIterator.cpp rename to maximumMeetings.cpp index 6ef55ca..a810528 100644 --- a/BSTIterator.cpp +++ b/maximumMeetings.cpp @@ -42,55 +42,66 @@ void file_i_o(){ +struct meet { + int meetID; + int startTime; + int endTime; +}; -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class BSTIterator { -public: - - vector v; - int i = 0; - - void inorder(TreeNode* root) { - if(not root) return; - inorder(root -> left) - v.push_back(root -> val); - inorder(root -> right); +bool comapre(struct meet a, struct meet b) { + if(a.endTime == b.endTime) { + return a.meetID < b.meetID; } + else { + return a.endTime < b.endTime; + } +} - BSTIterator(TreeNode* root) { - inorder(root); - } - - int next() { - return v[i++]; - } + + +vector maximumMeetings(vector &start, vector &end) { + // Write your code here. - bool hasNext() { - return inext(); - * bool param_2 = obj->hasNext(); - */ + // create meeting array of size n + for(int i = 0; i < n; i++) { + meeting[i].meetID = i + 1; + meeting[i].startTime = start[i]; + meeting[i].endTime = end[i]; + } + // Sorting the meeting array in increasing order of end time using customized comparator. + sort(meeting, meeting + n, comapre); + + vector result; + + result.push_back(meeting[0].meetID); + int currentTime = meeting[0].endTime; + + + + // Taking the first meeting of sorted array as our first meeting + for(int i = 1; i < n; i++) { + // If startTime of current meeting is greater than our currentTime + // Then we will perform this meeting and update currentTime with endTime of the meeting + + if(meeting[i].startTime > currentTime) { + result.push_back(meeting[i].meetID); + currentTime = meeting[i].endTime; + } + + } + + return result; + +} diff --git a/maximumSubarraySum.cpp b/maximumSubarraySum.cpp new file mode 100644 index 0000000..3e20d02 --- /dev/null +++ b/maximumSubarraySum.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +int maxSum (int arr[], int n) { + int maxEnding = arr[0], result = arr[0]; + for (int i = 1; i < n; i++) { + maxEnding = max (maxEnding + arr[i], arr[i]); + result = max (maxEnding, result); + } + return result; +} + +int main() { + int n; cin >> n; + int arr[n]; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + int result = maxSum (arr, n); + cout << result << '\n'; + return 0; +} diff --git a/maxsumrectangle.cpp b/maxsumrectangle.cpp deleted file mode 100644 index b4d6693..0000000 --- a/maxsumrectangle.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -int maxSumRectangle(vector>& arr, int n, int m) { - - int curr=0; - int maxSum=0; - - for(int i=0;i +using namespace std; + +void mergeArrays(int arr1[], int arr2[], int n1, + int n2, int arr3[]) +{ + int i = 0, j = 0, k = 0; + + while(i < n1){ + arr3[k++] = arr1[i++]; + } + + + while(j < n2){ + arr3[k++] = arr2[j++]; + } + + + sort(arr3, arr3+n1+n2); +} +int main() +{ + int arr1[] = {1, 3, 5, 7}; + int n1 = sizeof(arr1) / sizeof(arr1[0]); + + int arr2[] = {2, 4, 6, 8}; + int n2 = sizeof(arr2) / sizeof(arr2[0]); + + int arr3[n1+n2]; + mergeArrays(arr1, arr2, n1, n2, arr3); + + cout << "Array after merging" < -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - -/************************************************************ - - Following is the linked list node structure. - - template - class Node { - public: - T data; - Node* next; - - Node(T data) { - next = NULL; - this->data = data; - } - - ~Node() { - if (next != NULL) { - delete next; - } - } - }; - -************************************************************/ - - -Node* sortTwoLists(Node* first, Node* second) { - // Write your code here. - - if(first == NULL) return second; - if(second == NULL) return first; - - Node* head; - - if(first->data <= second->data){ - head = first; - head->next = sortTwoLists(first->next, second); - } - else { - head = second; - head->next = sortTwoLists(first, second->next); - } - - return head; -} - - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - TreeNode* merge(TreeNode* t1, TreeNode* t2) { - - if(t1 == nullptr and t2 == nullptr) - return nullptr; - - if(t1 == nullptr and t2 != nullptr) - return t2; - if(t1 != nullptr and t2 == nullptr) - return t1; - - TreeNode* sum = new TreeNode(t1->val+t2->val); - - sum -> left = merge(t1 -> left, t2 -> left); - sum -> right = merge(t1 -> right, t2 -> right); - - return sum; - - } - - TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { - - return merge(root1, root2); - - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(int array[], int const left, int const mid, + int const right) +{ + auto const subArrayOne = mid - left + 1; + auto const subArrayTwo = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArrayOne], + *rightArray = new int[subArrayTwo]; + + // Copy data to temp arrays leftArray[] and rightArray[] + for (auto i = 0; i < subArrayOne; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArrayTwo; j++) + rightArray[j] = array[mid + 1 + j]; + + auto indexOfSubArrayOne + = 0, // Initial index of first sub-array + indexOfSubArrayTwo + = 0; // Initial index of second sub-array + int indexOfMergedArray + = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (indexOfSubArrayOne < subArrayOne + && indexOfSubArrayTwo < subArrayTwo) { + if (leftArray[indexOfSubArrayOne] + <= rightArray[indexOfSubArrayTwo]) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + } + else { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + } + indexOfMergedArray++; + } + // Copy the remaining elements of + // left[], if there are any + while (indexOfSubArrayOne < subArrayOne) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + indexOfMergedArray++; + } + // Copy the remaining elements of + // right[], if there are any + while (indexOfSubArrayTwo < subArrayTwo) { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + indexOfMergedArray++; + } + delete[] leftArray; + delete[] rightArray; +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(int array[], int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// UTILITY FUNCTIONS +// Function to print an array +void printArray(int A[], int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + auto arr_size = sizeof(arr) / sizeof(arr[0]); + + cout << "Given array is \n"; + printArray(arr, arr_size); + + mergeSort(arr, 0, arr_size - 1); + + cout << "\nSorted array is \n"; + printArray(arr, arr_size); + return 0; +} \ No newline at end of file diff --git a/merge_two_ll.cpp b/merge_two_ll.cpp new file mode 100644 index 0000000..d26e045 --- /dev/null +++ b/merge_two_ll.cpp @@ -0,0 +1,137 @@ +/* C program to merge two sorted linked lists */ +#include +#include +#include + +/* Link list node */ +struct Node +{ + int data; + struct Node* next; +}; + +/* pull off the front node of the source and put it in dest */ +void MoveNode(struct Node** destRef, struct Node** sourceRef); + +/* Takes two lists sorted in increasing order, and splices +their nodes together to make one big sorted list which +is returned. */ +struct Node* SortedMerge(struct Node* a, struct Node* b) +{ + /* a dummy first node to hang the result on */ + struct Node dummy; + + /* tail points to the last result node */ + struct Node* tail = &dummy; + + /* so tail->next is the place to add new nodes + to the result. */ + dummy.next = NULL; + while (1) + { + if (a == NULL) + { + /* if either list runs out, use the + other list */ + tail->next = b; + break; + } + else if (b == NULL) + { + tail->next = a; + break; + } + if (a->data <= b->data) + MoveNode(&(tail->next), &a); + else + MoveNode(&(tail->next), &b); + + tail = tail->next; + } + return(dummy.next); +} + +/* UTILITY FUNCTIONS */ +/* MoveNode() function takes the node from the front of the +source, and move it to the front of the dest. +It is an error to call this with the source list empty. + +Before calling MoveNode(): +source == {1, 2, 3} +dest == {1, 2, 3} + +After calling MoveNode(): +source == {2, 3} +dest == {1, 1, 2, 3} */ +void MoveNode(struct Node** destRef, struct Node** sourceRef) +{ + /* the front source node */ + struct Node* newNode = *sourceRef; + assert(newNode != NULL); + + /* Advance the source pointer */ + *sourceRef = newNode->next; + + /* Link the old dest off the new node */ + newNode->next = *destRef; + + /* Move dest to point to the new node */ + *destRef = newNode; +} + + +/* Function to insert a node at the beginning of the +linked list */ +void push(struct Node** head_ref, int new_data) +{ + /* allocate node */ + struct Node* new_node = + (struct Node*) malloc(sizeof(struct Node)); + + /* put in the data */ + new_node->data = new_data; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +/* Function to print nodes in a given linked list */ +void printList(struct Node *node) +{ + while (node!=NULL) + { + printf("%d ", node->data); + node = node->next; + } +} + +/* Drier program to test above functions*/ +int main() +{ + /* Start with the empty list */ + struct Node* res = NULL; + struct Node* a = NULL; + struct Node* b = NULL; + + /* Let us create two sorted linked lists to test + the functions + Created lists, a: 5->10->15, b: 2->3->20 */ + push(&a, 15); + push(&a, 10); + push(&a, 5); + + push(&b, 20); + push(&b, 3); + push(&b, 2); + + /* Remove duplicates from linked list */ + res = SortedMerge(a, b); + + printf("Merged Linked List is: \n"); + printList(res); + + return 0; +} diff --git a/minCostClimbingStairs.cpp b/minCostClimbingStairs.cpp deleted file mode 100644 index 65b7ce3..0000000 --- a/minCostClimbingStairs.cpp +++ /dev/null @@ -1,106 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - - int minCostClimbingStairs(vector& cost, int idx, vector &memo) { - if(idx == cost.size()-1 or idx == cost.size()-2) - return cost[idx]; - if(memo[idx] != 0) - return memo[idx]; - int x = minCostClimbingStairs(cost, idx+1, memo); - int y = minCostClimbingStairs(cost, idx+2, memo); - - memo[idx] = min(x, y) + cost[idx]; - - return memo[idx]; - } - - int minCostClimbingStairs(vector& cost) { - if(cost.size() == 2) - return min(cost[0], cost[1]); - vector memo(1001); - - int x = minCostClimbingStairs(cost, 0, memo); - int y = minCostClimbingStairs(cost, 1, memo); - - return min(x, y); - } - -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - int n; - cin >> n; - - vector cost(n); - - for(int i = 0; i < n; i++){ - cin >> cost[i]; - } - - Solution ans; - - cout << ans.minCostClimbingStairs(cost) << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int minRefuelStops(int target, int startFuel, vector>& stations) { - int i = 0; - int res; - - priority_queuepq; - - for(res = 0; startFuel < target; res++) { - while(i < stations.size() and stations[i][0] <= startFuel) - pq.push(stations[i++][1]); - if(pq.empty()) return -1; - startFuel += pq.top(), pq.pop(); - } - - return res; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int minSubArrayLen(int target, vector& nums) { - long long sum = 0; - int len = INT_MAX; - - int left = 0; - - for(int i = 0; i < nums.size(); i++) { - sum += nums[i]; - if(sum >= target) len = min(len, i+1); - while(left < nums.size() and (sum - nums[left]) >= target) { - sum -= nums[left]; - left++; - len = min(len, i-left+1); - } - } - - return (len == INT_MAX) ? 0 : len; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - - -class Solution { -public: - string minWindow(string s, string t) { - - int n = s.length(); - int m = t.length(); - - int len = n; - - map mp; - - for(int i = 0; i < m; i++) { - mp[t[i]]++; - } - - int cnt = mp.size(); - - string ans = ""; - - int i = 0; - int j = 0; - - while(j < n) { - if(mp.find(s[j]) != mp.end()) { - mp[s[j]]--; - if(mp[s[j]] == 0) cnt--; - } - if(cnt == 0) { - while(cnt == 0) { - if(mp.find(s[i]) != mp.end() and mp[s[i]] < 0) { - mp[s[i]]++; - i++; - } - - else if(mp.find(s[i]) != mp.end() and mp[s[i]] == 0) - break; - else i++; - } - if(len >= j-i+1) { - ans = s.substr(i, j-i+1); - len = j-i+1; - } - } - j++; - } - - return ans; - - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - int mirrorReflection(int p, int q) { - int m = 1; - int n = 1; - - while (m*p != n*q) { - n++; - m = n*q/p; - } - - if(m%2 == 0 and n%2 == 1) return 0; - if(m%2 == 1 and n%2 == 1) return 1; - if(m%2 == 1 and n%2 == 0) return 2; - - return -1; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - int p, q; - cin >> p >> q; - - Solution ans; - cout << ans.mirrorReflection(p, q) << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& nums) { + int ans = nums.size(); + int mask = 0; + + for(auto i : nums){ + ans = ans ^ i; + ans = ans ^ mask; + mask++; + } + + return ans; + } +}; diff --git a/n queens problem b/n queens problem new file mode 100644 index 0000000..be040a0 --- /dev/null +++ b/n queens problem @@ -0,0 +1,44 @@ +class Solution { +public: + vector > sols; // 2D vector of strings to store the solutions + vector> solveNQueens(int n) { + vector board(n, string(n, '.')); // creating an empty board + solve(board, 0); // calling the recursive function + return sols; + } + bool isSafe(vector& board, int row, int col) { + int n = size(board); + for(int i = 0; i < n; i++) { + // checking if there is a queen in the same column + if(board[i][col] == 'Q') return false; + // checking if there is a queen in the same diagonal (left to right) + if(row - i >= 0 && col - i >= 0 && board[row - i][col - i] == 'Q') return false; + if(row - i >= 0 && col + i < n && board[row - i][col + i] == 'Q') return false; + // No need to traverse more since the lower rows below current row attribute will always be safe. + /* if(row + i < n && col - i >= 0 && board[row + i][col - i] == 'Q') return false; + if(row + i < n && col + i < n && board[row + i][col + i] == 'Q') return false; */ + } + return true; + } + // Recursive Function (solve) - It basically tries all possible placement of queen for the current row & recurses for it's next row + void solve(vector& board, int row) { + // Base condition. + // We reached the last row, so we have a solution so we add it to the solution vector + if(row == size(board)) { + sols.push_back(board); + return; + } + // Try placing a queen on each column for a given row. + // Explore next row by placing Q at each valid column for the current row + for(int col = 0; col < size(board); col++){ + if(isSafe(board, row, col)) { + board[row][col] = 'Q'; // Queen placed on a valid cell + solve(board, row + 1); // Exploring next row + board[row][col] = '.'; // Backtracking to get all possible solutions + } + } + } +}; + +// Time Complexity : O(N!), Since we have N choices in the first row, then N-1 choices in the second row and so on so the overall complexity become O(N!) +// Space Complexity: O(N*N), Just the board and recursive stack space diff --git a/numberOfWeakCharacters.cpp b/numberOfWeakCharacters.cpp deleted file mode 100644 index 485c3f7..0000000 --- a/numberOfWeakCharacters.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - bool sorted(vector& a, vector& b) { - if(a[0] == b[0]) return a[1] > b[1]; - - return a[0] < b[0]; - } - - int numberOfWeakCharacters(vector>& properties) { - sort(properties.begin(), properties.end(), sorted); - int ans = 0, maxDiffVal = INT_MIN; - - int n = properties.size(); - for(int i = n-1; i >= 0; i--) { - if(properties[i][1] < maxDiffVal) { - ans++; - } - if(properties[i][1] > maxDiffVal) { - maxDiffVal = properties[i][1]; - } - } - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { - vector ans; -public: - - int countDigit(int n) { - int cnt = 0; - while(n > 0) { - cnt++; - n = n / 10; - } - - return cnt; - } - - void findNumber(int num, int n, int k) { - if(countDigit(num) == n) { - ans.push_back(num); - return; - } - - for(int i = 0; i <= 9; i++) { - - int l = num % 10; - - if(abs(l - i) == k) { - int number = num*10+i; - findNumber(number, n, k); - } - } - } - - vector numsSameConsecDiff(int n, int k) { - for(int i = 1; i <= 9; i++) { - findNumber(i, n ,k); - } - - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* oddEvenList(ListNode* head) { - ListNode* oddH = nullptr, *oddT = nullptr, *evenH = nullptr, *evenT = nullptr; - int cnt = 1; - - while(head != nullptr) { - if(cnt%2 == 0) { - if(evenH == nullptr){ - evenH = head; - evenT = head; - head = head -> next; - } - - else { - evenT -> next = head; - evenT = evenT -> next; - head = head -> next; - } - } - - else { - if(oddH == nullptr) { - oddH = oddT = head; - - head = head -> next; - } - - else { - oddT -> next = head; - oddT = oddT -> next; - head = head -> next; - } - } - cnt++; - } - - if(oddH == nullptr) { - return evenH; - } - - if(evenH == nullptr) { - return oddH; - } - - evenT -> next = nullptr; - oddT -> next = evenH; - - return oddH; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< + + + + On Off Bulb + + + + +
+
+
+
+
+
+ + + + + diff --git a/orangesRotting.cpp b/orangesRotting.cpp deleted file mode 100644 index 4ac0dea..0000000 --- a/orangesRotting.cpp +++ /dev/null @@ -1,117 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - int orangesRotting(vector>& grid) { - if(grid.empty()) return 0; - - int m = grid.size(), n = grid[0].size(), days = 0, tot = 0, cnt = 0; - - queue> rotten; - - for(int i = 0; i < m; i++) { - for(int j = 0; j < n; j++) { - if(grid[i][j] != 0) tot++; - if(grid[i][j] == 2) rotten.push({i, j}); - } - } - - int dx[4] = {0, 0, 1, -1}; - int dy[4] = {1, -1, 0, 0}; - - while(not rotten.empty()) { - int k = rotten.size(); - - cnt += k; - - while(k--) { - int x = rotten.front().first; - int y = rotten.front().second; - rotten.pop(); - - for(int i = 0; i < 4; i++) { - int nx = x + dx[i]; - int ny = y + dy[i]; - if(nx < 0 or ny < 0 or nx >= m or ny >= n or grid[nx][ny] != 1) continue; - grid[nx][ny] = 2; - rotten.push({nx, ny}); - } - - } - - if(not rotten.empty()) days++; - } - - return tot == cnt ? days : -1; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - vector> pacificAtlantic(vector>& matrix) { - - vector>ans; - if(matrix.size()<1)return ans; - vector>pacific(matrix.size(),vector(matrix[0].size(),0)); - vector>atlantic(matrix.size(),vector(matrix[0].size(),0)); - - for(int col=0;colv(2); - v[0]=i; - v[1]=j; - ans.push_back(v); - } - } - } - - - - return ans; - } - - void fnc(vector>& matrix,int i, int j,int prev,vector>& ocean) - { - if(i<0 || j<0 || i>=matrix.size() || j>=matrix[0].size()) - return; - if(ocean[i][j]==1) - return; - if(matrix[i][j] +using namespace std; + +int binomialCoeff(int n, int k); + + +void printPascal(int n) +{ + for (int line = 0; line < n; line++) + { + + for (int i = 0; i <= line; i++) + cout <<" "<< binomialCoeff(line, i); + cout <<"\n"; + } +} + + +int binomialCoeff(int n, int k) +{ + int res = 1; + if (k > n - k) + k = n - k; + for (int i = 0; i < k; ++i) + { + res *= (n - i); + res /= (i + 1); + } + + return res; +} + + +int main() +{ + int n = 7; + printPascal(n); + return 0; +} + diff --git a/pascalTraingle.cpp b/pascalTraingle.cpp deleted file mode 100644 index 9a98bc5..0000000 --- a/pascalTraingle.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - vector> generate(int numRows) { - vector>rows(numRows); - for(int i = 0; i < numRows; i++) { - for(int j = 0; j <= i; j++) { - rows[i].push_back(j > 0 and j < i ? rows[i-1][j] + rows[i-1][j-1] : 1); - } - } - - return rows; - } -}; - - -int main(int argc, char const *argv[]) -{ - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +#include +using namespace std; + +static const char alphanum[] = +"0123456789" +"!@#$%^&*" +"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +"abcdefghijklmnopqrstuvwxyz"; +int size = sizeof(alphanum) - 1; + +int main() +{ + //password length + int length = 8; + + srand(time(0)); + for (int i = 0; i < length; i++) + { + cout << alphanum[rand() % ::size]; + } + return 0; +} diff --git a/passwordgenerator.py b/passwordgenerator.py new file mode 100644 index 0000000..f3c3373 --- /dev/null +++ b/passwordgenerator.py @@ -0,0 +1,15 @@ +import random + +pass1 = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', + 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', + 't', 'u', 'v', 'x', 'y', 'z', 'A', 'B', 'C', + 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', + 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', + '7', '8', '9', '0', '@', '#', '$', '_', '*', + '.', '!', '(', ')', '%', '^', '/', '|', ' '] +password = " " +for x in range(16): + password = password + random.choice(pass1)[0] + +print('your new password is:\n', password) diff --git a/permutation.cpp b/permutation.cpp deleted file mode 100644 index 965185b..0000000 --- a/permutation.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector> permute(vector& nums) { - - if(nums.size() <= 1) { - return {nums}; - } - - vector> res; - - for(int i = 0; i < nums.size(); i++) { - vector v(nums.begin(), nums.end()); - v.erase(v.begin()+i); - - auto ans = permute(v); - - for(int j = 0; j < ans.size(); j++) { - vector _v = ans[j]; - _v.insert(_v.begin(), nums[i]); - res.push_back(_v); - } - } - - return res; - - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution { -public: - Node* connect(Node* root) { - if(root == NULL) return NULL; - queueq; - q.push(root); - - while(not q.empty()) { - int n = q.size(); - - Node* prev = NULL; - for(int i = 0; i < n; i++) { - auto top = q.front(); - - q.pop(); - - top -> next = prev; - - prev = top; - - if(top -> right) { - q.push(top -> right); - } - - if(top -> left) { - q.push(top -> left); - } - } - } - - return root; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< + +using namespace std; + +int main() + +{ + + int n, i, m=0, flag=0; + + cout << "Enter the Number to check Prime: "; + + cin >> n; + + m=n/2; + + for(i = 2; i <= m; i++) + + { + + if(n % i == 0) + + { + + cout<<"Number is not Prime."< sieve; +void prime(int n){ + sieve.resize(n+1,true); + sieve[0]=sieve[1]=false; + for(int i=2;(long long)i*i<=n;++i){ + if(sieve[i]) + for(int j=i*i;j<=n;j+=i) + sieve[j]=false; + } +} + +int main{ + cout<<"Enter total numbers you wanted to check for prime: "; + int t; + cin>>t; + + // Initialise the sieve upto the maximum number + prime(100005); + while(t--){ + int n; + cin>>n; + if(sieve[n]==true) + cout<<"Number "< +using namespace std; + +bool isPrime(int n) +{ + // Corner case + if (n <= 1) + return false; + + // Check from 2 to n-1 + for (int i = 2; i < n; i++) + if (n % i == 0) + return false; + + return true; +} + +// Driver Program to test above function +int main() +{ + isPrime(11) ? cout << " true\n" : cout << " false\n"; + isPrime(15) ? cout << " true\n" : cout << " false\n"; + return 0; +} diff --git a/prims algo.cpp b/prims algo.cpp new file mode 100644 index 0000000..d22a98d --- /dev/null +++ b/prims algo.cpp @@ -0,0 +1,83 @@ +#include + +using namespace std; + +// Number of vertices in the graph +#define V 5 + +// A utility function to find the vertex with minimum key value, from +// the set of vertices not yet included in MST +int minKey(int key[], bool mstSet[]) +{ + // Initialize min value + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (mstSet[v] == false && key[v] < min) + min = key[v], min_index = v; + + return min_index; +} + +// A utility function to print the constructed MST stored in parent[] +int printMST(int parent[], int n, int graph[V][V]) +{ + cout<<"Edge Weight\n"; + for (int i = 1; i < V; i++) + printf("%d - %d %d \n", parent[i], i, graph[i][parent[i]]); +} + +// Function to construct and print MST for a graph represented using adjacency +// matrix representation +void primMST(int graph[V][V]) +{ + int parent[V]; // Array to store constructed MST + int key[V]; // Key values used to pick minimum weight edge in cut + bool mstSet[V]; // To represent set of vertices not yet included in MST + + // Initialize all keys as INFINITE + for (int i = 0; i < V; i++) + key[i] = INT_MAX, mstSet[i] = false; + + // Always include first 1st vertex in MST. + key[0] = 0; // Make key 0 so that this vertex is picked as first vertex + parent[0] = -1; // First node is always root of MST + + // The MST will have V vertices + for (int count = 0; count < V - 1; count++) + { + // Pick thd minimum key vertex from the set of vertices + // not yet included in MST + int u = minKey(key, mstSet); + + // Add the picked vertex to the MST Set + mstSet[u] = true; + + // Update key value and parent index of the adjacent vertices of + // the picked vertex. Consider only those vertices which are not yet + // included in MST + for (int v = 0; v < V; v++) + + // graph[u][v] is non zero only for adjacent vertices of m + // mstSet[v] is false for vertices not yet included in MST + // Update the key only if graph[u][v] is smaller than key[v] + if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) + parent[v] = u, key[v] = graph[u][v]; + } + + // print the constructed MST + printMST(parent, V, graph); +} + +// driver program to test above function +int main() +{ + + int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, + { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 }, }; + + // Print the solution + primMST(graph); + + return 0; +} \ No newline at end of file diff --git a/pruneTree.cpp b/pruneTree.cpp deleted file mode 100644 index 731ae30..0000000 --- a/pruneTree.cpp +++ /dev/null @@ -1,105 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int helper(TreeNode* root) { - if(root == nullptr) return 0; - - if(root -> left == nullptr and root -> right == nullptr) { - if(root -> val == 0) return 0; - else return 1; - } - - int leftSubTreeOrder = helper(root -> left); - int rightSubTreeOrder = helper(root -> right); - - if(leftSubTreeOrder == 0) root -> left = nullptr; - - if(rightSubTreeOrder == 0) root -> right = nullptr; - - return leftSubTreeOrder + rightSubTreeOrder + (root -> val == 1 ? 1 : 0); - } - - TreeNode* pruneTree(TreeNode* root) { - if(helper(root) == 0) return nullptr; - - return root; - } -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - void dfs(TreeNode *root, vectorfreq, int& cnt) { - if(root == NULL) return; - - freq[root->val]++; - - dfs(root -> left, freq, cnt); - - if(root -> left == NULL and root -> right == NULL) { - int oddCnt = 0; - for(auto x: freq) { - if(x%2 == 1) { - oddCnt++; - } - - } - - if(oddCnt <= 1) { - cnt++; - } - } - - dfs(root -> right, freq, cnt); - } - - int pseudoPalindromicPaths (TreeNode* root) { - vectorfreq(10, 0); - int cnt = 0; - dfs(root, freq, cnt); - - return cnt; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +#include +#include +using namespace std; + +int total_score=0; +int correct_answer = 0; +int hints_used = 0; +string Name[5]; +string level; + +//the main menu view and some additionl functionalities +int main_menu_view() +{ + system("color 3F"); + cout << "\t\t *************************************************************************************" << endl; + cout << "\t\t ***** *****" << endl; + cout << "\t\t ***** H E L L O ! W E L C O M E T O T H E 'Q U I Z L E T' *****" << endl; + cout << "\t\t ***** = = = = = = = = = = = = = = = = = = = = = = = = *****" << endl; + cout << "\t\t ***** = = = = = = = = = = = = *****" << endl; + cout << "\t\t ***** B Y *****" << endl; + cout << "\t\t ***** R U S T A M Z O K I R O V *****" << endl; + cout << "\t\t ***** *****" << endl; + cout << "\t\t *************************************************************************************" << endl; + cout << endl; + + cout << "\t\t\t\t\t\tH O W T O P L A Y\n\n"; + cout << "\t\t1. IN THIS QUIZ GAME YOU WILL BE GIVEN 10 'C++ PROGRAMMING LANGUAGE' RELATED QUESTIONS.\n\n"; + cout << "\t\t2. IF YOU PRESS INCORRECT KEY, THE PROGRAM WILL AGAIN ASK YOU TO INPUT CORRECT VALUE.\n\n"; + cout << "\t\t3. ADDITIONALLY YOU WILL HAVE SOME HINTS WHICH YOU CAN USE FROM the 8TH QUESTION.\n\n"; + cout << "\t\t4. YOU WILL LOSE '5' POINTS FROM YOUR OVERALL SCORE IF YOU WILL USE HINTS.\n\n\n\n"; + cout << "\t\t\t\t\tPRESS THE 'ENTER' KEY TO START A QUIZ... "; + if (cin.get() == '\n') { + system("cls"); + cout << "\t\t\t\t\tI N F O R M A T I O N T A B L E\n\n"; + cout << "What is your name? "; + getline(cin, Name[0]); + cout << "What is your level of C++?"<> level; + cin.clear(); + } while (level != "1"&&level!="2"&&level!="3"); + string Respond; + cout << endl; + cout << "Are you ready to take the Quiz " << Name[0] << " ? Yes = 'Yes'/No = 'Any key'. " << endl; + cout << "Your choice: "; + cin >> Respond; + if (Respond == "yes" || Respond == "Yes") + { + cout << endl; + cout << "OK, Good Like!!! " << endl; + system("cls"); + return 1; + } + else + { + cout << "OK. Goodbye." << endl; + system("exit"); + return 0; + } + } + else + cout << "I meant ONLY the ENTER key... Oh well.\n"; + return 0; +} +//the view for the hints in the corner +void hints() +{ + cout << " ***********************************" << endl; + cout << " ** A: Audience help **" << endl; + cout << " ** B: 50:50 **" << endl; + cout << " ** C: Room for mistake **" << endl; + cout << " ** D: Change the question **" << endl; + cout << " ***********************************" << endl; +} +//questions +void question1() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + cout << "\t\t\t\t\t Q U E S T I O N No. 1"<< endl; + cout << "What is the correct value to return to the operating system upon the successful completion of a program?" << endl; + cout << "[1] -1"<> answer; + //limiting the answers of the user + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "3") + { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + } + else if (answer == "1" || answer == "2" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question1(); + } +} +void question2() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + cout << "\t\t\t\t\t Q U E S T I O N No. 2" << endl; + cout << "What is the only function all C++ programs must contain?" << endl; + cout << "[1] start()" << endl; + cout << "[2] system()" << endl; + cout << "[3] program()" << endl; + cout << "[4] main()" << endl; + string answer; + cout<> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "4") + { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + } + else if (answer == "1" || answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question2(); + } + +} +void question3() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + cout << "\t\t\t\t\t Q U E S T I O N No. 3" << endl; + cout << "Which of the following is a correct comment?" << endl; + cout << "[1] / Comment /" << endl; + cout << "[2] ** Comment **" << endl; + cout << "[3] { Comment }" << endl; + cout << "[4] //comment" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "4") { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + } + else if (answer == "1" || answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question3(); + } +} +void question4() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + cout << "\t\t\t\t\t Q U E S T I O N No. 4" << endl; + cout << "Which of the following is the correct operator to compare two variables?" << endl; + cout << "[1] = =" << endl; + cout << "[2] :=" << endl; + cout << "[3] =" << endl; + cout << "[4] ==" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "4") { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + } + else if (answer == "1" || answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question4(); + } +} +void question5() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + cout << "\t\t\t\t\t Q U E S T I O N No. 5" << endl; + cout << "Which of the following is a complete function?" << endl; + cout << "[1] int funct();" << endl; + cout << "[2] int funct(int x) {return x=x+1;}" << endl; + cout << "[3] void funct(int) {cout<<'Hello'}" << endl; + cout << "[4] void funct(x) {cout<<'Hello'}" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "2") { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + } + else if (answer == "1" || answer == "3" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question5(); + } + +} +void question6() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + cout << "\t\t\t\t\t Q U E S T I O N No. 6" << endl; + cout << "Which is not a proper prototype?" << endl; + cout << "[1] int funct(char x, char y);" << endl; + cout << "[2] double funct(char x)" << endl; + cout << "[3] void funct();" << endl; + cout << "[4] char x();" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "2") + { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + + } + else if (answer == "1" || answer == "3" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question6(); + } +} +void question7() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + cout << "\t\t\t\t\t Q U E S T I O N No. 7" << endl; + cout << "Which of the following is a two-dimensional array?" << endl; + cout << "[1] array anarray[20][20];" << endl; + cout << "[2] int anarray[20][20];" << endl; + cout << "[3] int array[20, 20];" << endl; + cout << "[4] char array[20];" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "2") { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + } + else if (answer == "1" || answer == "3" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question7(); + } +} +void question8() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + hints(); + cout << "\t\t\t\t\t Q U E S T I O N No. 8" << endl; + cout << "Evaluate !(1 && !(0 || 1))." << endl; + cout << "[1] True" << endl; + cout << "[2] False" << endl; + cout << "[3] Unevaluatable" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + //limiting the answers of the user + if (answer == "1" || answer == "2" || answer == "3" ) + { + if (answer == "1") { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + + } + else if (answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + //if cases for the hints + else if (answer == "A" || answer == "a") + { + hints_used++; + cout << endl; + cout << "Audience prediction is... " << endl; + cout << "[1] 42%" << endl; + cout << "[2] 38%" << endl; + cout << "[3] 20%" << endl; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1") { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 5." << endl; + + } + else if (answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + + } + + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "B" || answer == "b") + { + hints_used++; + system("cls"); + cout << "Now you have chance to choose two answers. If one of them will correct you will take 5 points." << endl; + cout << "\t\t\t\t\tQ U E S T I O N No. 8" << endl; + cout << "Evaluate !(1 && !(0 || 1))." << endl; + cout << "[1] True" << endl; + cout << "[2] False" << endl; + cout << "[3] Unevaluatable" << endl; + string answer1, answer2; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR FIRST CHOICE: "; + cin >> answer1; + cout << "\t\t\t\t\tENTER YOUR SECOND CHOICE: "; + cin >> answer2; + if (answer1 == "1" || answer2 == "1") + { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + } + else + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "C" || answer == "c") + { + hints_used++; + system("cls"); + cout << "Now you have chance to answer incorrectly. You will take 5 points for this question." << endl; + cout << "\t\t\t\t\tQ U E S T I O N No. 8" << endl; + cout << "Evaluate !(1 && !(0 || 1))." << endl; + cout << "[1] True" << endl; + cout << "[2] False" << endl; + cout << "[3] Unevaluatable" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + total_score += 5; + correct_answer += 1; + if(answer=="1") + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "D" || answer == "d") + { + hints_used++; + system("cls"); + cout << "\t T H I S I S A N E W Q U E S T I O N. Y O U W I L L G E T 5 P O I N T S. " << endl; + cout << endl; + cout << "When did INHA UNivercity in TAshkent established?." << endl; + cout << "[1] 2014" << endl; + cout << "[2] 1968" << endl; + cout << "[3] 2015" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1") { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + + } + else if (answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question8(); + } +} +void question9() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + hints(); + cout << "\t\t\t\t\t Q U E S T I O N No. 9" << endl; + cout << "What is the result of the program below?" << endl; + cout << " int x = 10; " << endl; + cout << " int y = 70; " << endl; + cout << " x = x + y; " << endl; + cout << " y = x - y; " << endl; + cout << " x = x - y; " << endl; + cout << endl; + cout << "[1] x=70, y=10" << endl; + cout << "[2] x=10, y=70" << endl; + cout << "[3] x=60, y=20" << endl; + cout << "[4] x=20, y=60" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "1") { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + + } + else if (answer == "2" || answer == "3" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "A" || answer == "a") + { + hints_used++; + cout << endl; + cout << "Audience prediction is... " << endl; + cout << "[1] 30%" << endl; + cout << "[2] 25%" << endl; + cout << "[3] 20%" << endl; + cout << "[4] 25%" << endl; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1") { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + + } + else if (answer == "2" || answer == "3" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "B" || answer == "b") + { + hints_used++; + system("cls"); + cout << "Now you have chance to choose two answers. If one of them will correct you will take 5 points." << endl; + cout << "\t\t\t\t\tQ U E S T I O N No. 9" << endl; + cout << "What is the result of the program below?" << endl; + cout << " int x = 10; " << endl; + cout << " int y = 70; " << endl; + cout << " x = x + y; " << endl; + cout << " y = x - y; " << endl; + cout << " x = x - y; " << endl; + cout << endl; + cout << "[1] x=70, y=10" << endl; + cout << "[2] x=10, y=70" << endl; + cout << "[3] x=60, y=20" << endl; + cout << "[4] x=20, y=60" << endl; + string answer1, answer2; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR FIRST CHOICE: "; + cin >> answer1; + cout << "\t\t\t\t\tENTER YOUR SECOND CHOICE: "; + cin >> answer2; + if (answer1 == "1" || answer2 == "1") + { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + } + else + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + } + cout << endl; + system("pause"); + system("cls"); + + } + else if (answer == "C" || answer == "c") + { + hints_used++; + system("cls"); + cout << "Now you have chance to answer incorrectly. You will take 5 points for this question." << endl; + cout << "\t\t\t\t\tQ U E S T I O N No. 9" << endl; + cout << "What is the result of the program below?" << endl; + cout << " int x = 10; " << endl; + cout << " int y = 70; " << endl; + cout << " x = x + y; " << endl; + cout << " y = x - y; " << endl; + cout << " x = x - y; " << endl; + cout << endl; + cout << "[1] x=70, y=10" << endl; + cout << "[2] x=10, y=70" << endl; + cout << "[3] x=60, y=20" << endl; + cout << "[4] x=20, y=60" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + total_score += 5; + correct_answer += 1; + if (answer == "1") + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + cout << endl; + system("pause"); + system("cls"); + + } + else if (answer == "D" || answer == "d") { + hints_used++; + system("cls"); + cout << "\t T H I S I S A N E W Q U E S T I O N. Y O U W I L L G E T 5 P O I N T S. " << endl; + cout << endl; + cout << "When did INHA UNivercity in TAshkent established?." << endl; + cout << "[1] 2014" << endl; + cout << "[2] 1968" << endl; + cout << "[3] 2015" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1") { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + + } + else if (answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question9(); + } +} +void question10() { + cout << " ***********************************" << endl; + cout << " ***** TOTAL SCORE:" << total_score << " *****" << endl; + cout << " ***********************************" << endl; + hints(); + cout << "\t\t\t\t\t Q U E S T I O N No. 10" << endl; + cout << "What will i and j equal after the code below is executed?" << endl; + cout << "int i = 5;" << endl; + cout << "int j = i++;" << endl; + cout << "[1] i=5, j=5 " << endl; + cout << "[2] i=5, j=4" << endl; + cout << "[3] i=5, j=6" << endl; + cout << "[4] ERROR" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1" || answer == "2" || answer == "3" || answer == "4") + { + if (answer == "3") { + total_score += 10; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 10 points out of 10." << endl; + } + else if (answer == "1" || answer == "2" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 10." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "A" || answer == "a") + { + hints_used++; + cout << endl; + cout << "Audience prediction is... " << endl; + cout << "[1] 30%" << endl; + cout << "[2] 25%" << endl; + cout << "[3] 20%" << endl; + cout << "[4] 25%" << endl; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "3") { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + } + else if (answer == "1" || answer == "2" || answer == "4") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "B" || answer == "b") + { + hints_used++; + system("cls"); + cout << "Now you have chance to choose two answers. If one of them will correct you will take 5 points." << endl; + cout << "\t\t\t\t\tQ U E S T I O N No. 10" << endl; + cout << "What will i and j equal after the code below is executed?" << endl; + cout << "int i = 5;" << endl; + cout << "int j = i++;" << endl; + cout << "[1] i=5, j=5 " << endl; + cout << "[2] i=5, j=4" << endl; + cout << "[3] i=5, j=6" << endl; + cout << "[4] ERROR" << endl; + string answer1, answer2; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR FIRST CHOICE: "; + cin >> answer1; + cout << "\t\t\t\t\tENTER YOUR SECOND CHOICE: "; + cin >> answer2; + if (answer1 == "3" || answer2 == "3") + { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + } + else + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + } + cout << endl; + system("pause"); + system("cls"); + } + else if (answer == "C" || answer == "c") + { + hints_used++; + system("cls"); + cout << "Now you have chance to answer incorrectly. You will take 5 points for this question." << endl; + cout << "\t\t\t\t\tQ U E S T I O N No. 10" << endl; + cout << "What will i and j equal after the code below is executed?" << endl; + cout << "int i = 5;" << endl; + cout << "int j = i++;" << endl; + cout << "[1] i=5, j=5 " << endl; + cout << "[2] i=5, j=4" << endl; + cout << "[3] i=5, j=6" << endl; + cout << "[4] ERROR" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + total_score += 5; + correct_answer += 1; + if (answer == "3") + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + cout << endl; + system("pause"); + system("cls"); + + } + else if (answer == "D" || answer == "d") { + hints_used++; + system("cls"); + cout << "\t T H I S I S A N E W Q U E S T I O N. Y O U W I L L G E T '5' P O I N T S. " << endl; + cout << endl; + cout << "When did INHA UNivercity in TAshkent established?." << endl; + cout << "[1] 2014" << endl; + cout << "[2] 1968" << endl; + cout << "[3] 2015" << endl; + string answer; + cout << endl; + cout << "\t\t\t\t\tENTER YOUR CHOICE: "; + cin >> answer; + if (answer == "1") { + total_score += 5; + correct_answer += 1; + cout << "C O R R E C T A N S W E R !!!" << endl; + cout << "You got 5 points out of 5." << endl; + + } + else if (answer == "2" || answer == "3") + { + cout << "W R O N G A N S W E R !!!" << endl; + cout << "You got 0 points out of 5." << endl; + + } + cout << endl; + system("pause"); + system("cls"); + } + else + { + system("cls"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t**** P L E A S E I N P U T C O R R E C T V A L U E ! ****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + question10(); + } +} +//function for the view after game +void after_game() { + system("cls"); + system("color 0A"); + cout << "\t\t*************************************************************************************" << endl; + cout << "\t\t***** *****" << endl; + cout << "\t\t***** C O N G R A T U L A T I O N S ! ! ! *****" << endl; + cout << "\t\t***** = = = = = = = = = = = = = = = = = = = = = = = = *****" << endl; + cout << "\t\t***** = = = = = = = = = = = *****" << endl; + cout << "\t\t***** *****" << endl; + cout << "\t\t***** *****" << endl; + cout << "\t\t***** *****" << endl; + cout << "\t\t*************************************************************************************" << endl; + cout << endl; + cout << "\tTOTAL SCORE: " << total_score << endl; + cout << "\tYOU HAVE ANSWERED FOR '" << correct_answer << "' QUESTIONS OUT OF 10." << endl; + cout << "\tYOU HAVE USED "<> play_again; + if (play_again == "Yes" || play_again == "yes") + { + total_score = 0; + main(); + } + else + cout << "OK, Goodbye! "; +} diff --git a/removeNthFromEnd.cpp b/removeNthFromEnd.cpp deleted file mode 100644 index c0a700f..0000000 --- a/removeNthFromEnd.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* removeNthFromEnd(ListNode* head, int n) { - ListNode* start = new ListNode(); - start->next = head; - ListNode* fast = start; - ListNode* slow = start; - - for(int i = 0; i < n; i++) { - fast = fast->next; - } - - while(fast->next != NULL) { - fast = fast -> next; - slow = slow -> next; - } - - slow -> next = slow -> next -> next; - - return start -> next; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class UnionFind { - unordered_mapparent; - unordered_maprank; - -public: - - int cnt; - - UnionFind(vector> &stones) { - for(vector &stone: stones) { - int row = -(stone[0] + 1); - int col = stone[1] + 1; - parent[row] = row; - parent[col] = col; - } - cnt = parent.size(); - } - - int find(int x) { - if(parent[x] != x) { - parent[x] = find(parent[x]); - } - - return parent[x]; - } - - void union_(int x, int y) { - int xset = find(x); - int yset = find(y); - - if(xset == yset) return; - cnt--; - - if(rank[xset] < rank[yset]) parent[xset] = yset; - else if(rank[xset] > rank[yset]) parent[yset] = xset; - else { - parent[yset] = xset; - rank[xset] = rank[yset] + 1; - } - } - -}; - - -class Solution { -public: - int removeStones(vector>& stones) { - UnionFind uf(stones); - for(vector& stone: stones) { - int row = -(stone[0] + 1); - int col = stone[1] + 1; - uf.union_(row, col); - } - - return stones.size() - uf.cnt; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< |string2|). + + +Example 1: + +Input: +string1 = "computer" +string2 = "cat" +Output: "ompuer" +Explanation: After removing characters(c, a, t) +from string1 we get "ompuer". +Example 2: + +Input: +string1 = "occurrence" +string2 = "car" +Output: "ouene" +Explanation: After removing characters +(c, a, r) from string1 we get "ouene". + + +Your Task: +You dont need to read input or print anything. Complete the function removeChars() which takes string1 and string2 as input parameter and returns the result string after removing characters from string2 from string1. + + +Expected Time Complexity:O( |String1| + |String2| ) +Expected Auxiliary Space: O(K),Where K = Constant +*/ + + +/* +Approach: + +Keep on iterating string1(outer for loop) and set the flag to 0 + +In the inner for loop iterate through string2 + +If any element of string2 matches the corresponding character of string1 then set the flag to 1 + +After completion of the inner for loop, if the flag is not equal to 1 i.e if the corresponding string1 character is not present in string2 then add that character to the resulting string. + +Return the resulting string after the iteration of loops is completed. +*/ + + +//https://practice.geeksforgeeks.org/problems/remove-character3815/1 + + //{ Driver Code Starts +// Initial template for C++ +#include +using namespace std; + + +// } Driver Code Ends +// User function template for c++ +class Solution { + public: + string removeChars(string string1, string string2) { + // code here + string ans; + for (int i = 0; i < string1.length(); i++) + { + int flag = 0; + + for (int j = 0; j> string1; + cin >> string2; + Solution ob; + cout << ob.removeChars(string1,string2) << endl; + + + return 0; +} + +// } Driver Code Ends diff --git a/reorderedPowerOf2.cpp b/reorderedPowerOf2.cpp deleted file mode 100644 index 8c32e10..0000000 --- a/reorderedPowerOf2.cpp +++ /dev/null @@ -1,107 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - bool reorderedPowerOf2(int n) { - int x = pow(10, 9); - map> mp; - - for(int i = 1; i <= x; i = i*2) { - int k = i; - vectorv(10, 0); - while(k) { - int r = k%10; - v[r]++; - k /= 10; - } - mp[i] = v; - } - - vector countOfDigitInN(10, 0); - - while(n) { - int r = n%10; - countOfDigitInN[r]++; - n = n/10; - } - - for(int i = 1; i <= x; i = i*2) { - vector tmp = mp[i]; - bool flag = 0; - for(int j = 0; j <= 9; j++) { - if(tmp[j] != countOfDigitInN[j]) - flag = 1; - } - if(flag == 0) - return 1; - } - return 0; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<0){ + while(x!=0){ + int rem=x%10; + rev=rev*10+rem; + x/=10; + if(rev>INT_MAX||revINT_MAX||rev -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - uint32_t reverseBits(uint32_t n) { - uint32_t ans =0; - - for(int i=0;i<32;i++) - { - uint32_t lsb = n&1; - lsb = lsb<<(31-i); - ans = ans | lsb; - n = n >>1; - } - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int romanToInt(string s) { - long long res = 0; - - for(int i = s.length()-1; i >= 0; i--){ - if(s[i] == 'V') res += 5; - else if(s[i] == 'L') res += 50; - else if(s[i] == 'D') res += 500; - else if(s[i] == 'M') res += 1000; - - if(s[i] == 'I'){ - if(s[i+1] == 'V' or s[i+1] == 'X') res -= 1; - else res += 1; - } - - if(s[i] == 'X'){ - if(s[i+1] == 'L' or s[i+1] == 'C') res -= 10; - else res += 10; - } - - if(s[i] == 'C'){ - if(s[i+1] == 'D' or s[i+1] == 'M') res -= 100; - else res += 100; - } - } - - return res; - - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<> v; - MyCalendar() { - - } - - bool book(int start, int end) { - for(auto x : v) { - if(start < x.second and x.first < end) { - return false; - } - } - - v.push_back({start, end}); - - return true; - } -}; +/****************************************************/ + // Binary tree node class for reference: + class BinaryTreeNode { + public : + T data; + BinaryTreeNode *left; + BinaryTreeNode *right; + BinaryTreeNode(T data) { + this -> data = data; + left = NULL; + right = NULL; + } + }; +/****************************************************/ -class MyCalendar { -public: - - set> v; - MyCalendar() { - - } - - bool book(int start, int end) { - auto it = v.upper_bound({start, end}); - if(it != v.end() and it -> second < end) return false; - - v.insert({end, start}); - - return true; - } -}; +void calcSum(long long &sum, BinaryTreeNode* root, long long CurNum) { + if(not root) return; + long long num = (((CurNum%mod)*10)%mod + root->data)%mod; + if(root->left == NULL and root->right == NULL) { + sum = (sum%mod + num%mod)%mod; + return; + } + calcSum(sum, root->left, num); + calcSum(sum, root->right, num); + return; +} +int rootToLeafSum( BinaryTreeNode* root) { + + + if(not root) return 0; + long long sum = 0; + calcSum(sum, root, 0); + return sum%mod; -/** - * Your MyCalendar object will be instantiated and called as such: - * MyCalendar* obj = new MyCalendar(); - * bool param_1 = obj->book(start,end); - */ +} diff --git a/rotate_bits b/rotate_bits new file mode 100644 index 0000000..89ac4df --- /dev/null +++ b/rotate_bits @@ -0,0 +1,29 @@ +#include +using namespace std; + +int INT_BITS = 32; + + +int leftRotate(int n, unsigned int d) { + return (n << d)|(n >> (INT_BITS - d)); +} + + +int rightRotate(int n, unsigned int d) { + return (n >> d)|(n << (INT_BITS - d)); +} + +int main() { + + int n = 4; + + + int d = 2; + + + cout << "Left Rotation of " << n << " by " << d << " is " << leftRotate(n, d)<<"\n"; + + cout << "Right Rotation of " << n <<" by " << d << " is "<< rightRotate(n, d); + + return 0; +} diff --git a/search2DMatrix.cpp b/search2DMatrix.cpp deleted file mode 100644 index 7775b28..0000000 --- a/search2DMatrix.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - - if(!matrix.size()){ - return false; - } - - int n=matrix.size(); //rows - int m=matrix[0].size(); //cols - - int lo=0; - int h= (n*m)-1; - - while(lo<=h){ - - - int mid= (lo +(h-lo)/2); - if(matrix[mid/m][mid%m]==target){ - return true; - } - - else if(matrix[mid/m][mid%m] < target){ - lo=mid+1; - }else{ - h=mid-1; - } - } - return false; - } - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<>& isConnected, vector& visited) { - visited[s] = true; + int pivot = -1; - vectoradjLs; - for(int i = 0; i < n; i++) { - int x = isConnected[s][i]; - - if(x == 1) - adjLs.push_back(i); + int start = 0; + int end = n-1; + + while(start <= end) { + int mid = (start + end)/2; + + if(arr[mid] > arr[mid+1]) { + pivot = mid; + break; } + else if(arr[mid] >= arr[start]){ + start = mid + 1; + } + else { + end = mid - 1; + } + } + + if(pivot == -1) { + start = 0; + end = n-1; + } + else if(arr[0] > key) { + start = pivot+1; + end = n-1; + } + else { + start = 0; + end = pivot; + } + + while(start <= end) { + int mid = (start + end)/2; - for(auto x: adjLs) { - if(not visited[x]) { - dfs(x, n, isConnected, visited); - } + if(arr[mid] == key){ + return mid; + } + else if(arr[mid] > key) { + end = mid - 1; + } + else{ + start = mid + 1; } } -public: - int findCircleNum(vector>& isConnected) { - int n = isConnected.size(); + return -1; - vectorvisited(n, false); - int cnt = 0; - for(int i = 0; i < n; i++) { - if(not visited[i]) { - cnt++; - dfs(i, n, isConnected, visited); - } - } +} - return cnt; - } -}; @@ -92,6 +109,20 @@ int main(int argc, char const *argv[]) { w(t){ /* Write Code Here */ + int n; + cin >> n; + + int arr[n]; + + for(int i = 0; i < n; i++) { + cin >> arr[i]; + } + + int key; + + cin >> key; + + cout << search(arr, n, key) << endl; } diff --git a/segregate_even_and_odd_nodes_in_LL.cpp b/segregate_even_and_odd_nodes_in_LL.cpp new file mode 100644 index 0000000..f94df00 --- /dev/null +++ b/segregate_even_and_odd_nodes_in_LL.cpp @@ -0,0 +1,153 @@ +/* +GFG PROBLEM: Segregate even and odd nodes in a Linked List + +Given a link list of size N, modify the list such that all the even numbers appear before all the odd numbers in the modified list. +The order of appearance of numbers within each segregation should be same as that in the original list. + +Example 1: + +Input: +N = 7 +Link List: +17 -> 15 -> 8 -> 9 -> 2 -> 4 -> 6 -> NULL + +Output: 8 2 4 6 17 15 9 + +Explanation: 8,2,4,6 are the even numbers +so they appear first and 17,15,9 are odd +numbers that appear later. +*/ + +// CODE: +// { Driver Code Starts +// Initial template for C++ + +#include + +using namespace std; + +struct Node +{ + int data; + struct Node *next; + + Node(int x) + { + data = x; + next = NULL; + } +}; +void printList(Node *node) +{ + while (node != NULL) + { + cout << node->data << " "; + node = node->next; + } + cout << "\n"; +} + +// } Driver Code Ends +// User function template for C++ + +/* +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; +*/ +class Solution +{ +public: + Node *divide(int N, Node *head) + { + // code here + Node *evenHead = NULL; + Node *evenTail = NULL; + Node *oddHead = NULL; + Node *oddTail = NULL; + + Node *temp = head; + while (temp != NULL) + { + if (temp->data % 2 == 0) + { + if (evenHead == NULL) + { + evenHead = temp; + evenTail = temp; + } + else + { + evenTail->next = temp; + evenTail = temp; + } + } + else + { + if (oddHead == NULL) + { + oddHead = temp; + oddTail = temp; + } + else + { + oddTail->next = temp; + oddTail = temp; + } + } + temp = temp->next; + } + + if (evenHead == NULL) + { + return oddHead; + } + if (oddHead == NULL) + { + return evenHead; + } + else + { + evenTail->next = oddHead; + oddTail->next = NULL; + return evenHead; + } + } +}; + +// { Driver Code Starts. + +int main() +{ + // code + int t; + cin >> t; + while (t--) + { + int N; + cin >> N; + int data; + cin >> data; + struct Node *head = new Node(data); + struct Node *tail = head; + for (int i = 0; i < N - 1; ++i) + { + cin >> data; + tail->next = new Node(data); + tail = tail->next; + } + + Solution ob; + Node *ans = ob.divide(N, head); + printList(ans); + } + return 0; +} +// } Driver Code Ends diff --git a/MinimizeMalwareSpreadII.cpp b/shortestPathUnweightedGraph.cpp similarity index 70% rename from MinimizeMalwareSpreadII.cpp rename to shortestPathUnweightedGraph.cpp index ef5fe74..4d3c00d 100644 --- a/MinimizeMalwareSpreadII.cpp +++ b/shortestPathUnweightedGraph.cpp @@ -40,54 +40,69 @@ void file_i_o(){ } -void dfs(int node, set &vis, vector> &graph, int &cnt) { - if(vis.count(node)){ - return; - } - - cnt++; - vis.insert(node); - for(int nbr = 0; nbr < graph.size(); nbr++) { - if(graph[node][nbr] and node != nbr) - dfs(nbr, vis, graph, cnt); + +vector shortestPath( vector> edges , int n , int m, int s , int t){ + + // Write your code here + + vector ADJ[n+1]; + + for(int i = 0; i < m; i++){ + int x, y; + x = edges[i].first; + y = edges[i].second; + ADJ[x].push_back(y); + ADJ[y].push_back(x); } - return; -} + vector visited(n+1, -1); + vector parent(n+1, -1); -int minMalwareSpread(vector>& graph, vector& initial) { - // Write your code here - int n = graph.size(); + visited[s] = 1; - int minCount = n + 1; + queue Q; - int nodeRemove = -1; + Q.push(s); - sort(initial.begin(), initial.end()); + while(Q.size() > 0) { + int curNode = Q.front(); + Q.pop(); - for(int nodeToRemove : initial) { - set vis; - vis.insert(nodeToRemove); - int cnt = 0; - for(int infectedNode : initial) { - dfs(infectedNode, vis, graph, cnt); + for(int nextNode : ADJ[curNode]) { + if(visited[nextNode] == -1) { + visited[nextNode] = 1; + Q.push(nextNode); + parent[nextNode] = curNode; + } } + } - if(minCount > cnt) { - minCount = cnt; - nodeRemove = nodeToRemove; - } + vector path; + int currentNode = t; + + path.push_back(t); + + while(currentNode != s) { + currentNode = parent[currentNode]; + path.push_back(currentNode); } - return nodeRemove; + // path.push_back(s); + + reverse(path.begin(), path.end()); + + return path; + } + + int main(int argc, char const *argv[]) { file_i_o(); diff --git a/singleNumber.cpp b/singleNumber.cpp deleted file mode 100644 index 62a3139..0000000 --- a/singleNumber.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int singleNumber(vector& nums) { - int ans=0; - for(auto x:nums) - ans^=x; - return ans; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< + using namespace std; + + int main() + { + int tc, n , m, k; + scanf("%d",&tc); + while(tc--) { + scanf("%d %d %d",&n,&m,&k); + int ar[n+1] = {0}; + int sum = 0,ans = 0 ; + for(int i = 0; i < n; i++) scanf("%d",&ar[i]); + for(int i = 0, j = 0; i < n*m; i++) { + j = i + 1; + sum = 0; + if(ar[i%n] <= k){ + ans++; + sum = ar[i%n] + ar[j%n]; + + while(j < n*m and sum <= k) { + ans++;j++; + sum += ar[j%n]; + } + } + } + cout << ans << endl; + } + return 0; + } \ No newline at end of file diff --git a/single_num_2.cpp b/single_num_2.cpp new file mode 100644 index 0000000..f7eb38f --- /dev/null +++ b/single_num_2.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector singleNumber(vector& nums) { + int x=0,x1=0,x2=0,pos=-1; + for(int i=0;i vect; + vect.push_back(x1); + vect.push_back(x2); + return vect; + } +}; \ No newline at end of file diff --git a/sortList.cpp b/sortList.cpp deleted file mode 100644 index de1ab2c..0000000 --- a/sortList.cpp +++ /dev/null @@ -1,157 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - - - ListNode* sortList(ListNode* head) { - if(head == NULL || head ->next == NULL) - return head; - - - ListNode *temp = NULL; - ListNode *slow = head; - ListNode *fast = head; - - //middle of linked list - while(fast != NULL && fast -> next != NULL){ - temp = slow; - slow = slow->next; - fast = fast ->next ->next; - - } - temp -> next = NULL; - - ListNode* l1 = sortList(head); //2 - ListNode* l2 = sortList(slow); //1 - - return mergeTwoLists(l1, l2); - - } - - ListNode* mergeTwoLists(ListNode* head1, ListNode* head2) { - ListNode* fh = nullptr; - ListNode* ft = nullptr; - - while(head1 != nullptr and head2 != nullptr) { - - if(fh == nullptr and ft == nullptr) { - - if(head1 -> val > head2 -> val) { - fh = head2; - ft = head2; - head2 = head2 -> next; - } - - else { - fh = head1; - ft = head1; - head1 = head1 -> next; - } - - } - - if(head1 and head2) { - - if(head1 -> val < head2 -> val) { - ft -> next = head1; - ft = ft -> next; - head1 = head1 -> next; - } - - else { - ft -> next = head2; - ft = ft -> next; - head2 = head2 -> next; - } - } - - } - - if(head1 != nullptr) ft -> next = head1; - if(head2 != nullptr) ft -> next = head2; - - return fh; - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<& stack, int current) { + if(stack.empty() or current > stack.top()) { + stack.push(current); + return; + } + + int top = stack.top(); + stack.pop(); + + sortedInsert(stack, current); + stack.push(top); +} + +void sortStack(stack &stack) { + // Write your code here + if(stack.empty()) return; + int top = stack.top(); + stack.pop(); -class Solution { -public: + sortStack(stack); - int combinationSum4(vector& nums, int target) { - - vectordp(target+1, 0); - dp[0] = 1; + sortedInsert(stack, top); - for(int i = 1; i <= target; i++) { - for(auto x : nums) { - if(x <= i) - dp[i] += dp[i-x]; - } - } +} - return dp[target]; - } -}; diff --git a/sortedArrayToBST.cpp b/sortedArrayToBST.cpp deleted file mode 100644 index 774d61f..0000000 --- a/sortedArrayToBST.cpp +++ /dev/null @@ -1,105 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* sortedArrayToBST(vector& nums) { - - if(nums.size() == 0) return nullptr; - - return bst(nums, 0, nums.size()-1); - } - - TreeNode* bst(vector& nums, int left, int right) { - if(left > right) return nullptr; - - int mid = left + (right - left)/2; - - TreeNode* node = new TreeNode(nums[mid]); - - node -> left = bst(nums, left, mid - 1); - node -> right = bst(nums, mid + 1, right); - - return node; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +struct Element +{ + int i; + int j; + int x; +}; +struct Sparse +{ + int m; + int n; + int num; + struct Element *ele; +}; +void create(struct Sparse *s) +{ + int i; + printf("Eneter Dimensions"); + scanf("%d%d", &s->m, &s->n); + printf("Number of non-zero"); + scanf("%d", &s->num); + s->ele = (struct Element *)malloc(s->num * sizeof(struct Element)); + printf("Eneter non-zero Elements"); + for (i = 0; i < s->num; i++) + scanf("%d%d%d", &s->ele[i].i, &s->ele[i].j, &s->ele[i].x); +} +void display(struct Sparse s) +{ + int i, j, k = 0; + for (i = 0; i < s.m; i++) + { + for (j = 0; j < s.n; j++) + { + if (i == s.ele[k].i && j == s.ele[k].j) + printf("%d ", s.ele[k++].x); + else + printf("0 "); + } + printf("\n"); + } +} +struct Sparse *add(struct Sparse *s1, struct Sparse *s2) +{ + struct Sparse *sum; + int i, j, k; + i = j = k = 0; + if (s1->n != s2->n && s1->m != s2->m) + return NULL; + sum = (struct Sparse *)malloc(sizeof(struct Sparse)); + sum->ele = (struct Element *)malloc((s1->num + s2->num) * sizeof(struct Element)); + while (i < s1->num && j < s2->num) + { + if (s1->ele[i].i < s2->ele[j].i) + sum->ele[k++] = s1->ele[i++]; + else if (s1->ele[i].i > s2->ele[j].i) + sum->ele[k++] = s2->ele[j++]; + else + { + if (s1->ele[i].j < s2->ele[j].j) + sum->ele[k++] = s1->ele[i++]; + else if (s1->ele[i].j > s2->ele[j].j) + sum->ele[k++] = s2->ele[j++]; + else + { + sum->ele[k] = s1->ele[i]; + sum->ele[k++].x = s1->ele[i++].x + s2->ele[j++].x; + } + } + } + for (; i < s1->num; i++) + sum->ele[k++] = s1->ele[i]; + for (; j < s2->num; j++) + sum->ele[k++] = s2->ele[j]; + sum->m = s1->m; + sum->n = s1->n; + sum->num = k; + return sum; +} +int main() +{ + struct Sparse s1, s2, *s3; + create(&s1); + create(&s2); + s3 = add(&s1, &s2); + printf("First Matrix\n"); + display(s1); + printf("Second Matrix\n"); + display(s2); + printf("Sum Matrix\n"); + display(*s3); + return 0; +} \ No newline at end of file diff --git a/spiralOrder.cpp b/spiralOrder.cpp deleted file mode 100644 index 1ce409e..0000000 --- a/spiralOrder.cpp +++ /dev/null @@ -1,117 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector spiralOrder(vector>& matrix) { - - int top = 0; - int bottom = matrix.size()-1; - int left = 0; - int right = matrix[0].size()-1; - vector ans; - - while(top <= bottom and left <= right) { - for(int i = left; i <= right; i++) { - ans.push_back(matrix[top][i]); - } - top++; - for(int i = top; i <= bottom; i++) { - ans.push_back(matrix[i][right]); - } - right--; - if(top <= bottom) { - for(int i = right; i >= left; i--) { - ans.push_back(matrix[bottom][i]); - } - bottom--; - } - if(left <= right) { - for(int i = bottom; i >= top; i--) { - ans.push_back(matrix[i][left]); - } - left++; - } - } - - return ans; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - vector> matrix = { - {1,2,3},{4,5,6},{7,8,9} - }; - - Solution s; - vector ans; - - ans = s.spiralOrder(matrix); - - for(int i = 0; i < ans.size(); i++) { - cout << ans[i] << " "; - } - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +int main() +{ + int i,j,k,l,m,n,o=2,a,b,c,d,g,h; + printf("enter the last digit of square"); + scanf("%d",&n); + b=n-1; + for(i=n;i>=1;i--) + { + m=n; + for(l=1;l<=n-i;l++) + { + printf("%d ",m); + m--; + } + for(j=1;j<=2*i-1;j++) + { + printf("%d ",i); + } + o=i+1; + for(k=1;k<=n-i;k++) + { + printf("%d ",o); + o++; + } + printf("\n"); + } + for(a=1;a<=b;a++) + { + d=n; + for(c=1;c<=b-a;c++) + { + printf("%d ",d); + d--; + } + for(g=1;g<=2*a+1;g++) + { + printf("%d ",a+1); + } + for(h=1;h<=b-a;h++) + { + printf("%d ",a+h+1); + } + + printf("\n"); + } +return 0; +} diff --git a/stack_next_greater_element.cpp b/stack_next_greater_element.cpp new file mode 100644 index 0000000..e99d737 --- /dev/null +++ b/stack_next_greater_element.cpp @@ -0,0 +1,33 @@ +// https://www.hackerrank.com/contests/second/challenges/next-greater-element/problem +// problem + + +#include +using namespace std; + +int main() { + int n; + cin>>n; + int nums[n]; + for(int i=0;i>nums[i]; + } + int nge[n]; + for(int i=0;ist; + for (int i = n - 1; i >= 0; i--) { + while (!st.empty() && st.top() <= nums[i]) { + st.pop(); + } + + if (i < n) { + if (!st.empty()) + nge[i] = st.top(); + } + st.push(nums[i]); + } + for(int i=0;i +int main() +{ + int a,b,mod=5,k,i,z,c; + a=1; + printf("\n\n\n"); + while(a<=6) + { + printf("\t\t"); + b=0; + printf(" "); + while(b<6-a) + { + printf(" "); + b=b+1; + } + b=0; + while(b0;z--){ + printf(" "); + } + for(k;k>=0;k--){ + printf("* "); + } + printf("\n"); + i = i+1; + b = b-2; + a = a+1; + } + while(mod>=0){ + printf("\t\t"); + z=mod+3; + while(z>0){ + printf(" "); + z = z-1; + } + printf(" "); + for(k=1;k<=mod;k++){ + printf("* "); + } + for(i=1;i<=2*(a-2*mod);i++){ + printf(" "); + } + for(k=1;k<=mod;k++){ + printf("* "); + } + printf("\n"); + mod=mod-1; + a = a+1; + } + return 0; +} diff --git a/strongnum.cpp b/strongnum.cpp new file mode 100644 index 0000000..a96c3a9 --- /dev/null +++ b/strongnum.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; + +// function to calculate factorial +int factorial(int n){ + int fact = 1; + + for(int i = 1; i <= n; i++) + fact = fact * i; + + return fact; +} + +int Strongnum(int num){ + + int digit, sum = 0; + int temp = num; + + // calculate 1! + 4! + 5! + while(temp!=0){ + digit = temp % 10; + + sum = sum + factorial(digit); + temp /= 10; + } + + + return sum == num; + +} +int main () +{ + int num = 120; + + if(Strongnum(num)) + cout << num << " is Strong Number"; + else + cout << num << " is Not Strong Number"; + +} diff --git a/subArraySumK.cpp b/subArraySumK.cpp deleted file mode 100644 index 7134d3f..0000000 --- a/subArraySumK.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - int subarraySum(vector& nums, int k) { - int count = 0; - int sum = 0; - mapmp; - - for(int i = 0; i > n; - vector nums(n); - int k; - - for(int i = 0; i < n; i++){ - cin >> nums[i]; - } - - cin >> k; - - Solution s; - - int result = s.subarraySum(nums, k); - - cout << result << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; +class Solution { +public: + bool isRow(vector>& board,int row,char num,int COLS){ + for(int i =0; i < COLS;i++){ + if(board[row][i] == num) return false; + } + return true; + } + bool isCol(vector>& board,int col,char num,int ROWS){ + for(int i =0;i < ROWS;i++){ + if(board[i][col] == num) return false; + } + return true; + } + bool isGrid(vector>& board,int row,int col,char num,int ROWS,int COLS){ + //starting row and starting column of that specific 3 x 3 grid + int rowfactor = row - (row%3); + int colfactor = col - (col%3); + for(int i =0 ; i < 3;i++){ + for(int j =0; j < 3;j++){ + int newrow = rowfactor + i; + int newcol = colfactor + j; + if(board[newrow][newcol] == num) return false; + } + } + return true; + } + bool check(vector>& board,int row,int col,char num,int ROWS,int COLS){ + //1.check in row Each of the digits 1-9 must occur exactly once in each row. + //2.check in col Each of the digits 1-9 must occur exactly once in each column. + //3.check in grid Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. + if(isRow(board,row,num,COLS) && isCol(board,col,num,ROWS) && isGrid(board,row,col,num,ROWS,COLS)){ + return true; + } + return false; + } + bool isEmpty(vector>& board,int ROWS,int COLS,int &row,int &col){ + for(int i =0 ; i < ROWS;i++){ + for(int j =0; j < COLS;j++) { + if(board[i][j] == '.') { + row = i; + col = j; + return true; + } + } + } + return false; + } + + bool solve(vector>& board,int ROWS,int COLS){ + //base case when there is no empty space in board + int row ,col; + if(!isEmpty(board,ROWS,COLS,row,col)) return true; + for(int i =1; i <= 9;i++){ + bool isPlacable = check(board,row,col,(i+48),ROWS,COLS); + if(isPlacable){ + board[row][col] = (char)(i+48); + if(solve(board,ROWS,COLS)) return true; + board[row][col] = '.'; + } + } + return false; + } + void solveSudoku(vector>& board) { + int ROWS = board.size(); + int COLS = board[0].size(); + solve(board,ROWS,COLS); + } +}; \ No newline at end of file diff --git a/symmetricTree.cpp b/symmetricTree.cpp deleted file mode 100644 index 4d20e33..0000000 --- a/symmetricTree.cpp +++ /dev/null @@ -1,104 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - bool isSymmetric(TreeNode* root) { - return root == nullptr or isSymmetricHelp(root -> left, root -> right); - } - - bool isSymmetricHelp(TreeNode* left, TreeNode* right) { - if(left == nullptr or right == nullptr) - return left == right; - - if(left -> val != right -> val) - return false; - - return isSymmetricHelp(left -> left, right -> right) and isSymmetricHelp(left -> right, right -> left); - } -}; - - - - - - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +int main() +{ + printf("Table Program (Using Loop) \n\n\n"); + printf("Enter A Number That You want the Table : \n"); + int num; + scanf("%d", &num); + + for (int i = 1; i <= 10; i++) + { + printf("%d * %d = %d \n", num, i, num * i); + } +} diff --git a/taskScheduler.cpp b/taskScheduler.cpp deleted file mode 100644 index 7e39cc3..0000000 --- a/taskScheduler.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - -class Solution { -public: - int leastInterval(vector& tasks, int n) { - unordered_map< char, int> freq; - - for(char c : tasks) { - freq[c]++; - } - - priority_queue pq; - - for(auto c : freq) { - pq.push(c.second); - } - - int result = 0; - - while(not pq.empty()) { - int time = 0; - - vector temp; - - for(int i = 0; i < n + 1; i++) { - if(not pq.empty()){ - temp.push_back(pq.top() - 1); - pq.pop(); - time++; - } - } - - for(auto t : temp){ - if(t) pq.push(t); - } - - result += pq.empty() ? time : n+1; - } - - return result; - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; +class Solution +{ +public: + vector findArray(vector &A) + { + for (int i = A.size() - 1; i > 0; --i) + A[i] ^= A[i - 1]; + return A; + } +}; + +int main() +{ + Solution b; + vector arr = {5, 2, 0, 3, 1}; + cout << b.findArray(arr) << endl; + return 0; +} \ No newline at end of file diff --git a/threeSumClosest.cpp b/threeSumClosest.cpp deleted file mode 100644 index 7f10479..0000000 --- a/threeSumClosest.cpp +++ /dev/null @@ -1,107 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int threeSumClosest(vector& nums, int target) { - - sort(nums.begin(), nums.end()); - int diff = INT_MAX; - int ans = 0; - - for(int i = 0; i < nums.size(); i++) { - int first = nums[i]; - - int start = i+1; - int end = nums.size() -1; - - while(start < end) { - - if(first + nums[start] + nums[end] == target) return target; - - else if(abs(first + nums[start] + nums[end] - target) < diff) { - diff = abs(first + nums[start] + nums[end] - target); - ans = first + nums[start] + nums[end]; - } - - if(first + nums[start] + nums[end] > target) end--; - else start++; - } - } - - return ans; - - } -}; - - - - - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - - - -class Solution { -public: - vector topKFrequent(vector& nums, int k) { - unordered_map counts; - priority_queue, vector>, greater>> min_heap; - - for(auto i : nums) { - counts[i]++; - } - - for(auto & i : counts) { - min_heap.push({i.second, i.first}); - if(min_heap.size() > k) - min_heap.pop(); - } - - vector res; - while(k--) { - res.push_back(min_heap.top().second); - min_heap.pop(); - } - - return res; - - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector topKFrequent(vector& words, int k) { - unordered_map m; - - for(auto &w : words) { - m[w]++; - } - - struct Comp { - bool operator()(pair &a, pair &b) { - return (a.second > b.second) or (a.second == b.second and a < b); - } - }; - - using Node = pair; //Word, Freq - priority_queue, Comp> pq; - - for(auto &p : m) { - pq.push(p); - if(pq.size() > k){ - pq.pop(); - } - } - - vector ans; - - while(not pq.empty()) { - ans.push_back(pq.top().first); - pq.pop(); - } - - reverse(ans.begin(), ans.end()); - - return ans; - } -}; - - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +using namespace std; + + +int maxWater(int arr[], int n) +{ + + int res = 0; + + + for (int i = 1; i < n - 1; i++) { + + + int left = arr[i]; + for (int j = 0; j < i; j++) + left = max(left, arr[j]); + + + int right = arr[i]; + for (int j = i + 1; j < n; j++) + right = max(right, arr[j]); + + + res = res + (min(left, right) - arr[i]); + } + + return res; +} + + +int main() +{ + int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; + int n = sizeof(arr) / sizeof(arr[0]); + + cout << maxWater(arr, n); + + return 0; +} diff --git a/tree.c b/tree.c new file mode 100644 index 0000000..acb8458 --- /dev/null +++ b/tree.c @@ -0,0 +1,187 @@ +/*BINARY SEARCH TREE(BST) +Operations: +Insertion in BST +Displaying in inorder, postorder and preorder +Counting nodes +Deletion of node */ +#include +#include +typedef struct node +{ + struct node *left; + int info; + struct node *right; +}treetype; +void insert(treetype **root, int data) +{ + if (*root == NULL) + { + treetype *newnode = (treetype *)malloc(sizeof(treetype)); + if (newnode == NULL) + printf("Memory not allocated\n"); + else + { + newnode->left = NULL; + newnode->info = data; + newnode->right = NULL; + } + *root = newnode; + return; + } + if (data < (*root)->info) + insert(&(*root)->left, data); + else + insert(&(*root)->right, data); +} +void inorder_display(treetype *root) +{ + if (root == NULL) + return; + inorder_display(root->left); + printf("%d ", root->info); + inorder_display(root->right); +} +void preorder_display(treetype *root) +{ + if (root == NULL) + return; + printf("%d ", root->info); + preorder_display(root->left); + preorder_display(root->right); +} +void postorder_display(treetype *root) +{ + if (root == NULL) + return; + postorder_display(root->left); + postorder_display(root->right); + printf("%d ", root->info); +} +void fullcount(treetype *root, int *p) +{ + if (root == NULL) + return; + else + { + if (root) + *p = *p + 1; + fullcount(root->left, p); + fullcount(root->right, p); + } +} +void parentcount(treetype *root, int *p) +{ + if (root == NULL) + return; + else + { + if (root->left && root->right) + *p = *p + 1; + parentcount(root->left, p); + parentcount(root->right, p); + } +} +void leafcount(treetype *root, int *p) +{ + if (root == NULL) + return; + else + { + if (root->left == NULL && root->right == NULL) + *p = *p + 1; + leafcount(root->left, p); + leafcount(root->right, p); + } +} + +treetype *inordersuccessor(treetype *p) +{ + treetype *temp = p; + while (temp && temp->left != NULL) + temp = temp->left; + return temp; +} +void delete (treetype **root, int key) +{ + if (*root == NULL) + return; + else if (key < (*root)->info) + delete (&(*root)->left, key); + else if (key > (*root)->info) + delete (&(*root)->right, key); + else + { + if ((*root)->left == NULL && (*root)->right == NULL) + { + free(*root); + *root = NULL; + } + else if ((*root)->left == NULL) + { + treetype *temp = *root; + *root = (*root)->right; + free(temp); + } + else if ((*root)->right == NULL) + { + treetype *temp = *root; + *root = (*root)->left; + free(temp); + } + else + { + treetype *temp = inordersuccessor((*root)->right); + (*root)->info = temp->info; + delete (&(*root)->right, temp->info); + } + } +} +int main() +{ + treetype *root = NULL; + int data, ch, c = 0, c1 = 0, c2 = 0, key; + do + { + printf("Enter 1 for insert 2 for display 3 for node count 4 for deletion and 5 for exit: "); + scanf("%d", &ch); + switch (ch) + { + case 1: + printf("Enter data to insert in binary search tree: "); + scanf("%d", &data); + insert(&root, data); + break; + case 2: + preorder_display(root); + printf("\n"); + inorder_display(root); + printf("\n"); + postorder_display(root); + printf("\n"); + break; + case 3: + fullcount(root, &c); + printf("Number of nodes are: %d\n", c); + parentcount(root, &c1); + printf("Number of parent nodes are: %d\n", c1); + leafcount(root, &c2); + printf("Number of leaf nodes are: %d\n", c2); + break; + case 4: + if (root == NULL) + printf("Nothing to delete\n"); + else + { + printf("Enter the value you want to delete:"); + scanf("%d", &key); + delete (&root, key); + } + break; + case 5: + exit(0); + break; + } + } while (1); + + return 0; +} diff --git a/triangle.cpp b/triangle.cpp deleted file mode 100644 index 9d7a70b..0000000 --- a/triangle.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int minimumTotal(vector>& triangle) { - int n = triangle.size(); - - vector minlen(triangle.back()); - - for(int i = n-2; i >= 0; i--) { - for(int j = 0; j <= i; j++) { - minlen[j] = min(minlen[j],minlen[j+1]) + triangle[i][j]; - } - } - - return minlen[0]; - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< +#include +using namespace std; + +struct Node { + Node * links[2]; + + bool containsKey(int ind) { + return (links[ind] != NULL); + } + Node * get(int ind) { + return links[ind]; + } + void put(int ind, Node * node) { + links[ind] = node; + } +}; +class Trie { + private: Node * root; + public: + Trie() { + root = new Node(); + } + + public: + void insert(int num) { + Node * node = root; + // cout << num << endl; + for (int i = 31; i >= 0; i--) { + int bit = (num >> i) & 1; + if (!node -> containsKey(bit)) { + node -> put(bit, new Node()); + } + node = node -> get(bit); + } + } + public: + int findMax(int num) { + Node * node = root; + int maxNum = 0; + for (int i = 31; i >= 0; i--) { + int bit = (num >> i) & 1; + if (node -> containsKey(!bit)) { + maxNum = maxNum | (1 << i); + node = node -> get(!bit); + } else { + node = node -> get(bit); + } + } + return maxNum; + } +}; +int maxXOR(int n, int m, vector < int > & arr1, vector < int > & arr2) { + Trie trie; + for (int i = 0; i < n; i++) { + trie.insert(arr1[i]); + } + int maxi = 0; + for (int i = 0; i < m; i++) { + maxi = max(maxi, trie.findMax(arr2[i])); + } + return maxi; +} +int main() { + vector < int > arr1 = {6, 8}; + vector < int > arr2 = {7, 8, 2}; + int n = 2, m = 3; + cout << maxXOR(n, m, arr1, arr2) << endl; + return 0; +} diff --git a/two sum.cpp b/two sum.cpp new file mode 100644 index 0000000..e0cb799 --- /dev/null +++ b/two sum.cpp @@ -0,0 +1,52 @@ +// Link for problem +https://leetcode.com/problems/two-sum/ + +// Map based approach +class Solution { +public: + vector twoSum(vector& nums, int target) { + map m; + for(int i=0; i twoSum(vector& nums, int target) { + int n=nums.size(); + vector ans; + + vector> arr(n); + for(int i=0;itarget) + --j; + // If sum of elements at i and j is smaller than the target then we have to increase the ith element + else + ++i; + } + + return ans; + } +}; \ No newline at end of file diff --git a/twoSum.cpp b/twoSum.cpp deleted file mode 100644 index 1107718..0000000 --- a/twoSum.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - vector twoSum(vector& nums, int target) { - vector arr(2,-1); - for (int i = 0; i < nums.size(); i++){ - for(int j = i+1; j < nums.size(); j++){ - if(nums[i]+nums[j] == target){ - arr[0] = i; - arr[1] = j; - } - } - } - - return arr; - } -}; - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - - - - - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< + +using namespace std; + +class Solution { +public: + vector twoSum(vector& nums, int target) { + + + + int n=nums.size(); + + unordered_setst; +// for(int i=0;ians; + for(int i=0;i -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -class Solution { -public: - int uniqueMorseRepresentations(vector& words) { - - string table[] = { - ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.." - }; - - set differentTranformations; - - // convert each word into a transformation - - for(int i = 0; i < words.size(); i++) { - string transformedString = ""; - - for(char &curChar : words[i]) { - transformedString += table[(int)curChar - (int)97]; - } - - differentTranformations.insert(transformedString); - } - - // get only the difference transformation - - - // return the total number of different transformation - return differentTranformations.size(); - } -}; - - - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - -class Solution { -public: - - int f(int i, int j, vector> &dp) { - if(i == 0 and j == 0) return 1; - if(i < 0 or j < 0) return 0; - - if(dp[i][j] != -1) return dp[i][j]; - - int up = f(i-1, j, dp); - int left = f(i, j-1, dp); - - return dp[i][j] = up+left; - } - - int uniquePaths(int m, int n) { - vector> dp(m, vector(n, -1)); - return f(m-1, n-1, dp); - } -}; - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - int m, n; - cin >> m >> n; - - Solution result; - cout << result.uniquePaths(m, n) << endl; - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "< &freq) + { + for(int i=0;i freq(26); + for(auto ch:s) + { + freq[ch-'a']++; + } + + stack st; + string ans = ""; + + for(auto ch:s) + { + st.push(ch); + freq[ch-'a']--; + //bhai terse chota koi nahi h ans me add hoja -> st ka top , min in freq se bhi minimum hai + while(!st.empty() && st.top()<=getMinChar(freq)) + { + ans.push_back(st.top()); + st.pop(); + } + + } + + + while(!st.empty()) + { + ans.push_back(st.top()); + st.pop(); + } + + + return ans; + } +}; diff --git a/validAnagram.js b/validAnagram.js deleted file mode 100644 index f4ee65d..0000000 --- a/validAnagram.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @param {string} s - * @param {string} t - * @return {boolean} - */ -var isAnagram = function(s, t) { - if(s.length != t.length) return false; - - const count = {} - - const N = s.length - for(let i = 0; i < N; i++) { - if(!count[s[i]]) count[s[i]] = 0 - if(!count[t[i]]) count[t[i]] = 0 - - count[s[i]]++ - count[t[i]]-- - } - - /*console.log(s, ":", sCount) - console.log(t, ":", tCount)*/ - for(let ch in count) { - if(count[ch] !== 0) return false; - } - return true; -} \ No newline at end of file diff --git a/verticalTraversal.cpp b/verticalTraversal.cpp deleted file mode 100644 index ff89d0f..0000000 --- a/verticalTraversal.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include -#include -#include -using namespace __gnu_pbds; -using namespace std; -#define ff first -#define ss second -#define endl "\n" -#define ll long long -#define ld long double -#define loop(a, b, c) for(ll (a) = (b); (a)<=(c); (a)++) -#define looprev(a, b, c) for(ll (a) = (b); (a)>=(c); (a)--) -#define pb push_back -#define mp make_pair -#define pii pair -#define vi vector -#define mii map -#define ump unordered_map -#define pqb priority_queue -#define pqs priority_queue > -#define setbits(x) __builtin_popcountll(x) -#define zrobits(x) __builtin_ctzll(x) -#define mod 1000000007 -#define inf 1e18 -#define ps(x, y) fixed<>x; while(x--) -// mt19937 rng(chrono::steady_clock::now,time_since_epoch(),count()); -typedef tree, null_type, less>, rb_tree_tag, tree_order_statistics_node_update> pbds; - - -void file_i_o(){ - ios_base::sync_with_stdio(0); - cin.tie(0); - cout.tie(0); - /* #ifndef ONLINE_JUDGE - freopen("input.txt", "r", stdin); - freopen("output.txt", "w", stdout); - #endif */ -} - - - - -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector> verticalTraversal(TreeNode* root) { - map>> nodes; - - queue>> todo; - - todo.push({root, {0, 0}}); - - while(not todo.empty()) { - auto p = todo.front(); - - todo.pop(); - - TreeNode* node = p.first; - int x = p.second.first, y = p.second.second; - - nodes[x][y].insert(node -> val); - - if(node -> left) { - todo.push({node -> left, {x - 1, y + 1}}); - } - - if(node -> right) { - todo.push({node -> right, {x + 1, y + 1}}); - } - - } - - vector> ans; - - for(auto p : nodes) { - vector col; - for(auto q: p.second) { - col.insert(col.end(), q.second.begin(), q.second.end()); - } - ans.push_back(col); - } - - return ans; - - } -}; - - - - -int main(int argc, char const *argv[]) { - - file_i_o(); - - clock_t start, end; - start = clock(); - - w(t){ - - /* Write Code Here */ - - } - - end = clock(); - - double time_taken=double(end-start)/double(CLOCKS_PER_SEC); - cerr<<"\nTime : "<