diff --git a/data_structures/linked_list/circular_linked_list.c b/data_structures/linked_list/circular_linked_list.c index 6d923ae705..8668ea745f 100644 --- a/data_structures/linked_list/circular_linked_list.c +++ b/data_structures/linked_list/circular_linked_list.c @@ -1,155 +1,154 @@ -/* Circularly Linked List (Basic Operations) - Program to create a Circularly linked list abstract data type and perform various operations on it (Variable first and last declared globally) */ - -#include -#include -#include -#define NULL 0 - -/* Assume that the data portion of each node consists of ONLY an integer.*/ -struct node -{ - int data ; - struct node *next ; -} ; - -struct node *first=NULL ; -struct node *last=NULL ; -/* first and last are global variables and need not be passed to any function. Any changes made to variables first and last by any of the functions in the program will be reflected in the entire program */ - -/* This function is responsible for creating the Circularly Linked List right from the BEGINNING. */ -void create() -{ - int i , n ; - struct node *pnode , *p ; - - printf("Enter the number of nodes required:\n") ; - scanf("%d",&n) ; - - printf("Enter the data value of each node:\n") ; - for(i=1 ; i<=n ; i++) - { - pnode=(struct node*)malloc(sizeof(struct node)) ; - if(pnode==NULL) - { - printf("Memory overflow. Unable to create.\n") ; - return ; - } - - scanf("%d",&pnode->data) ; - - if(first==NULL) - first=last=pnode ; - else - { - last->next=pnode ; - last=pnode ; /* last keeps track of last node */ - } - - last->next=first ; - } -} - -/* This function will delete a node with value k from the Linked List if such a node exists */ -void deletenode(int k) -{ - struct node *p , *follow ; - - /* searching the required node */ - p=first ; - follow=NULL ; - while(follow!=last) - { - if(p->data==k) - break ; - follow=p ; - p=p->next ; - } - - if(follow==last) - printf("Required node not found.\n") ; - else - { - if(p==first&&p==last) /* deleting the one and the only node */ - first=last=NULL ; - else if(p==first) /* deleting the first node */ - { - first=first->next ; - last->next=first ; - } - else if(p==last) /* deleting the last node */ - { - last=follow ; - last->next=first ; - } - else /* deleting any other node */ - follow->next=p->next ; - - free(p) ; - } -} - -/* This function will go through all the nodes of Linked List exactly once and will display data value of each node */ -void traverse() -{ - struct node *p , *follow ; - if(first==NULL) - printf("Circularly Linked List Empty") ; - else - { - printf("Circularly Linked List is as shown: \n") ; - - p=first ; - follow = NULL ; - while(follow!=last) - { - printf("%d " , p->data) ; - follow=p ; - p=p->next ; - } - - printf("\n") ; - } -} - -void main() -{ - int x , k , ch ; - clrscr() ; - do - { - printf("\n Menu: \n") ; - printf("1:Create Linked List \n") ; - printf("2:Delete Node \n") ; - printf("3:Traverse \n") ; - printf("4:Exit \n") ; - - printf("\nEnter your choice: ") ; - scanf("%d",&ch) ; - - switch(ch) - { - case 1: - create() ; - break ; - - case 2: - printf("Enter the data value of the node to be deleted: ") ; - scanf("%d",&k) ; - deletenode(k) ; - break ; - - case 3: - traverse() ; - break ; - - case 4: - break ; - } - } - while(ch!=4) ; - - getch() ; -} - - - +/* Circularly Linked List (Basic Operations) - Program to create a Circularly linked list abstract data type and perform various operations on it (Variable first and last declared globally) */ + +#include +#include +#include +#define NULL 0 + +/* Assume that the data portion of each node consists of ONLY an integer.*/ +struct node +{ + int data ; + struct node *next ; +} ; + +struct node *first=NULL ; +struct node *last=NULL ; +/* first and last are global variables and need not be passed to any function. Any changes made to variables first and last by any of the functions in the program will be reflected in the entire program */ + +/* This function is responsible for creating the Circularly Linked List right from the BEGINNING. */ +void create() +{ + int i , n ; + struct node *pnode , *p ; + + printf("Enter the number of nodes required:\n") ; + scanf("%d",&n) ; + + printf("Enter the data value of each node:\n") ; + for(i=1 ; i<=n ; i++) + { + pnode=(struct node*)malloc(sizeof(struct node)) ; + if(pnode==NULL) + { + printf("Memory overflow. Unable to create.\n") ; + return ; + } + + scanf("%d",&pnode->data) ; + + if(first==NULL) + first=last=pnode ; + else + { + last->next=pnode ; + last=pnode ; /* last keeps track of last node */ + } + + last->next=first ; + } +} + +/* This function will delete a node with value k from the Linked List if such a node exists */ +void deletenode(int k) +{ + struct node *p , *follow ; + + /* searching the required node */ + p=first ; + follow=NULL ; + while(follow!=last) + { + if(p->data==k) + break ; + follow=p ; + p=p->next ; + } + + if(follow==last) + printf("Required node not found.\n") ; + else + { + if(p==first&&p==last) /* deleting the one and the only node */ + first=last=NULL ; + else if(p==first) /* deleting the first node */ + { + first=first->next ; + last->next=first ; + } + else if(p==last) /* deleting the last node */ + { + last=follow ; + last->next=first ; + } + else /* deleting any other node */ + follow->next=p->next ; + + free(p) ; + } +} + +/* This function will go through all the nodes of Linked List exactly once and will display data value of each node */ +void traverse() +{ + struct node *p , *follow ; + if(first==NULL) + printf("Circularly Linked List Empty") ; + else + { + printf("Circularly Linked List is as shown: \n") ; + + p=first ; + follow = NULL ; + while(follow!=last) + { + printf("%d " , p->data) ; + follow=p ; + p=p->next ; + } + + printf("\n") ; + } +} + +int main(void) +{ + int x , k , ch ; + do + { + printf("\n Menu: \n") ; + printf("1:Create Linked List \n") ; + printf("2:Delete Node \n") ; + printf("3:Traverse \n") ; + printf("4:Exit \n") ; + + printf("\nEnter your choice: ") ; + scanf("%d",&ch) ; + + switch(ch) + { + case 1: + create() ; + break ; + + case 2: + printf("Enter the data value of the node to be deleted: ") ; + scanf("%d",&k) ; + deletenode(k) ; + break ; + + case 3: + traverse() ; + break ; + + case 4: + break ; + } + } + while(ch!=4) ; + + return 0; +} + + + diff --git a/exercism/acronym/acronym.c b/exercism/acronym/acronym.c index 2c1c4e6455..791a1c6ba7 100644 --- a/exercism/acronym/acronym.c +++ b/exercism/acronym/acronym.c @@ -1,6 +1,7 @@ #include #include #include +#include char *abbreviate(const char *phrase) { diff --git a/leetcode/src/1.c b/leetcode/src/1.c index 53f260a10b..0a6df8ea7d 100644 --- a/leetcode/src/1.c +++ b/leetcode/src/1.c @@ -1,3 +1,4 @@ +#include int *twoSum(int *nums, int numsSize, int target, int *returnSize) { int i, j; diff --git a/leetcode/src/10.c b/leetcode/src/10.c index 26ed6a3b89..12fb37f5e8 100644 --- a/leetcode/src/10.c +++ b/leetcode/src/10.c @@ -1,3 +1,4 @@ +#include /* Prompt: diff --git a/leetcode/src/1008.c b/leetcode/src/1008.c index ce4871ecd4..be572a70e2 100644 --- a/leetcode/src/1008.c +++ b/leetcode/src/1008.c @@ -1,11 +1,9 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; struct TreeNode* bstFromPreorder(int* preorder, int preorderSize) { diff --git a/leetcode/src/1009.c b/leetcode/src/1009.c index 77480d71a7..48f46ffb45 100644 --- a/leetcode/src/1009.c +++ b/leetcode/src/1009.c @@ -1,15 +1,16 @@ -// Bit manipulation. -// - Find the bit length of n using log2 -// - Create bit mask of bit length of n -// - Retun ~n and bit of ones mask -// Runtime: O(log2(n)) -// Space: O(1) - -int bitwiseComplement(int n){ - if (n == 0){ - return 1; - } - - int binary_number_length = ceil(log2(n)); - return (~n) & ((1 << binary_number_length) - 1); -} +#include +// Bit manipulation. +// - Find the bit length of n using log2 +// - Create bit mask of bit length of n +// - Retun ~n and bit of ones mask +// Runtime: O(log2(n)) +// Space: O(1) + +int bitwiseComplement(int n){ + if (n == 0){ + return 1; + } + + int binary_number_length = ceil(log2(n)); + return (~n) & ((1 << binary_number_length) - 1); +} diff --git a/leetcode/src/101.c b/leetcode/src/101.c index 68a8dc5ed2..cb4fba071e 100644 --- a/leetcode/src/101.c +++ b/leetcode/src/101.c @@ -1,3 +1,5 @@ +#include +#include /** * Definition for a binary tree node. * struct TreeNode { diff --git a/leetcode/src/1019.c b/leetcode/src/1019.c index 31eca53d72..6eba5d175f 100644 --- a/leetcode/src/1019.c +++ b/leetcode/src/1019.c @@ -1,10 +1,8 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ +#include +struct ListNode { + int val; + struct ListNode *next; +}; int* nextLargerNodes(struct ListNode* head, int* returnSize) { diff --git a/leetcode/src/1026.c b/leetcode/src/1026.c index 0dda623023..5975d46502 100644 --- a/leetcode/src/1026.c +++ b/leetcode/src/1026.c @@ -1,38 +1,36 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define max(a,b) (((a)>(b))?(a):(b)) -#define min(a,b) (((a)<(b))?(a):(b)) - -void recursiveSolve(struct TreeNode* node, int* result, int minVal, int maxVal){ - if (node == NULL){ - return; - } - - *result = max(*result, abs(minVal - node->val)); - *result = max(*result, abs(maxVal - node->val)); - - minVal = min(minVal, node->val); - maxVal = max(maxVal, node->val); - - recursiveSolve(node->left, result, minVal, maxVal); - recursiveSolve(node->right, result, minVal, maxVal); -} - -// Depth First Search -// If The maximum diff is exists it should be the difference of the MAX or MIN value in the tree path to the LEAF -// Runtime: O(n) -// Space: O(1) -int maxAncestorDiff(struct TreeNode* root){ - int result = 0; - int maxVal = root->val; - int minVal = root->val; - recursiveSolve(root, &result, minVal, maxVal); - return result; -} +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +#define max(a,b) (((a)>(b))?(a):(b)) +#define min(a,b) (((a)<(b))?(a):(b)) + +void recursiveSolve(struct TreeNode* node, int* result, int minVal, int maxVal){ + if (node == NULL){ + return; + } + + *result = max(*result, abs(minVal - node->val)); + *result = max(*result, abs(maxVal - node->val)); + + minVal = min(minVal, node->val); + maxVal = max(maxVal, node->val); + + recursiveSolve(node->left, result, minVal, maxVal); + recursiveSolve(node->right, result, minVal, maxVal); +} + +// Depth First Search +// If The maximum diff is exists it should be the difference of the MAX or MIN value in the tree path to the LEAF +// Runtime: O(n) +// Space: O(1) +int maxAncestorDiff(struct TreeNode* root){ + int result = 0; + int maxVal = root->val; + int minVal = root->val; + recursiveSolve(root, &result, minVal, maxVal); + return result; +} diff --git a/leetcode/src/104.c b/leetcode/src/104.c index 91d8019aad..0535a3584a 100644 --- a/leetcode/src/104.c +++ b/leetcode/src/104.c @@ -1,11 +1,9 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; int maxval(int a, int b) { diff --git a/leetcode/src/108.c b/leetcode/src/108.c index 24ab54983b..07be6f00a6 100644 --- a/leetcode/src/108.c +++ b/leetcode/src/108.c @@ -1,11 +1,9 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; struct TreeNode *convertBST(int *nums, int left, int right) { diff --git a/leetcode/src/1089.c b/leetcode/src/1089.c index 81c89b8c97..96670044c7 100644 --- a/leetcode/src/1089.c +++ b/leetcode/src/1089.c @@ -1,3 +1,4 @@ +#include void duplicateZeros(int *arr, int arrSize) { int i, start = 0; diff --git a/leetcode/src/109.c b/leetcode/src/109.c index 5daf5ac317..ddbbe285cf 100644 --- a/leetcode/src/109.c +++ b/leetcode/src/109.c @@ -1,3 +1,6 @@ +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; +struct ListNode { int val; struct ListNode *next; }; struct TreeNode *buildBST(struct ListNode *head, struct ListNode *tail) { if (head == tail) diff --git a/leetcode/src/110.c b/leetcode/src/110.c index 639feab6e3..c65f01e4a2 100644 --- a/leetcode/src/110.c +++ b/leetcode/src/110.c @@ -1,3 +1,6 @@ +#include +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; int max(int a, int b) { return a >= b ? a : b; } int height(struct TreeNode *root) diff --git a/leetcode/src/112.c b/leetcode/src/112.c index dc3256d96e..7d4245df48 100644 --- a/leetcode/src/112.c +++ b/leetcode/src/112.c @@ -1,3 +1,6 @@ +#include +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; bool hasPathSum(struct TreeNode *root, int sum) { if (root == NULL) diff --git a/leetcode/src/1147.c b/leetcode/src/1147.c index 501060d098..b17745c3a7 100644 --- a/leetcode/src/1147.c +++ b/leetcode/src/1147.c @@ -1,49 +1,52 @@ -#define max(a,b) (((a)>(b))?(a):(b)) - -bool equalSubstrings(char* text, int firstIndex, int secondIndex, int length){ - for (int i = 0; i < length; i++){ - if (text[firstIndex + i] != text[secondIndex + i]){ - return false; - } - } - - return true; -} - -int longestDecompositionDpCached(char* text, int textLen, int index, int* dp){ - if (2 * index >= textLen){ - return 0; - } - - if (dp[index] == 0){ - dp[index] = longestDecompositionDp(text, textLen, index, dp); - } - - return dp[index]; -} - -int longestDecompositionDp(char* text, int textLen, int index, int* dp){ - char ch = text[index]; - int result = 1; - - for (int i = 0; i < (textLen - 2 * index) / 2; i++){ - if (ch == text[textLen - 1 - index - i] - && equalSubstrings(text, index, textLen - 1 - index - i, i + 1)){ - return max(result, 2 + longestDecompositionDpCached(text, textLen, index + i + 1, dp)); - } - } - - return result; -} - -// Dynamic programming. Up -> down approach. -// Runtime: O(n*n) -// Space: O(n) -int longestDecomposition(char * text){ - int textLen = strlen(text); - int* dp = calloc(textLen, sizeof(int)); - int result = longestDecompositionDpCached(text, textLen, 0, dp); - - free(dp); - return result; -} +#include +#include +#include +#define max(a,b) (((a)>(b))?(a):(b)) + +bool equalSubstrings(char* text, int firstIndex, int secondIndex, int length){ + for (int i = 0; i < length; i++){ + if (text[firstIndex + i] != text[secondIndex + i]){ + return false; + } + } + + return true; +} + +int longestDecompositionDpCached(char* text, int textLen, int index, int* dp){ + if (2 * index >= textLen){ + return 0; + } + + if (dp[index] == 0){ + dp[index] = longestDecompositionDp(text, textLen, index, dp); + } + + return dp[index]; +} + +int longestDecompositionDp(char* text, int textLen, int index, int* dp){ + char ch = text[index]; + int result = 1; + + for (int i = 0; i < (textLen - 2 * index) / 2; i++){ + if (ch == text[textLen - 1 - index - i] + && equalSubstrings(text, index, textLen - 1 - index - i, i + 1)){ + return max(result, 2 + longestDecompositionDpCached(text, textLen, index + i + 1, dp)); + } + } + + return result; +} + +// Dynamic programming. Up -> down approach. +// Runtime: O(n*n) +// Space: O(n) +int longestDecomposition(char * text){ + int textLen = strlen(text); + int* dp = calloc(textLen, sizeof(int)); + int result = longestDecompositionDpCached(text, textLen, 0, dp); + + free(dp); + return result; +} diff --git a/leetcode/src/118.c b/leetcode/src/118.c index a926efdcb1..aef7c82e80 100644 --- a/leetcode/src/118.c +++ b/leetcode/src/118.c @@ -1,3 +1,4 @@ +#include /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. diff --git a/leetcode/src/119.c b/leetcode/src/119.c index a4b6f7a921..529fde4454 100644 --- a/leetcode/src/119.c +++ b/leetcode/src/119.c @@ -1,3 +1,4 @@ +#include /** * Note: The returned array must be malloced, assume caller calls free(). */ diff --git a/leetcode/src/12.c b/leetcode/src/12.c index b8d8f7c04f..0df7729a97 100644 --- a/leetcode/src/12.c +++ b/leetcode/src/12.c @@ -1,3 +1,6 @@ +#include +#include +#include char *getOne(char c) { switch (c) diff --git a/leetcode/src/1207.c b/leetcode/src/1207.c index 8c8eb8dc02..0c5e38af86 100644 --- a/leetcode/src/1207.c +++ b/leetcode/src/1207.c @@ -1,3 +1,5 @@ +#include +#include #define MAP_SIZE 2048 int cmpvalue(const void *a, const void *b) { return *(int *)b - *(int *)a; } diff --git a/leetcode/src/124.c b/leetcode/src/124.c index a846dfcb44..600590a8da 100644 --- a/leetcode/src/124.c +++ b/leetcode/src/124.c @@ -1,36 +1,34 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define max(a,b) (((a)>(b))?(a):(b)) - -int recursiveSolve(struct TreeNode* node, int* result){ - if (node == NULL){ - return 0; - } - - int leftSum = max(recursiveSolve(node->left, result), 0); - int rightSum = max(recursiveSolve(node->right, result), 0); - - // Check if it's possible to make a maximum path from left right and current node - int maxValueNode = node->val + leftSum + rightSum; - *result = max(maxValueNode, *result); - - // Choose the max sum val path - return node->val + max(leftSum, rightSum); -} - -// Depth First Search -// Runtime: O(n), n - the number of nodes in tree. -// Space: O(1) -int maxPathSum(struct TreeNode* root){ - const int LOWER_BOUND = -2147483648 - int result = LOWER_BOUND; - recursiveSolve(root, &result); - return result; -} +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +#define max(a,b) (((a)>(b))?(a):(b)) + +int recursiveSolve(struct TreeNode* node, int* result){ + if (node == NULL){ + return 0; + } + + int leftSum = max(recursiveSolve(node->left, result), 0); + int rightSum = max(recursiveSolve(node->right, result), 0); + + // Check if it's possible to make a maximum path from left right and current node + int maxValueNode = node->val + leftSum + rightSum; + *result = max(maxValueNode, *result); + + // Choose the max sum val path + return node->val + max(leftSum, rightSum); +} + +// Depth First Search +// Runtime: O(n), n - the number of nodes in tree. +// Space: O(1) +int maxPathSum(struct TreeNode* root){ + const int LOWER_BOUND = -2147483648; + int result = LOWER_BOUND; + recursiveSolve(root, &result); + return result; +} diff --git a/leetcode/src/125.c b/leetcode/src/125.c index 07a210b0a5..3205a5ff7c 100644 --- a/leetcode/src/125.c +++ b/leetcode/src/125.c @@ -1,3 +1,6 @@ +#include +#include +#include bool isPalindrome(char *s) { int start = 0, end = strlen(s) - 1; diff --git a/leetcode/src/141.c b/leetcode/src/141.c index 6e4ac65a2a..562f51243f 100644 --- a/leetcode/src/141.c +++ b/leetcode/src/141.c @@ -1,10 +1,8 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ +#include +struct ListNode { + int val; + struct ListNode *next; +}; bool hasCycle(struct ListNode *head) { struct ListNode *fast = head, *slow = head; diff --git a/leetcode/src/142.c b/leetcode/src/142.c index c45fe586fb..6de569f455 100644 --- a/leetcode/src/142.c +++ b/leetcode/src/142.c @@ -1,3 +1,5 @@ +#include +struct ListNode { int val; struct ListNode *next; }; struct ListNode *detectCycle(struct ListNode *head) { if (head == NULL || head->next == NULL) diff --git a/leetcode/src/160.c b/leetcode/src/160.c index bfca759bc3..561d5e0800 100644 --- a/leetcode/src/160.c +++ b/leetcode/src/160.c @@ -1,3 +1,5 @@ +#include +struct ListNode { int val; struct ListNode *next; }; struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { diff --git a/leetcode/src/1657.c b/leetcode/src/1657.c index 10aa60d258..96db5c8527 100644 --- a/leetcode/src/1657.c +++ b/leetcode/src/1657.c @@ -1,51 +1,54 @@ -const charLength = 26; - -int* charsCount(char* word){ - int* result = calloc(charLength, sizeof(int)); - int wordLen = strlen(word); - for (int i = 0; i < wordLen; i++){ - result[word[i] - 'a']++; - } - - return result; -} - -int diff(const int *i, const int *j) -{ - return *i - *j; -} - -// Counting -// Runtime: O(n) -// Space: O(1) -bool closeStrings(char * word1, char * word2){ - int* word1CharsCounter = charsCount(word1); - int* word2CharsCounter = charsCount(word2); - - // The lengths of both string should be equal - if (strlen(word1) != strlen(word2)){ - return false; - } - - // The char should appear in both strings - for (int i = 0; i < charLength; i++){ - if ((word1CharsCounter[i] != 0 && word2CharsCounter[i] == 0) || - (word1CharsCounter[i] == 0 && word2CharsCounter[i] != 0)){ - return false; - } - } - - qsort(word1CharsCounter, charLength, sizeof (int), (int(*) (const void *, const void *)) diff); - qsort(word2CharsCounter, charLength, sizeof (int), (int(*) (const void *, const void *)) diff); - - // appearing of chars should be the same in both strings. - for (int i = 0; i < charLength; i++){ - if (word1CharsCounter[i] != word2CharsCounter[i]){ - return false; - } - } - - free(word1CharsCounter); - free(word2CharsCounter); - return true; -} +#include +#include +#include +const charLength = 26; + +int* charsCount(char* word){ + int* result = calloc(charLength, sizeof(int)); + int wordLen = strlen(word); + for (int i = 0; i < wordLen; i++){ + result[word[i] - 'a']++; + } + + return result; +} + +int diff(const int *i, const int *j) +{ + return *i - *j; +} + +// Counting +// Runtime: O(n) +// Space: O(1) +bool closeStrings(char * word1, char * word2){ + int* word1CharsCounter = charsCount(word1); + int* word2CharsCounter = charsCount(word2); + + // The lengths of both string should be equal + if (strlen(word1) != strlen(word2)){ + return false; + } + + // The char should appear in both strings + for (int i = 0; i < charLength; i++){ + if ((word1CharsCounter[i] != 0 && word2CharsCounter[i] == 0) || + (word1CharsCounter[i] == 0 && word2CharsCounter[i] != 0)){ + return false; + } + } + + qsort(word1CharsCounter, charLength, sizeof (int), (int(*) (const void *, const void *)) diff); + qsort(word2CharsCounter, charLength, sizeof (int), (int(*) (const void *, const void *)) diff); + + // appearing of chars should be the same in both strings. + for (int i = 0; i < charLength; i++){ + if (word1CharsCounter[i] != word2CharsCounter[i]){ + return false; + } + } + + free(word1CharsCounter); + free(word2CharsCounter); + return true; +} diff --git a/leetcode/src/1695.c b/leetcode/src/1695.c index c0a57247a0..799c86a126 100644 --- a/leetcode/src/1695.c +++ b/leetcode/src/1695.c @@ -1,29 +1,30 @@ -// Window sliding. Runtime: O(n), Space: O(n) -int maximumUniqueSubarray(int* nums, int numsSize){ - short* numsSet = (short*)calloc(10001, sizeof(short)); - numsSet[nums[0]] = 1; - - int maxSum = nums[0]; - - int windowSumm = maxSum; - int leftIndex = 0; - - int num = 0; - for(int i = 1; i < numsSize; i++){ - num = nums[i]; - while (numsSet[num] != 0){ - numsSet[nums[leftIndex]] = 0; - windowSumm -= nums[leftIndex]; - leftIndex++; - } - - numsSet[num] = 1; - windowSumm += num; - - if (maxSum < windowSumm){ - maxSum = windowSumm; - } - } - - return maxSum; -} +#include +// Window sliding. Runtime: O(n), Space: O(n) +int maximumUniqueSubarray(int* nums, int numsSize){ + short* numsSet = (short*)calloc(10001, sizeof(short)); + numsSet[nums[0]] = 1; + + int maxSum = nums[0]; + + int windowSumm = maxSum; + int leftIndex = 0; + + int num = 0; + for(int i = 1; i < numsSize; i++){ + num = nums[i]; + while (numsSet[num] != 0){ + numsSet[nums[leftIndex]] = 0; + windowSumm -= nums[leftIndex]; + leftIndex++; + } + + numsSet[num] = 1; + windowSumm += num; + + if (maxSum < windowSumm){ + maxSum = windowSumm; + } + } + + return maxSum; +} diff --git a/leetcode/src/1704.c b/leetcode/src/1704.c index 25251983bc..cdd34342ae 100644 --- a/leetcode/src/1704.c +++ b/leetcode/src/1704.c @@ -1,38 +1,41 @@ -bool isVowel(char chr){ - switch(chr){ - case 'a': - case 'e': - case 'i': - case 'o': - case 'u': - case 'A': - case 'E': - case 'I': - case 'O': - case 'U': - return true; - } - - return false; -} - -// Counting -// Runtime: O(n) -// Space: O(1) -bool halvesAreAlike(char * s){ - int lenS = strlen(s); - int halfVowels = 0; - int currVowels = 0; - - for (int i = 0; i < lenS; i++){ - if (isVowel(s[i])){ - currVowels++; - } - - if (2 * (i + 1) == lenS){ - halfVowels = currVowels; - } - } - - return 2 * halfVowels == currVowels; -} +#include +#include +#include +bool isVowel(char chr){ + switch(chr){ + case 'a': + case 'e': + case 'i': + case 'o': + case 'u': + case 'A': + case 'E': + case 'I': + case 'O': + case 'U': + return true; + } + + return false; +} + +// Counting +// Runtime: O(n) +// Space: O(1) +bool halvesAreAlike(char * s){ + int lenS = strlen(s); + int halfVowels = 0; + int currVowels = 0; + + for (int i = 0; i < lenS; i++){ + if (isVowel(s[i])){ + currVowels++; + } + + if (2 * (i + 1) == lenS){ + halfVowels = currVowels; + } + } + + return 2 * halfVowels == currVowels; +} diff --git a/leetcode/src/173.c b/leetcode/src/173.c index 0dcc59964e..37fd164e4a 100644 --- a/leetcode/src/173.c +++ b/leetcode/src/173.c @@ -8,6 +8,9 @@ */ #include +#include +#include +#include typedef struct { diff --git a/leetcode/src/1752.c b/leetcode/src/1752.c index 492a82b484..f86f306e97 100644 --- a/leetcode/src/1752.c +++ b/leetcode/src/1752.c @@ -1,18 +1,19 @@ -bool check(int* nums, int numsSize){ - if (numsSize == 1) { - return true; - } - - bool wasShift = false; - for(int i = 1; i < numsSize; i++) { - if (nums[i - 1] > nums[i]) { - if (wasShift) { - return false; - } - - wasShift = true; - } - } - - return !wasShift || nums[0] >= nums[numsSize-1]; -} +#include +bool check(int* nums, int numsSize){ + if (numsSize == 1) { + return true; + } + + bool wasShift = false; + for(int i = 1; i < numsSize; i++) { + if (nums[i - 1] > nums[i]) { + if (wasShift) { + return false; + } + + wasShift = true; + } + } + + return !wasShift || nums[0] >= nums[numsSize-1]; +} diff --git a/leetcode/src/1769.c b/leetcode/src/1769.c index e1a81d0492..73f85f9b9e 100644 --- a/leetcode/src/1769.c +++ b/leetcode/src/1769.c @@ -1,41 +1,43 @@ -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ - -// Count one's from right. Each step from right side decrease for one for each 1's and increase from left: -// 1001*0101 -> left: 4 + 1, right: 2 + 4 -// 10010*101 -> left: (4+1) + (1+1), right: (2-1) + (4-1) -// Runtime: O(n) -// Space: O(1) -int* minOperations(char* boxes, int* returnSize){ - int leftOnes = 0; - int leftCommonDistance = 0; - - int rightOnes = 0; - int rightCommonDistance = 0; - - int boxesLength = strlen(boxes); - - *returnSize = boxesLength; - int* result = malloc(boxesLength * sizeof(int)); - - for (int i = 0; i < boxesLength; i++){ - if (boxes[i] == '1'){ - rightOnes += 1; - rightCommonDistance += i; - } - } - - for (int i = 0; i < boxesLength; i++){ - if (boxes[i] == '1'){ - rightOnes -= 1; - leftOnes += 1; - } - - result[i] = rightCommonDistance + leftCommonDistance; - rightCommonDistance -= rightOnes; - leftCommonDistance += leftOnes; - } - - return result; -} +#include +#include +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +// Count one's from right. Each step from right side decrease for one for each 1's and increase from left: +// 1001*0101 -> left: 4 + 1, right: 2 + 4 +// 10010*101 -> left: (4+1) + (1+1), right: (2-1) + (4-1) +// Runtime: O(n) +// Space: O(1) +int* minOperations(char* boxes, int* returnSize){ + int leftOnes = 0; + int leftCommonDistance = 0; + + int rightOnes = 0; + int rightCommonDistance = 0; + + int boxesLength = strlen(boxes); + + *returnSize = boxesLength; + int* result = malloc(boxesLength * sizeof(int)); + + for (int i = 0; i < boxesLength; i++){ + if (boxes[i] == '1'){ + rightOnes += 1; + rightCommonDistance += i; + } + } + + for (int i = 0; i < boxesLength; i++){ + if (boxes[i] == '1'){ + rightOnes -= 1; + leftOnes += 1; + } + + result[i] = rightCommonDistance + leftCommonDistance; + rightCommonDistance -= rightOnes; + leftCommonDistance += leftOnes; + } + + return result; +} diff --git a/leetcode/src/1838.c b/leetcode/src/1838.c index fe4469bf3b..2be80fde78 100644 --- a/leetcode/src/1838.c +++ b/leetcode/src/1838.c @@ -1,36 +1,37 @@ -#define max(a,b) (((a)>(b))?(a):(b)) - -int compare(const int* i, const int* j) -{ - return *i - *j; -} - -// Sort + prefix sum + windows sliding -// Runtime: O(n*log(n)) -// Space: O(n) -int maxFrequency(int* nums, int numsSize, int k){ - qsort(nums, numsSize, sizeof (int), (int(*) (const void*, const void*)) compare); - long* prefixSum = malloc(numsSize * sizeof(long)); - - prefixSum[0] = nums[0]; - for(int i = 0; i < numsSize - 1; i++){ - prefixSum[i + 1] = prefixSum[i] + nums[i]; - } - - int leftWindowPosition = 0; - int result = 0; - - for(int rightWindowPosition = 0; rightWindowPosition < numsSize; rightWindowPosition++){ - long rightSum = prefixSum[rightWindowPosition]; - long leftSum = prefixSum[leftWindowPosition]; - - while ((long)nums[rightWindowPosition] * (rightWindowPosition - leftWindowPosition) - (rightSum - leftSum) > k){ - leftWindowPosition += 1; - } - - result = max(result, rightWindowPosition - leftWindowPosition + 1); - } - - free(prefixSum); - return result; -} +#include +#define max(a,b) (((a)>(b))?(a):(b)) + +int compare(const int* i, const int* j) +{ + return *i - *j; +} + +// Sort + prefix sum + windows sliding +// Runtime: O(n*log(n)) +// Space: O(n) +int maxFrequency(int* nums, int numsSize, int k){ + qsort(nums, numsSize, sizeof (int), (int(*) (const void*, const void*)) compare); + long* prefixSum = malloc(numsSize * sizeof(long)); + + prefixSum[0] = nums[0]; + for(int i = 0; i < numsSize - 1; i++){ + prefixSum[i + 1] = prefixSum[i] + nums[i]; + } + + int leftWindowPosition = 0; + int result = 0; + + for(int rightWindowPosition = 0; rightWindowPosition < numsSize; rightWindowPosition++){ + long rightSum = prefixSum[rightWindowPosition]; + long leftSum = prefixSum[leftWindowPosition]; + + while ((long)nums[rightWindowPosition] * (rightWindowPosition - leftWindowPosition) - (rightSum - leftSum) > k){ + leftWindowPosition += 1; + } + + result = max(result, rightWindowPosition - leftWindowPosition + 1); + } + + free(prefixSum); + return result; +} diff --git a/leetcode/src/19.c b/leetcode/src/19.c index c189f8f288..7b505888d5 100644 --- a/leetcode/src/19.c +++ b/leetcode/src/19.c @@ -1,10 +1,8 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ +#include +struct ListNode { + int val; + struct ListNode *next; +}; struct ListNode *removeNthFromEnd(struct ListNode *head, int n) { struct ListNode entry, *p_free, *p = head; diff --git a/leetcode/src/2.c b/leetcode/src/2.c index d2bec03099..ee94981cbc 100644 --- a/leetcode/src/2.c +++ b/leetcode/src/2.c @@ -1,10 +1,8 @@ -/* - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ +#include +struct ListNode { + int val; + struct ListNode *next; +}; struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) { diff --git a/leetcode/src/20.c b/leetcode/src/20.c index 7d3ad5c0a4..2e96861ef3 100644 --- a/leetcode/src/20.c +++ b/leetcode/src/20.c @@ -1,3 +1,6 @@ +#include +#include +#include bool isValid(char *s) { int i, k = 0, len = strlen(s); diff --git a/leetcode/src/203.c b/leetcode/src/203.c index f652aaeb45..33aa202b6f 100644 --- a/leetcode/src/203.c +++ b/leetcode/src/203.c @@ -1,3 +1,5 @@ +#include +struct ListNode { int val; struct ListNode *next; }; struct ListNode *removeElements(struct ListNode *head, int val) { if (head == NULL) diff --git a/leetcode/src/206.c b/leetcode/src/206.c index adc4657b9d..ca563d0eeb 100644 --- a/leetcode/src/206.c +++ b/leetcode/src/206.c @@ -1,10 +1,8 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ +#include +struct ListNode { + int val; + struct ListNode *next; +}; struct ListNode *reverseList(struct ListNode *head) { diff --git a/leetcode/src/2095.c b/leetcode/src/2095.c index 196b0892a7..2ec348f9b1 100644 --- a/leetcode/src/2095.c +++ b/leetcode/src/2095.c @@ -1,10 +1,8 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ +#include +struct ListNode { + int val; + struct ListNode *next; +}; struct ListNode* deleteMiddle(struct ListNode* head) { diff --git a/leetcode/src/21.c b/leetcode/src/21.c index 54d31e1b3e..2ebd59fded 100644 --- a/leetcode/src/21.c +++ b/leetcode/src/21.c @@ -1,3 +1,5 @@ +#include +struct ListNode { int val; struct ListNode *next; }; /* * Iterative approach */ diff --git a/leetcode/src/2130.c b/leetcode/src/2130.c index 6dbacc1d20..3d8a479942 100644 --- a/leetcode/src/2130.c +++ b/leetcode/src/2130.c @@ -1,10 +1,8 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ +#include +struct ListNode { + int val; + struct ListNode *next; +}; int pairSum(struct ListNode* head) { diff --git a/leetcode/src/217.c b/leetcode/src/217.c index a349ef9e2c..b9c78cae3b 100644 --- a/leetcode/src/217.c +++ b/leetcode/src/217.c @@ -1,3 +1,5 @@ +#include +#include int numcmp(const void *a, const void *b) { return *(int *)a - *(int *)b; } bool containsDuplicate(int *nums, int numsSize) diff --git a/leetcode/src/2256.c b/leetcode/src/2256.c index 06e4d123a5..e1cf80edb2 100644 --- a/leetcode/src/2256.c +++ b/leetcode/src/2256.c @@ -1,37 +1,38 @@ -// Prefix sum. -// - Calculate whole nums sum. -// - Calculate currIndex sum. -// - Compare averages -// Runtime: O(n) -// Space: O(1) - -int minimumAverageDifference(int* nums, int numsSize){ - long numsSum = 0; - for (int i = 0; i < numsSize; i++){ - numsSum += nums[i]; - } - - long currSum = 0; - long minAverage = 9223372036854775807; // Long max - int minIndex = 0; - - for (int i = 0; i < numsSize; i++){ - currSum += nums[i]; - - int leftItemsNumber = (numsSize - i - 1); - long leftItemsNumberAverage = 0; - if (leftItemsNumber != 0){ - leftItemsNumberAverage = (numsSum - currSum) / leftItemsNumber; - } - - long currItemsNumberAverage = currSum / (i + 1); - long averageDiff = abs(currItemsNumberAverage - leftItemsNumberAverage); - - if (averageDiff < minAverage){ - minAverage = averageDiff; - minIndex = i; - } - } - - return minIndex; -} +#include +// Prefix sum. +// - Calculate whole nums sum. +// - Calculate currIndex sum. +// - Compare averages +// Runtime: O(n) +// Space: O(1) + +int minimumAverageDifference(int* nums, int numsSize){ + long numsSum = 0; + for (int i = 0; i < numsSize; i++){ + numsSum += nums[i]; + } + + long currSum = 0; + long minAverage = 9223372036854775807; // Long max + int minIndex = 0; + + for (int i = 0; i < numsSize; i++){ + currSum += nums[i]; + + int leftItemsNumber = (numsSize - i - 1); + long leftItemsNumberAverage = 0; + if (leftItemsNumber != 0){ + leftItemsNumberAverage = (numsSum - currSum) / leftItemsNumber; + } + + long currItemsNumberAverage = currSum / (i + 1); + long averageDiff = abs(currItemsNumberAverage - leftItemsNumberAverage); + + if (averageDiff < minAverage){ + minAverage = averageDiff; + minIndex = i; + } + } + + return minIndex; +} diff --git a/leetcode/src/226.c b/leetcode/src/226.c index ac2bf1613a..ad1c5ac8e2 100644 --- a/leetcode/src/226.c +++ b/leetcode/src/226.c @@ -1,3 +1,5 @@ +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; struct TreeNode *invertTree(struct TreeNode *root) { struct TreeNode *tmp; diff --git a/leetcode/src/2279.c b/leetcode/src/2279.c index 8dc05d981e..191b5189ca 100644 --- a/leetcode/src/2279.c +++ b/leetcode/src/2279.c @@ -1,29 +1,30 @@ -int compare(const int* i, const int* j) -{ - return *i - *j; -} - -// Sorting. -// Runtime: O(n*log(n)) -// Space: O(n) -int maximumBags(int* capacity, int capacitySize, int* rocks, int rocksSize, int additionalRocks) { - int* capacityLeft = malloc(capacitySize * sizeof(int)); - for (int i = 0; i < capacitySize; i++) { - capacityLeft[i] = capacity[i] - rocks[i]; - } - - qsort(capacityLeft, capacitySize, sizeof (int), (int(*) (const void*, const void*)) compare); - - int bags = 0; - for (int i = 0; i < capacitySize; i++) { - if (additionalRocks < capacityLeft[i]){ - break; - } - - additionalRocks -= capacityLeft[i]; - bags++; - } - - free(capacityLeft); - return bags; -} +#include +int compare(const int* i, const int* j) +{ + return *i - *j; +} + +// Sorting. +// Runtime: O(n*log(n)) +// Space: O(n) +int maximumBags(int* capacity, int capacitySize, int* rocks, int rocksSize, int additionalRocks) { + int* capacityLeft = malloc(capacitySize * sizeof(int)); + for (int i = 0; i < capacitySize; i++) { + capacityLeft[i] = capacity[i] - rocks[i]; + } + + qsort(capacityLeft, capacitySize, sizeof (int), (int(*) (const void*, const void*)) compare); + + int bags = 0; + for (int i = 0; i < capacitySize; i++) { + if (additionalRocks < capacityLeft[i]){ + break; + } + + additionalRocks -= capacityLeft[i]; + bags++; + } + + free(capacityLeft); + return bags; +} diff --git a/leetcode/src/230.c b/leetcode/src/230.c index 61fa0e77f8..a0739b4494 100644 --- a/leetcode/src/230.c +++ b/leetcode/src/230.c @@ -1,35 +1,33 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct TreeNode* findKthSmallest(struct TreeNode* node, int* k){ - if (node == NULL){ - return NULL; - } - - struct TreeNode* resultNode = findKthSmallest(node->left, k); - - if (resultNode != NULL){ - return resultNode; - } - - *k -= 1; - - if (*k == 0){ - return node; - } - - return findKthSmallest(node->right, k); -} - -// Depth-First Search -// Runtime: O(n) -// Space: O(1) -int kthSmallest(struct TreeNode* root, int k){ - return findKthSmallest(root, &k)->val; -} +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +struct TreeNode* findKthSmallest(struct TreeNode* node, int* k){ + if (node == NULL){ + return NULL; + } + + struct TreeNode* resultNode = findKthSmallest(node->left, k); + + if (resultNode != NULL){ + return resultNode; + } + + *k -= 1; + + if (*k == 0){ + return node; + } + + return findKthSmallest(node->right, k); +} + +// Depth-First Search +// Runtime: O(n) +// Space: O(1) +int kthSmallest(struct TreeNode* root, int k){ + return findKthSmallest(root, &k)->val; +} diff --git a/leetcode/src/2304.c b/leetcode/src/2304.c index d8cfcb2521..716c7ee4c6 100644 --- a/leetcode/src/2304.c +++ b/leetcode/src/2304.c @@ -1,42 +1,43 @@ -#define min(x,y)(((x)<(y))?(x):(y)) - -// DP up -> down. We are going down from gridline to gridline -// and collect the minumum cost path. -// Runtime : O(gridSize*gridColSize*gridColSize) -// Space: O(gridColSize) -int minPathCost(int** grid, int gridSize, int* gridColSize, int** moveCost, int moveCostSize, int* moveCostColSize){ - int* dp = (int*)calloc(gridColSize[0], sizeof(int)); - int* newDp = (int*)calloc(gridColSize[0], sizeof(int)); - - for(int i = 0; i < gridSize - 1; i++){ - int currGridColSize = gridColSize[i]; - for(int j = 0; j < currGridColSize; j++){ - newDp[j] = -1; - } - - for(int j = 0; j < currGridColSize; j++){ - int currGridItem = grid[i][j]; - for(int z = 0; z < currGridColSize; z++){ - int currMoveCost = dp[j] + moveCost[currGridItem][z] + currGridItem; - - newDp[z] = (newDp[z] == -1) ? currMoveCost : min(newDp[z], currMoveCost); - } - } - - for(int j = 0; j < currGridColSize; j++){ - dp[j] = newDp[j]; - } - } - - // Find minimum value. - int minValue = dp[0] + grid[gridSize - 1][0]; - for(int j = 1; j < gridColSize[0]; j++){ - minValue = min(minValue, dp[j] + grid[gridSize - 1][j]); - } - - // free resources - free(dp); - free(newDp); - - return minValue; -} +#include +#define min(x,y)(((x)<(y))?(x):(y)) + +// DP up -> down. We are going down from gridline to gridline +// and collect the minumum cost path. +// Runtime : O(gridSize*gridColSize*gridColSize) +// Space: O(gridColSize) +int minPathCost(int** grid, int gridSize, int* gridColSize, int** moveCost, int moveCostSize, int* moveCostColSize){ + int* dp = (int*)calloc(gridColSize[0], sizeof(int)); + int* newDp = (int*)calloc(gridColSize[0], sizeof(int)); + + for(int i = 0; i < gridSize - 1; i++){ + int currGridColSize = gridColSize[i]; + for(int j = 0; j < currGridColSize; j++){ + newDp[j] = -1; + } + + for(int j = 0; j < currGridColSize; j++){ + int currGridItem = grid[i][j]; + for(int z = 0; z < currGridColSize; z++){ + int currMoveCost = dp[j] + moveCost[currGridItem][z] + currGridItem; + + newDp[z] = (newDp[z] == -1) ? currMoveCost : min(newDp[z], currMoveCost); + } + } + + for(int j = 0; j < currGridColSize; j++){ + dp[j] = newDp[j]; + } + } + + // Find minimum value. + int minValue = dp[0] + grid[gridSize - 1][0]; + for(int j = 1; j < gridColSize[0]; j++){ + minValue = min(minValue, dp[j] + grid[gridSize - 1][j]); + } + + // free resources + free(dp); + free(newDp); + + return minValue; +} diff --git a/leetcode/src/231.c b/leetcode/src/231.c index 81ea2b0454..f450d2ebe8 100644 --- a/leetcode/src/231.c +++ b/leetcode/src/231.c @@ -1,6 +1,7 @@ -// Without loops/recursion. -// Runtime: O(1) -// Space: O(1) -bool isPowerOfTwo(int n){ - return (n > 0) && ((n & (n - 1)) == 0); -} +#include +// Without loops/recursion. +// Runtime: O(1) +// Space: O(1) +bool isPowerOfTwo(int n){ + return (n > 0) && ((n & (n - 1)) == 0); +} diff --git a/leetcode/src/234.c b/leetcode/src/234.c index b541bf6172..be5397315e 100644 --- a/leetcode/src/234.c +++ b/leetcode/src/234.c @@ -1,3 +1,5 @@ +#include +#include /** * Definition for singly-linked list. * struct ListNode { diff --git a/leetcode/src/236.c b/leetcode/src/236.c index 71235c4e64..b7d490d1cb 100644 --- a/leetcode/src/236.c +++ b/leetcode/src/236.c @@ -1,82 +1,84 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -// The list for TreeNodes. -struct ListItem { - struct TreeNode* node; // TreeNode pointer - struct ListItem* next; // Pointer to the next ListItem -}; - -bool findTargetPath(struct TreeNode* node, struct TreeNode* target, struct ListItem* path){ - if (node == NULL){ - return false; - } - - struct ListItem* pathItem = malloc(sizeof(struct ListItem)); - pathItem->node = node; - pathItem->next = NULL; - path->next = pathItem; - - if (node->val == target->val){ - return true; - } - - if (findTargetPath(node->left, target, pathItem)){ - return true; - } - - if (findTargetPath(node->right, target, pathItem)){ - return true; - } - - path->next = NULL; - free(pathItem); - return false; -} - -void freeList(struct ListItem* target){ - if (target->next != NULL){ - freeList(target->next); - } - - free(target); -} - - -// Find full path for p and q. -// Find the longest common path in paths. - -// Runtime: O(n) -// Space: O(n) -struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { - struct ListItem* pPath = malloc(sizeof(struct ListItem)); - struct ListItem* qPath = malloc(sizeof(struct ListItem)); - - findTargetPath(root, p, pPath); - findTargetPath(root, q, qPath); - - struct TreeNode* lowestTreeNode = NULL; - struct ListItem* pPathCursor = pPath->next; - struct ListItem* qPathCursor = qPath->next; - while(pPathCursor != NULL && qPathCursor != NULL) { - if (pPathCursor->node->val == qPathCursor->node->val){ - lowestTreeNode = pPathCursor->node; - pPathCursor = pPathCursor->next; - qPathCursor = qPathCursor->next; - continue; - } - - break; - } - - freeList(pPath); - freeList(qPath); - - return lowestTreeNode; -} +#include +#include +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +// The list for TreeNodes. +struct ListItem { + struct TreeNode* node; // TreeNode pointer + struct ListItem* next; // Pointer to the next ListItem +}; + +bool findTargetPath(struct TreeNode* node, struct TreeNode* target, struct ListItem* path){ + if (node == NULL){ + return false; + } + + struct ListItem* pathItem = malloc(sizeof(struct ListItem)); + pathItem->node = node; + pathItem->next = NULL; + path->next = pathItem; + + if (node->val == target->val){ + return true; + } + + if (findTargetPath(node->left, target, pathItem)){ + return true; + } + + if (findTargetPath(node->right, target, pathItem)){ + return true; + } + + path->next = NULL; + free(pathItem); + return false; +} + +void freeList(struct ListItem* target){ + if (target->next != NULL){ + freeList(target->next); + } + + free(target); +} + + +// Find full path for p and q. +// Find the longest common path in paths. + +// Runtime: O(n) +// Space: O(n) +struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { + struct ListItem* pPath = malloc(sizeof(struct ListItem)); + struct ListItem* qPath = malloc(sizeof(struct ListItem)); + + findTargetPath(root, p, pPath); + findTargetPath(root, q, qPath); + + struct TreeNode* lowestTreeNode = NULL; + struct ListItem* pPathCursor = pPath->next; + struct ListItem* qPathCursor = qPath->next; + while(pPathCursor != NULL && qPathCursor != NULL) { + if (pPathCursor->node->val == qPathCursor->node->val){ + lowestTreeNode = pPathCursor->node; + pPathCursor = pPathCursor->next; + qPathCursor = qPathCursor->next; + continue; + } + + break; + } + + freeList(pPath); + freeList(qPath); + + return lowestTreeNode; +} diff --git a/leetcode/src/242.c b/leetcode/src/242.c index 9b4abbf6a0..41698fd54b 100644 --- a/leetcode/src/242.c +++ b/leetcode/src/242.c @@ -1,3 +1,6 @@ +#include +#include +#include bool isAnagram(char *s, char *t) { int n = strlen(s); diff --git a/leetcode/src/2482.c b/leetcode/src/2482.c index df9f702dec..4a8bdfebdb 100644 --- a/leetcode/src/2482.c +++ b/leetcode/src/2482.c @@ -1,42 +1,43 @@ -/** - * Return an array of arrays of size *returnSize. - * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). - */ - -// Calculating ones on each row and column. -// Runtime: O(n * m) -// Space: O(n + m) -int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize, int** returnColumnSizes){ - int n = gridSize; - int m = gridColSize[0]; - - int** result = malloc(gridSize * sizeof(int*)); - for (int i = 0; i < n; i++){ - result[i] = malloc(m * sizeof(int)); - } - - int* onesRows = calloc(n, sizeof(int)); - int* onesCols = calloc(m, sizeof(int)); - for (int i = 0; i < n; i++){ - for (int j = 0; j < m; j++){ - if (grid[i][j] == 1){ - onesRows[i] += 1; - onesCols[j] += 1; - } - } - } - - for (int i = 0; i < gridSize; i++){ - for (int j = 0; j < gridColSize[i]; j++){ - result[i][j] = onesRows[i] + onesCols[j] - (m - onesRows[i]) - (n - onesCols[j]); - } - } - - free(onesRows); - free(onesCols); - - *returnSize = gridSize; - *returnColumnSizes = gridColSize; - return result; -} +#include +/** + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ + +// Calculating ones on each row and column. +// Runtime: O(n * m) +// Space: O(n + m) +int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize, int** returnColumnSizes){ + int n = gridSize; + int m = gridColSize[0]; + + int** result = malloc(gridSize * sizeof(int*)); + for (int i = 0; i < n; i++){ + result[i] = malloc(m * sizeof(int)); + } + + int* onesRows = calloc(n, sizeof(int)); + int* onesCols = calloc(m, sizeof(int)); + for (int i = 0; i < n; i++){ + for (int j = 0; j < m; j++){ + if (grid[i][j] == 1){ + onesRows[i] += 1; + onesCols[j] += 1; + } + } + } + + for (int i = 0; i < gridSize; i++){ + for (int j = 0; j < gridColSize[i]; j++){ + result[i][j] = onesRows[i] + onesCols[j] - (m - onesRows[i]) - (n - onesCols[j]); + } + } + + free(onesRows); + free(onesCols); + + *returnSize = gridSize; + *returnColumnSizes = gridColSize; + return result; +} diff --git a/leetcode/src/2501.c b/leetcode/src/2501.c index 87cfa2702b..4c76d295bf 100644 --- a/leetcode/src/2501.c +++ b/leetcode/src/2501.c @@ -1,52 +1,53 @@ -#define max(a,b) (((a)>(b))?(a):(b)) - -int longestSquareStreakDp(int* numsSet, int numsSetSize, int* dp, long num){ - if (dp[num] != 0){ - return dp[num]; - } - - long numSquare = num * num; - - dp[num] = 1; - if (numSquare <= numsSetSize && numsSet[numSquare] == 1){ - dp[num] += longestSquareStreakDp(numsSet, numsSetSize, dp, numSquare); - } - - return dp[num]; -} - -// Dynamic approach. Up -> down. -// Runtime: O(numsSize) -// Space: O(max(nums)) -int longestSquareStreak(int* nums, int numsSize){ - // Find nums maximum - int numMax = 0; - for(int i = 0; i < numsSize; i++){ - numMax = max(numMax, nums[i]); - } - - int* numsSet = calloc(numMax + 1, sizeof(int)); - int* dp = calloc(numMax + 1, sizeof(int)); - - // Init set of nums - for(int i = 0; i < numsSize; i++){ - numsSet[nums[i]] = 1; - } - - // Find result - int result = -1; - for(int i = 0; i < numsSize; i++){ - long num = nums[i]; - long numSquare = num * num; - - if (numSquare > numMax || numsSet[numSquare] == 0){ - continue; - } - - result = max(result, 1 + longestSquareStreakDp(numsSet, numMax, dp, numSquare)); - } - - free(dp); - free(numsSet); - return result; -} +#include +#define max(a,b) (((a)>(b))?(a):(b)) + +int longestSquareStreakDp(int* numsSet, int numsSetSize, int* dp, long num){ + if (dp[num] != 0){ + return dp[num]; + } + + long numSquare = num * num; + + dp[num] = 1; + if (numSquare <= numsSetSize && numsSet[numSquare] == 1){ + dp[num] += longestSquareStreakDp(numsSet, numsSetSize, dp, numSquare); + } + + return dp[num]; +} + +// Dynamic approach. Up -> down. +// Runtime: O(numsSize) +// Space: O(max(nums)) +int longestSquareStreak(int* nums, int numsSize){ + // Find nums maximum + int numMax = 0; + for(int i = 0; i < numsSize; i++){ + numMax = max(numMax, nums[i]); + } + + int* numsSet = calloc(numMax + 1, sizeof(int)); + int* dp = calloc(numMax + 1, sizeof(int)); + + // Init set of nums + for(int i = 0; i < numsSize; i++){ + numsSet[nums[i]] = 1; + } + + // Find result + int result = -1; + for(int i = 0; i < numsSize; i++){ + long num = nums[i]; + long numSquare = num * num; + + if (numSquare > numMax || numsSet[numSquare] == 0){ + continue; + } + + result = max(result, 1 + longestSquareStreakDp(numsSet, numMax, dp, numSquare)); + } + + free(dp); + free(numsSet); + return result; +} diff --git a/leetcode/src/278.c b/leetcode/src/278.c index ec292d73b9..67be3dbfc6 100644 --- a/leetcode/src/278.c +++ b/leetcode/src/278.c @@ -1,3 +1,4 @@ +#include // Forward declaration of isBadVersion API. bool isBadVersion(int version); diff --git a/leetcode/src/28.c b/leetcode/src/28.c index ad11969e82..a27210cce5 100644 --- a/leetcode/src/28.c +++ b/leetcode/src/28.c @@ -1,3 +1,5 @@ +#include +#include /* * brute force approach * time complexity: O(mn) diff --git a/leetcode/src/32.c b/leetcode/src/32.c index ce05249af9..7e5abe6cdc 100644 --- a/leetcode/src/32.c +++ b/leetcode/src/32.c @@ -1,60 +1,62 @@ -#define max(x,y)(((x)>(y))?(x):(y)) - -const int notCalculated = -2; -const int notValid = -1; - -int getEndValidIndexFromDp(int* dp, char* s, int index, int lenS){ - if (index >= lenS){ - return notValid; - } - - if (dp[index] == notCalculated){ - dp[index] = getEndValidIndex(dp, s, index, lenS); - } - - return dp[index]; -} - -int getEndValidIndex(int* dp, char* s, int index, int lenS){ - if (s[index] == '('){ - if (index + 1 >= lenS){ - return notValid; - } - - if (s[index + 1] == ')'){ - return max(index + 1, getEndValidIndexFromDp(dp, s, index + 2, lenS)); - } - - int nextEndValidIndex = getEndValidIndexFromDp(dp, s, index + 1, lenS); - if (nextEndValidIndex == notValid || nextEndValidIndex + 1 >= lenS || s[nextEndValidIndex + 1] != ')') { - return notValid; - } - - return max(nextEndValidIndex + 1, getEndValidIndexFromDp(dp, s, nextEndValidIndex + 2, lenS)); - } - - return notValid; -} - -// Dynamic Programming. UP -> down approach. -// Runtime: O(n) -// Space: O(n) -int longestValidParentheses(char * s){ - int lenS = strlen(s); - if (lenS == 0){ - return 0; - } - - int* dp = malloc(lenS * sizeof(int)); - for(int i = 0; i < lenS; i++){ - dp[i] = notCalculated; - } - - int result = 0; - for(int i = 0; i < lenS; i++){ - result = max(result, getEndValidIndexFromDp(dp, s, i, lenS) - i + 1); - } - - free(dp); - return result; -} +#include +#include +#define max(x,y)(((x)>(y))?(x):(y)) + +const int notCalculated = -2; +const int notValid = -1; + +int getEndValidIndexFromDp(int* dp, char* s, int index, int lenS){ + if (index >= lenS){ + return notValid; + } + + if (dp[index] == notCalculated){ + dp[index] = getEndValidIndex(dp, s, index, lenS); + } + + return dp[index]; +} + +int getEndValidIndex(int* dp, char* s, int index, int lenS){ + if (s[index] == '('){ + if (index + 1 >= lenS){ + return notValid; + } + + if (s[index + 1] == ')'){ + return max(index + 1, getEndValidIndexFromDp(dp, s, index + 2, lenS)); + } + + int nextEndValidIndex = getEndValidIndexFromDp(dp, s, index + 1, lenS); + if (nextEndValidIndex == notValid || nextEndValidIndex + 1 >= lenS || s[nextEndValidIndex + 1] != ')') { + return notValid; + } + + return max(nextEndValidIndex + 1, getEndValidIndexFromDp(dp, s, nextEndValidIndex + 2, lenS)); + } + + return notValid; +} + +// Dynamic Programming. UP -> down approach. +// Runtime: O(n) +// Space: O(n) +int longestValidParentheses(char * s){ + int lenS = strlen(s); + if (lenS == 0){ + return 0; + } + + int* dp = malloc(lenS * sizeof(int)); + for(int i = 0; i < lenS; i++){ + dp[i] = notCalculated; + } + + int result = 0; + for(int i = 0; i < lenS; i++){ + result = max(result, getEndValidIndexFromDp(dp, s, i, lenS) - i + 1); + } + + free(dp); + return result; +} diff --git a/leetcode/src/367.c b/leetcode/src/367.c index e05eb646a0..c9c3f25713 100644 --- a/leetcode/src/367.c +++ b/leetcode/src/367.c @@ -1,3 +1,4 @@ +#include bool isPerfectSquare(int num) { for (long i = 1; i * i <= num; i++) diff --git a/leetcode/src/37.c b/leetcode/src/37.c index 7d8cae115e..2391e538ba 100644 --- a/leetcode/src/37.c +++ b/leetcode/src/37.c @@ -1,88 +1,90 @@ -int** initSet(int size){ - int** result = (int**) malloc(size * sizeof(int*)); - for (int i = 0; i < size; i++) { - result[i] = (int*)calloc(size, sizeof(int)); - } - - return result; -} - -// Returns the id of triplet which the point (i, j) belongs to -int getTripletId(int i, int j){ - return (i / 3) * 3 + (j / 3); -} - -// Recursive function which populates sudoku board. -bool sudokuSolver(int startI, int startJ, char** board, int boardSize, int* boardColSize, int** horizontalsSets, int** verticalsSets, int** tripletsSets){ - for (int i = startI; i < boardSize; i++) { - for (int j = startJ; j < boardColSize[i]; j++) { - if (board[i][j] != '.'){ - continue; - } - - // Find the sets of the current point (i, j) - int* horizontalSet = horizontalsSets[i]; - int* verticalSet = verticalsSets[j]; - int* tripletsSet = tripletsSets[getTripletId(i, j)]; - - for (int z = 1; z < 10; z++) { - if (horizontalSet[z] || verticalSet[z] || tripletsSet[z]){ - continue; - } - - // If the z doesn't belong to occupations sets, we check this value to be in place - horizontalSet[z] = 1; - verticalSet[z] = 1; - tripletsSet[z] = 1; - - if (sudokuSolver(i, j + 1, board, boardSize, boardColSize, horizontalsSets, verticalsSets, tripletsSets)){ - board[i][j] = z + '0'; - return true; - } - - horizontalSet[z] = 0; - verticalSet[z] = 0; - tripletsSet[z] = 0; - } - - // We tried all possible values in range 1-10. No variants - returns false; - return false; - } - - // startJ to begin of the row. - startJ = 0; - } - - // Reach it when the end of the board - then all previous values are setup correctly. - return true; -} - -// Use backtracking -void solveSudoku(char** board, int boardSize, int* boardColSize){ - // Declare sets for cheking occupation of numbers by horizontals, verticals lines and triplets. - int** horizontalsSets = initSet(boardSize + 1); - int** verticalsSets = initSet(boardSize + 1); - int** tripletsSets = initSet(getTripletId(boardSize + 1, boardSize + 1)); - - // Populate sets with values from the board. - for (int i = 0; i < boardSize; i++) { - for (int j = 0; j < boardColSize[i]; j++) { - if (board[i][j] == '.'){ - continue; - } - - int value = board[i][j] - '0'; - horizontalsSets[i][value] = 1; - verticalsSets[j][value] = 1; - tripletsSets[getTripletId(i, j)][value] = 1; - } - } - - // Solving - sudokuSolver(0, 0, board, boardSize, boardColSize, horizontalsSets, verticalsSets, tripletsSets); - - // Free resources - free(horizontalsSets); - free(verticalsSets); - free(tripletsSets); -} +#include +#include +int** initSet(int size){ + int** result = (int**) malloc(size * sizeof(int*)); + for (int i = 0; i < size; i++) { + result[i] = (int*)calloc(size, sizeof(int)); + } + + return result; +} + +// Returns the id of triplet which the point (i, j) belongs to +int getTripletId(int i, int j){ + return (i / 3) * 3 + (j / 3); +} + +// Recursive function which populates sudoku board. +bool sudokuSolver(int startI, int startJ, char** board, int boardSize, int* boardColSize, int** horizontalsSets, int** verticalsSets, int** tripletsSets){ + for (int i = startI; i < boardSize; i++) { + for (int j = startJ; j < boardColSize[i]; j++) { + if (board[i][j] != '.'){ + continue; + } + + // Find the sets of the current point (i, j) + int* horizontalSet = horizontalsSets[i]; + int* verticalSet = verticalsSets[j]; + int* tripletsSet = tripletsSets[getTripletId(i, j)]; + + for (int z = 1; z < 10; z++) { + if (horizontalSet[z] || verticalSet[z] || tripletsSet[z]){ + continue; + } + + // If the z doesn't belong to occupations sets, we check this value to be in place + horizontalSet[z] = 1; + verticalSet[z] = 1; + tripletsSet[z] = 1; + + if (sudokuSolver(i, j + 1, board, boardSize, boardColSize, horizontalsSets, verticalsSets, tripletsSets)){ + board[i][j] = z + '0'; + return true; + } + + horizontalSet[z] = 0; + verticalSet[z] = 0; + tripletsSet[z] = 0; + } + + // We tried all possible values in range 1-10. No variants - returns false; + return false; + } + + // startJ to begin of the row. + startJ = 0; + } + + // Reach it when the end of the board - then all previous values are setup correctly. + return true; +} + +// Use backtracking +void solveSudoku(char** board, int boardSize, int* boardColSize){ + // Declare sets for cheking occupation of numbers by horizontals, verticals lines and triplets. + int** horizontalsSets = initSet(boardSize + 1); + int** verticalsSets = initSet(boardSize + 1); + int** tripletsSets = initSet(getTripletId(boardSize + 1, boardSize + 1)); + + // Populate sets with values from the board. + for (int i = 0; i < boardSize; i++) { + for (int j = 0; j < boardColSize[i]; j++) { + if (board[i][j] == '.'){ + continue; + } + + int value = board[i][j] - '0'; + horizontalsSets[i][value] = 1; + verticalsSets[j][value] = 1; + tripletsSets[getTripletId(i, j)][value] = 1; + } + } + + // Solving + sudokuSolver(0, 0, board, boardSize, boardColSize, horizontalsSets, verticalsSets, tripletsSets); + + // Free resources + free(horizontalsSets); + free(verticalsSets); + free(tripletsSets); +} diff --git a/leetcode/src/38.c b/leetcode/src/38.c index 599655468d..8c3f2568fd 100644 --- a/leetcode/src/38.c +++ b/leetcode/src/38.c @@ -1,3 +1,5 @@ +#include +#include char *countAndSay(int n) { // Calculating the length of array diff --git a/leetcode/src/387.c b/leetcode/src/387.c index cbc78b7e53..9ca4579a86 100644 --- a/leetcode/src/387.c +++ b/leetcode/src/387.c @@ -1,3 +1,5 @@ +#include +#include int firstUniqChar(char *s) { int *arr = calloc(256, sizeof(int)); diff --git a/leetcode/src/404.c b/leetcode/src/404.c index 260c7c0b05..beb274eb2a 100644 --- a/leetcode/src/404.c +++ b/leetcode/src/404.c @@ -1,3 +1,6 @@ +#include +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; bool isleaf(struct TreeNode *root) { return root->left == NULL && root->right == NULL; diff --git a/leetcode/src/42.c b/leetcode/src/42.c index 7c49239740..04287f2ef9 100644 --- a/leetcode/src/42.c +++ b/leetcode/src/42.c @@ -1,27 +1,28 @@ -#define max(x,y)(((x)>(y))?(x):(y)) -#define min(x,y)(((x)<(y))?(x):(y)) - -// Max stack. Runtime: O(n), Space: O(n) -// Algorithm description: -// - Calculate the stack of maximums from right board. -// - For each index find left maximum and right maximum of height -// - The each index if heights could place nor greater than minimum of left and right max minus curr height -// - Sum all index in result -int trap(int* height, int heightSize){ - int* rightMaxStack = malloc(heightSize * sizeof(int)); - rightMaxStack[heightSize - 1] = height[heightSize - 1]; - - for (int i = heightSize - 2; i >= 0; i--){ - rightMaxStack[i] = max(rightMaxStack[i + 1], height[i]); - } - - int leftMax = 0; - int result = 0; - for (int i = 0; i < heightSize; i++){ - leftMax = max(leftMax, height[i]); - result += max(0, min(leftMax, rightMaxStack[i]) - height[i]); - } - - free(rightMaxStack); - return result; -} +#include +#define max(x,y)(((x)>(y))?(x):(y)) +#define min(x,y)(((x)<(y))?(x):(y)) + +// Max stack. Runtime: O(n), Space: O(n) +// Algorithm description: +// - Calculate the stack of maximums from right board. +// - For each index find left maximum and right maximum of height +// - The each index if heights could place nor greater than minimum of left and right max minus curr height +// - Sum all index in result +int trap(int* height, int heightSize){ + int* rightMaxStack = malloc(heightSize * sizeof(int)); + rightMaxStack[heightSize - 1] = height[heightSize - 1]; + + for (int i = heightSize - 2; i >= 0; i--){ + rightMaxStack[i] = max(rightMaxStack[i + 1], height[i]); + } + + int leftMax = 0; + int result = 0; + for (int i = 0; i < heightSize; i++){ + leftMax = max(leftMax, height[i]); + result += max(0, min(leftMax, rightMaxStack[i]) - height[i]); + } + + free(rightMaxStack); + return result; +} diff --git a/leetcode/src/442.c b/leetcode/src/442.c index 7bfdfb4534..9f53ea1336 100644 --- a/leetcode/src/442.c +++ b/leetcode/src/442.c @@ -1,3 +1,4 @@ +#include int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; } int *findDuplicates(int *nums, int numsSize, int *returnSize) diff --git a/leetcode/src/45.c b/leetcode/src/45.c index 4deaab4594..f1e688feab 100644 --- a/leetcode/src/45.c +++ b/leetcode/src/45.c @@ -1,50 +1,51 @@ -// Breadth-first search, imitation. -// Runtime: O(n) -// Space: O(n) -int jump(int* nums, int numsSize) { - if (numsSize == 1) { - return 0; - } - - int step = 1; - int* visitedCells = calloc(numsSize, sizeof(int)); - - int* queue = malloc(numsSize * sizeof(int)); - queue[0] = 0; - int queueLength = 1; - - while (queueLength > 0){ - int* nextQueue = malloc(numsSize * sizeof(int)); - int nextQueueLength = 0; - - for (int i = 0; i < queueLength; i++) { - int cell = queue[i]; - int jump = nums[cell]; - - if (cell + jump >= numsSize - 1) { - free(visitedCells); - free(queue); - free(nextQueue); - return step; - } - - // populate next queue wave for searching - for (int nextCell = cell; nextCell <= cell + jump; nextCell++) { - if (visitedCells[nextCell] == 0){ - nextQueue[nextQueueLength++] = nextCell; - visitedCells[nextCell] = 1; - } - } - } - - step++; - free(queue); - - queue = nextQueue; - queueLength = nextQueueLength; - } - - free(visitedCells); - free(queue); - return -1; -} +#include +// Breadth-first search, imitation. +// Runtime: O(n) +// Space: O(n) +int jump(int* nums, int numsSize) { + if (numsSize == 1) { + return 0; + } + + int step = 1; + int* visitedCells = calloc(numsSize, sizeof(int)); + + int* queue = malloc(numsSize * sizeof(int)); + queue[0] = 0; + int queueLength = 1; + + while (queueLength > 0){ + int* nextQueue = malloc(numsSize * sizeof(int)); + int nextQueueLength = 0; + + for (int i = 0; i < queueLength; i++) { + int cell = queue[i]; + int jump = nums[cell]; + + if (cell + jump >= numsSize - 1) { + free(visitedCells); + free(queue); + free(nextQueue); + return step; + } + + // populate next queue wave for searching + for (int nextCell = cell; nextCell <= cell + jump; nextCell++) { + if (visitedCells[nextCell] == 0){ + nextQueue[nextQueueLength++] = nextCell; + visitedCells[nextCell] = 1; + } + } + } + + step++; + free(queue); + + queue = nextQueue; + queueLength = nextQueueLength; + } + + free(visitedCells); + free(queue); + return -1; +} diff --git a/leetcode/src/520.c b/leetcode/src/520.c index 399c1c8956..de9ac12c14 100644 --- a/leetcode/src/520.c +++ b/leetcode/src/520.c @@ -1,3 +1,6 @@ +#include +#include +#include bool detectCapitalUse(char *word) { int len = strlen(word); diff --git a/leetcode/src/567.c b/leetcode/src/567.c index 268579a03d..d86808d216 100644 --- a/leetcode/src/567.c +++ b/leetcode/src/567.c @@ -1,67 +1,70 @@ -const int EnglishLettersNumber = 26; - -void countCharsForStringSlice(int* charsCounter, char* s, int length, int sign) { - for (int i = 0; i < length; i++) { - - charsCounter[s[i] - 'a'] += sign; - } -} - -// Sliding window -// Calculate number of chars in the current slide. -// Runtime: O(n) -// Space: O(1) - only number of english lowercase letters. -bool checkInclusion(char* s1, char* s2) { - int lengthS1 = strlen(s1); - int lengthS2 = strlen(s2); - - if (lengthS1 > lengthS2) { - - return false; - } - - int* charsCounter = calloc(EnglishLettersNumber, sizeof(int)); - - // We keep counters of s1 with '-' sign. It has to be offset by s2 chars - countCharsForStringSlice(charsCounter, s1, lengthS1, -1); - countCharsForStringSlice(charsCounter, s2, lengthS1, 1); - - int diffChars = 0; - for (int i = 0; i < EnglishLettersNumber; i++) { - if (charsCounter[i] != 0) { - diffChars++; - } - } - - if (diffChars == 0) { - return true; - } - - for (int i = 0; i < lengthS2 - lengthS1; i++) { - int charNumberLeft = s2[i] - 'a'; - int charNumberRight = s2[i + lengthS1] - 'a'; - - charsCounter[charNumberLeft] -= 1; - if (charsCounter[charNumberLeft] == 0) { - diffChars -= 1; - } - else if (charsCounter[charNumberLeft] == -1) { - diffChars += 1; - } - - charsCounter[charNumberRight] += 1; - if (charsCounter[charNumberRight] == 0) { - diffChars -= 1; - } - else if (charsCounter[charNumberRight] == 1) { - diffChars += 1; - } - - if (diffChars == 0) { - return true; - } - } - - free(charsCounter); - return false; -} +#include +#include +#include +const int EnglishLettersNumber = 26; + +void countCharsForStringSlice(int* charsCounter, char* s, int length, int sign) { + for (int i = 0; i < length; i++) { + + charsCounter[s[i] - 'a'] += sign; + } +} + +// Sliding window +// Calculate number of chars in the current slide. +// Runtime: O(n) +// Space: O(1) - only number of english lowercase letters. +bool checkInclusion(char* s1, char* s2) { + int lengthS1 = strlen(s1); + int lengthS2 = strlen(s2); + + if (lengthS1 > lengthS2) { + + return false; + } + + int* charsCounter = calloc(EnglishLettersNumber, sizeof(int)); + + // We keep counters of s1 with '-' sign. It has to be offset by s2 chars + countCharsForStringSlice(charsCounter, s1, lengthS1, -1); + countCharsForStringSlice(charsCounter, s2, lengthS1, 1); + + int diffChars = 0; + for (int i = 0; i < EnglishLettersNumber; i++) { + if (charsCounter[i] != 0) { + diffChars++; + } + } + + if (diffChars == 0) { + return true; + } + + for (int i = 0; i < lengthS2 - lengthS1; i++) { + int charNumberLeft = s2[i] - 'a'; + int charNumberRight = s2[i + lengthS1] - 'a'; + + charsCounter[charNumberLeft] -= 1; + if (charsCounter[charNumberLeft] == 0) { + diffChars -= 1; + } + else if (charsCounter[charNumberLeft] == -1) { + diffChars += 1; + } + + charsCounter[charNumberRight] += 1; + if (charsCounter[charNumberRight] == 0) { + diffChars -= 1; + } + else if (charsCounter[charNumberRight] == 1) { + diffChars += 1; + } + + if (diffChars == 0) { + return true; + } + } + + free(charsCounter); + return false; +} diff --git a/leetcode/src/617.c b/leetcode/src/617.c index 95fca003a1..b1b9560632 100644 --- a/leetcode/src/617.c +++ b/leetcode/src/617.c @@ -1,3 +1,5 @@ +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; struct TreeNode *newNode(int item) { struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode)); diff --git a/leetcode/src/66.c b/leetcode/src/66.c index e312940a88..57dbce971c 100644 --- a/leetcode/src/66.c +++ b/leetcode/src/66.c @@ -1,3 +1,4 @@ +#include /** * Note: The returned array must be malloced, assume caller calls free(). */ diff --git a/leetcode/src/669.c b/leetcode/src/669.c index f8842a3463..587d5a02a4 100644 --- a/leetcode/src/669.c +++ b/leetcode/src/669.c @@ -1,30 +1,28 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - - -// Depth-First Search -// Runtime: O(n) -// Space: O(1) -struct TreeNode* trimBST(struct TreeNode* root, int low, int high){ - if (root == NULL){ - return NULL; - } - - if (root->val > high){ - return trimBST(root->left, low, high); - } - - if (root->val < low){ - return trimBST(root->right, low, high); - } - - root->left = trimBST(root->left, low, high); - root->right = trimBST(root->right, low, high); - return root; -} +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + + +// Depth-First Search +// Runtime: O(n) +// Space: O(1) +struct TreeNode* trimBST(struct TreeNode* root, int low, int high){ + if (root == NULL){ + return NULL; + } + + if (root->val > high){ + return trimBST(root->left, low, high); + } + + if (root->val < low){ + return trimBST(root->right, low, high); + } + + root->left = trimBST(root->left, low, high); + root->right = trimBST(root->right, low, high); + return root; +} diff --git a/leetcode/src/684.c b/leetcode/src/684.c index e5de7faa1e..9fb504a508 100644 --- a/leetcode/src/684.c +++ b/leetcode/src/684.c @@ -1,49 +1,50 @@ -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int find(int* sets, int index){ - while (sets[index] != index){ - index = sets[index]; - } - - return index; -} - -void unionSet(int* sets, int i1, int i2){ - int i1Parent = find(sets, i1); - int i2Parent = find(sets, i2); - - sets[i1Parent] = i2Parent; -} - -// Union find -// Runtime: O(n) -// Space: O(n) -int* findRedundantConnection(int** edges, int edgesSize, int* edgesColSize, int* returnSize){ - int setsSize = edgesSize + 1; - int* sets = malloc(setsSize * sizeof(int)); - for (int i = 0; i < setsSize; i++){ - sets[i] = i; - } - - int* result = malloc(2 * sizeof(int)); - *returnSize = 2; - - for (int i = 0; i < edgesSize; i++){ - int* edge = edges[i]; - - int i0Parent = find(sets, edge[0]); - int i1Parent = find(sets, edge[1]); - - if (i0Parent == i1Parent){ - result[0] = edge[0]; - result[1] = edge[1]; - continue; - } - - unionSet(sets, i0Parent, i1Parent); - } - - free(sets); - return result; -} +#include +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int find(int* sets, int index){ + while (sets[index] != index){ + index = sets[index]; + } + + return index; +} + +void unionSet(int* sets, int i1, int i2){ + int i1Parent = find(sets, i1); + int i2Parent = find(sets, i2); + + sets[i1Parent] = i2Parent; +} + +// Union find +// Runtime: O(n) +// Space: O(n) +int* findRedundantConnection(int** edges, int edgesSize, int* edgesColSize, int* returnSize){ + int setsSize = edgesSize + 1; + int* sets = malloc(setsSize * sizeof(int)); + for (int i = 0; i < setsSize; i++){ + sets[i] = i; + } + + int* result = malloc(2 * sizeof(int)); + *returnSize = 2; + + for (int i = 0; i < edgesSize; i++){ + int* edge = edges[i]; + + int i0Parent = find(sets, edge[0]); + int i1Parent = find(sets, edge[1]); + + if (i0Parent == i1Parent){ + result[0] = edge[0]; + result[1] = edge[1]; + continue; + } + + unionSet(sets, i0Parent, i1Parent); + } + + free(sets); + return result; +} diff --git a/leetcode/src/700.c b/leetcode/src/700.c index 73cc1a5a2d..8d6ca97916 100644 --- a/leetcode/src/700.c +++ b/leetcode/src/700.c @@ -1,11 +1,9 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; struct TreeNode *searchBST(struct TreeNode *root, int val) { diff --git a/leetcode/src/701.c b/leetcode/src/701.c index 3f7b7c97f9..03ff383675 100644 --- a/leetcode/src/701.c +++ b/leetcode/src/701.c @@ -1,3 +1,5 @@ +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; struct TreeNode *insertIntoBST(struct TreeNode *root, int val) { if (root == NULL) diff --git a/leetcode/src/79.c b/leetcode/src/79.c index 3ac9d11fbc..13a0c253c6 100644 --- a/leetcode/src/79.c +++ b/leetcode/src/79.c @@ -1,60 +1,63 @@ -int getPointKey(int i, int j, int boardSize, int boardColSize){ - return boardSize * boardColSize * i + j; -} - -const int directionsSize = 4; -const int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; - -bool exitsWord(int i, int j, char** board, int boardSize, int* boardColSize, int wordIndex, char* word, int* vistedPointSet){ - if (board[i][j] != word[wordIndex]){ - return false; - } - - if (wordIndex == strlen(word) - 1){ - return true; - } - - for (int k = 0; k < directionsSize; k++){ - int nextI = i + directions[k][0]; - int nextJ = j + directions[k][1]; - - if (nextI < 0 || nextI >= boardSize || nextJ < 0 || nextJ >= boardColSize[i]){ - continue; - } - - int key = getPointKey(nextI, nextJ, boardSize, boardColSize[i]); - if (vistedPointSet[key] == 1){ - continue; - } - - vistedPointSet[key] = 1; - if (exitsWord(nextI, nextJ, board, boardSize, boardColSize, wordIndex + 1, word, vistedPointSet)){ - return true; - } - - vistedPointSet[key] = 0; - } - - return false; -} - - -// Use backtracking. -// Runtime: Runtime: O(n*m*4^len(word)) -bool exist(char** board, int boardSize, int* boardColSize, char* word){ - int* vistedPointSet = (int*) calloc(getPointKey(boardSize, boardColSize[0], boardSize, boardColSize[0]), sizeof(int)); - - for (int i = 0; i < boardSize; i++){ - for (int j = 0; j < boardColSize[i]; j++){ - int key = getPointKey(i, j, boardSize, boardColSize[i]); - vistedPointSet[key] = 1; - if (exitsWord(i, j, board, boardSize, boardColSize, 0, word, vistedPointSet)){ - return true; - }; - - vistedPointSet[key] = 0; - } - } - - return false; -} +#include +#include +#include +int getPointKey(int i, int j, int boardSize, int boardColSize){ + return boardSize * boardColSize * i + j; +} + +const int directionsSize = 4; +const int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + +bool exitsWord(int i, int j, char** board, int boardSize, int* boardColSize, int wordIndex, char* word, int* vistedPointSet){ + if (board[i][j] != word[wordIndex]){ + return false; + } + + if (wordIndex == strlen(word) - 1){ + return true; + } + + for (int k = 0; k < directionsSize; k++){ + int nextI = i + directions[k][0]; + int nextJ = j + directions[k][1]; + + if (nextI < 0 || nextI >= boardSize || nextJ < 0 || nextJ >= boardColSize[i]){ + continue; + } + + int key = getPointKey(nextI, nextJ, boardSize, boardColSize[i]); + if (vistedPointSet[key] == 1){ + continue; + } + + vistedPointSet[key] = 1; + if (exitsWord(nextI, nextJ, board, boardSize, boardColSize, wordIndex + 1, word, vistedPointSet)){ + return true; + } + + vistedPointSet[key] = 0; + } + + return false; +} + + +// Use backtracking. +// Runtime: Runtime: O(n*m*4^len(word)) +bool exist(char** board, int boardSize, int* boardColSize, char* word){ + int* vistedPointSet = (int*) calloc(getPointKey(boardSize, boardColSize[0], boardSize, boardColSize[0]), sizeof(int)); + + for (int i = 0; i < boardSize; i++){ + for (int j = 0; j < boardColSize[i]; j++){ + int key = getPointKey(i, j, boardSize, boardColSize[i]); + vistedPointSet[key] = 1; + if (exitsWord(i, j, board, boardSize, boardColSize, 0, word, vistedPointSet)){ + return true; + }; + + vistedPointSet[key] = 0; + } + } + + return false; +} diff --git a/leetcode/src/8.c b/leetcode/src/8.c index bf3f905d72..d5a6499d94 100644 --- a/leetcode/src/8.c +++ b/leetcode/src/8.c @@ -1,3 +1,6 @@ +#include +#include +#include int myAtoi(char *str) { int minusFlag = 0; diff --git a/leetcode/src/807.c b/leetcode/src/807.c index 1f51bdd753..8d1e50a7ea 100644 --- a/leetcode/src/807.c +++ b/leetcode/src/807.c @@ -1,32 +1,33 @@ -#define min(a,b) (((a)<(b))?(a):(b)) -#define max(a,b) (((a)>(b))?(a):(b)) - -// Collect maxes on each row and each column. -// Runtime: O(n * n) -// Space: O(n) -int maxIncreaseKeepingSkyline(int** grid, int gridSize, int* gridColSize){ - int* rowsMaxs = calloc(gridSize, sizeof(int)); - int* colsMaxs = calloc(gridSize, sizeof(int)); - - // Find max of each row and column - for(int i = 0; i < gridSize; i++){ - for (int j = 0; j < gridSize; j++){ - rowsMaxs[i] = max(rowsMaxs[i], grid[i][j]); - colsMaxs[j] = max(colsMaxs[j], grid[i][j]); - } - } - - int result = 0; - for(int i = 0; i < gridSize; i++){ - for (int j = 0; j < gridSize; j++){ - int rowMax = rowsMaxs[i]; - int colMax = colsMaxs[j]; - result += min(rowMax - grid[i][j], colMax - grid[i][j]); - } - } - - free(rowsMaxs); - free(colsMaxs); - - return result; -} +#include +#define min(a,b) (((a)<(b))?(a):(b)) +#define max(a,b) (((a)>(b))?(a):(b)) + +// Collect maxes on each row and each column. +// Runtime: O(n * n) +// Space: O(n) +int maxIncreaseKeepingSkyline(int** grid, int gridSize, int* gridColSize){ + int* rowsMaxs = calloc(gridSize, sizeof(int)); + int* colsMaxs = calloc(gridSize, sizeof(int)); + + // Find max of each row and column + for(int i = 0; i < gridSize; i++){ + for (int j = 0; j < gridSize; j++){ + rowsMaxs[i] = max(rowsMaxs[i], grid[i][j]); + colsMaxs[j] = max(colsMaxs[j], grid[i][j]); + } + } + + int result = 0; + for(int i = 0; i < gridSize; i++){ + for (int j = 0; j < gridSize; j++){ + int rowMax = rowsMaxs[i]; + int colMax = colsMaxs[j]; + result += min(rowMax - grid[i][j], colMax - grid[i][j]); + } + } + + free(rowsMaxs); + free(colsMaxs); + + return result; +} diff --git a/leetcode/src/82.c b/leetcode/src/82.c index 6f784c5993..a6fb3fc5df 100644 --- a/leetcode/src/82.c +++ b/leetcode/src/82.c @@ -1,3 +1,5 @@ +#include +struct ListNode { int val; struct ListNode *next; }; struct ListNode *deleteDuplicates(struct ListNode *head) { if (head == NULL) diff --git a/leetcode/src/841.c b/leetcode/src/841.c index cae224887e..1f3d78f11d 100644 --- a/leetcode/src/841.c +++ b/leetcode/src/841.c @@ -1,27 +1,29 @@ -void visitRooms(int key, int** rooms, int roomsSize, int* roomsColSize, int* visitedRooms){ - if (visitedRooms[key] == 1){ - return; - } - - visitedRooms[key] = 1; - for (int i = 0; i < roomsColSize[key]; i++){ - visitRooms(rooms[key][i], rooms, roomsSize, roomsColSize, visitedRooms); - } -} - -// Depth-first search -// Runtime: O(n) -// Space: O(n) -bool canVisitAllRooms(int** rooms, int roomsSize, int* roomsColSize){ - int* visitedRooms = calloc(roomsSize, sizeof(int)); - visitRooms(0, rooms, roomsSize, roomsColSize, visitedRooms); - - int visitedRoomsNumber = 0; - for (int i = 0; i < roomsSize; i++){ - if (visitedRooms[i] == 1){ - visitedRoomsNumber++; - } - } - - return visitedRoomsNumber == roomsSize; -} +#include +#include +void visitRooms(int key, int** rooms, int roomsSize, int* roomsColSize, int* visitedRooms){ + if (visitedRooms[key] == 1){ + return; + } + + visitedRooms[key] = 1; + for (int i = 0; i < roomsColSize[key]; i++){ + visitRooms(rooms[key][i], rooms, roomsSize, roomsColSize, visitedRooms); + } +} + +// Depth-first search +// Runtime: O(n) +// Space: O(n) +bool canVisitAllRooms(int** rooms, int roomsSize, int* roomsColSize){ + int* visitedRooms = calloc(roomsSize, sizeof(int)); + visitRooms(0, rooms, roomsSize, roomsColSize, visitedRooms); + + int visitedRoomsNumber = 0; + for (int i = 0; i < roomsSize; i++){ + if (visitedRooms[i] == 1){ + visitedRoomsNumber++; + } + } + + return visitedRoomsNumber == roomsSize; +} diff --git a/leetcode/src/9.c b/leetcode/src/9.c index 29c99c160c..ab94db1dd6 100644 --- a/leetcode/src/9.c +++ b/leetcode/src/9.c @@ -1,3 +1,4 @@ +#include bool isPalindrome(int x) { if (x < 0 || (x % 10 == 0 && x != 0)) diff --git a/leetcode/src/901.c b/leetcode/src/901.c index efa712b69c..6c62b53b2b 100644 --- a/leetcode/src/901.c +++ b/leetcode/src/901.c @@ -1,68 +1,69 @@ -// Use monotonic stack. -// Keep the stack of monotonically increasing price and index. - -// Runtime: O(n) -// Space: O(n) -typedef struct stack{ - int price; - int index; - struct stack* previous; -} Stack; - - -typedef struct { - int index; - Stack* stackPointer; - Stack* sentry; -} StockSpanner; - - -StockSpanner* stockSpannerCreate() { - Stack* sentry = (Stack *)malloc(sizeof(Stack)); - StockSpanner* result = (StockSpanner *)malloc(sizeof(StockSpanner)); - result->index = 0; - result->sentry = sentry; - result->stackPointer = sentry; - return result; -} - -int stockSpannerNext(StockSpanner* obj, int price) { - while(obj->stackPointer != obj->sentry && obj->stackPointer->price <= price){ - Stack* currStackPointer = obj->stackPointer; - obj->stackPointer = obj->stackPointer->previous; - free(currStackPointer); - } - - obj->index += 1; - int result = obj->index; - if (obj->stackPointer != obj->sentry){ - result -= obj->stackPointer->index; - } - - Stack* newStackItem = (Stack *)malloc(sizeof(Stack)); - newStackItem->index = obj->index; - newStackItem->price = price; - newStackItem->previous = obj->stackPointer; - obj->stackPointer = newStackItem; - - return result; -} - -void stockSpannerFree(StockSpanner* obj) { - while(obj->stackPointer != obj->sentry){ - Stack* currStackPointer = obj->stackPointer; - obj->stackPointer = obj->stackPointer->previous; - free(currStackPointer); - } - - free(obj->sentry); - free(obj); -} - -/** - * Your StockSpanner struct will be instantiated and called as such: - * StockSpanner* obj = stockSpannerCreate(); - * int param_1 = stockSpannerNext(obj, price); - - * stockSpannerFree(obj); - */ +#include +// Use monotonic stack. +// Keep the stack of monotonically increasing price and index. + +// Runtime: O(n) +// Space: O(n) +typedef struct stack{ + int price; + int index; + struct stack* previous; +} Stack; + + +typedef struct { + int index; + Stack* stackPointer; + Stack* sentry; +} StockSpanner; + + +StockSpanner* stockSpannerCreate() { + Stack* sentry = (Stack *)malloc(sizeof(Stack)); + StockSpanner* result = (StockSpanner *)malloc(sizeof(StockSpanner)); + result->index = 0; + result->sentry = sentry; + result->stackPointer = sentry; + return result; +} + +int stockSpannerNext(StockSpanner* obj, int price) { + while(obj->stackPointer != obj->sentry && obj->stackPointer->price <= price){ + Stack* currStackPointer = obj->stackPointer; + obj->stackPointer = obj->stackPointer->previous; + free(currStackPointer); + } + + obj->index += 1; + int result = obj->index; + if (obj->stackPointer != obj->sentry){ + result -= obj->stackPointer->index; + } + + Stack* newStackItem = (Stack *)malloc(sizeof(Stack)); + newStackItem->index = obj->index; + newStackItem->price = price; + newStackItem->previous = obj->stackPointer; + obj->stackPointer = newStackItem; + + return result; +} + +void stockSpannerFree(StockSpanner* obj) { + while(obj->stackPointer != obj->sentry){ + Stack* currStackPointer = obj->stackPointer; + obj->stackPointer = obj->stackPointer->previous; + free(currStackPointer); + } + + free(obj->sentry); + free(obj); +} + +/** + * Your StockSpanner struct will be instantiated and called as such: + * StockSpanner* obj = stockSpannerCreate(); + * int param_1 = stockSpannerNext(obj, price); + + * stockSpannerFree(obj); + */ diff --git a/leetcode/src/905.c b/leetcode/src/905.c index 802b97f081..4da711e332 100644 --- a/leetcode/src/905.c +++ b/leetcode/src/905.c @@ -1,3 +1,4 @@ +#include /** * 905. Sort Array By Parity * Given an array A of non-negative integers, return an array consisting of diff --git a/leetcode/src/931.c b/leetcode/src/931.c index b257c8c33e..cb1be4e3eb 100644 --- a/leetcode/src/931.c +++ b/leetcode/src/931.c @@ -1,37 +1,38 @@ -#define min(a,b) (((a)<(b))?(a):(b)) - -// Dynamic programming. -// Runtime O(n*n) -// Space O(n) -int minFallingPathSum(int** matrix, int matrixSize, int* matrixColSize){ - int* dp = calloc(matrixSize, sizeof(int)); - - for (int i = 0; i < matrixSize; i++){ - int* nextDp = calloc(matrixSize, sizeof(int)); - - for (int j = 0; j < matrixSize; j++){ - nextDp[j] = dp[j] + matrix[i][j]; - - // If not the first column - try to find minimum in prev column - if(j > 0){ - nextDp[j] = min(nextDp[j], dp[j - 1] + matrix[i][j]); - } - - // If not the last column - try to find minimum in next column - if (j < matrixSize - 1){ - nextDp[j] = min(nextDp[j], dp[j + 1] + matrix[i][j]); - } - } - - free(dp); - dp = nextDp; - } - - int result = dp[0]; - for (int j = 1; j < matrixSize; j++){ - result = min(result, dp[j]); - } - - free(dp); - return result; -} +#include +#define min(a,b) (((a)<(b))?(a):(b)) + +// Dynamic programming. +// Runtime O(n*n) +// Space O(n) +int minFallingPathSum(int** matrix, int matrixSize, int* matrixColSize){ + int* dp = calloc(matrixSize, sizeof(int)); + + for (int i = 0; i < matrixSize; i++){ + int* nextDp = calloc(matrixSize, sizeof(int)); + + for (int j = 0; j < matrixSize; j++){ + nextDp[j] = dp[j] + matrix[i][j]; + + // If not the first column - try to find minimum in prev column + if(j > 0){ + nextDp[j] = min(nextDp[j], dp[j - 1] + matrix[i][j]); + } + + // If not the last column - try to find minimum in next column + if (j < matrixSize - 1){ + nextDp[j] = min(nextDp[j], dp[j + 1] + matrix[i][j]); + } + } + + free(dp); + dp = nextDp; + } + + int result = dp[0]; + for (int j = 1; j < matrixSize; j++){ + result = min(result, dp[j]); + } + + free(dp); + return result; +} diff --git a/leetcode/src/938.c b/leetcode/src/938.c index 7c6636a830..29f3204d5a 100644 --- a/leetcode/src/938.c +++ b/leetcode/src/938.c @@ -1,3 +1,5 @@ +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; int rangeSumBST(struct TreeNode *root, int L, int R) { if (root == NULL) diff --git a/leetcode/src/94.c b/leetcode/src/94.c index d9abcc4508..4ec9737dbe 100644 --- a/leetcode/src/94.c +++ b/leetcode/src/94.c @@ -1,3 +1,5 @@ +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; void processTraversal(struct TreeNode *root, int *res, int *size) { if (!root) diff --git a/leetcode/src/953.c b/leetcode/src/953.c index cb13d85d1e..fd49fd048a 100644 --- a/leetcode/src/953.c +++ b/leetcode/src/953.c @@ -1,40 +1,43 @@ -#define min(x, y) (((x) < (y)) ? (x) : (y)) - -bool isWordLess(char* word1, char* word2, int* charOrder){ - int word1Length = strlen(word1); - int word2Length = strlen(word2); - - for(int i = 0; i < min(word1Length, word2Length); i++) { - int charWordsDiff = (charOrder[word1[i] - 'a'] - charOrder[word2[i] - 'a']); - - if (charWordsDiff < 0){ - return true; - } - - if (charWordsDiff > 0){ - return false; - } - } - - return word1Length <= word2Length; -} - -// Keep array-hashtable of order letters. -// Runtime: O(n) -// Space: O(1) -bool isAlienSorted(char ** words, int wordsSize, char * order){ - const int lowerCaseLettersNumber = 26; - int charorder[lowerCaseLettersNumber]; - - for(int i = 0; i < lowerCaseLettersNumber; i++) { - charorder[order[i] - 'a'] = i; - } - - for(int i = 0; i < wordsSize - 1; i++) { - if (!isWordLess(words[i], words[i + 1], charorder)){ - return false; - } - } - - return true; -} +#include +#include +#include +#define min(x, y) (((x) < (y)) ? (x) : (y)) + +bool isWordLess(char* word1, char* word2, int* charOrder){ + int word1Length = strlen(word1); + int word2Length = strlen(word2); + + for(int i = 0; i < min(word1Length, word2Length); i++) { + int charWordsDiff = (charOrder[word1[i] - 'a'] - charOrder[word2[i] - 'a']); + + if (charWordsDiff < 0){ + return true; + } + + if (charWordsDiff > 0){ + return false; + } + } + + return word1Length <= word2Length; +} + +// Keep array-hashtable of order letters. +// Runtime: O(n) +// Space: O(1) +bool isAlienSorted(char ** words, int wordsSize, char * order){ + const int lowerCaseLettersNumber = 26; + int charorder[lowerCaseLettersNumber]; + + for(int i = 0; i < lowerCaseLettersNumber; i++) { + charorder[order[i] - 'a'] = i; + } + + for(int i = 0; i < wordsSize - 1; i++) { + if (!isWordLess(words[i], words[i + 1], charorder)){ + return false; + } + } + + return true; +} diff --git a/leetcode/src/965.c b/leetcode/src/965.c index 0892be6cbc..be8eae5743 100644 --- a/leetcode/src/965.c +++ b/leetcode/src/965.c @@ -1,3 +1,6 @@ +#include +#include +struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; bool isUnivalTree(struct TreeNode *root) { if (root == NULL) diff --git a/leetcode/src/977.c b/leetcode/src/977.c index 66b23607af..c6546e1298 100644 --- a/leetcode/src/977.c +++ b/leetcode/src/977.c @@ -1,3 +1,4 @@ +#include /* 1st way: Using 2 pointers */ int *sortedSquares(int *A, int ASize, int *returnSize) { @@ -23,7 +24,7 @@ int *sortedSquares(int *A, int ASize, int *returnSize) /* 2nd way: Using qsort */ int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; } -int *sortedSquares(int *A, int ASize, int *returnSize) +int *sortedSquares_qsort(int *A, int ASize, int *returnSize) { int *res = malloc(ASize * sizeof(int)); for (int i = 0; i < ASize; i++) res[i] = A[i] * A[i]; diff --git a/leetcode/src/979.c b/leetcode/src/979.c index b6ad8b1b95..3c6b5d5245 100644 --- a/leetcode/src/979.c +++ b/leetcode/src/979.c @@ -1,47 +1,45 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct NodeDistributeInfo { - int distributeMoves; - int distributeExcess; -}; - -struct NodeDistributeInfo* getDisturb(struct TreeNode* node) { - struct NodeDistributeInfo* result = malloc(sizeof(struct NodeDistributeInfo)); - - if (node == NULL) { - result->distributeMoves = 0; - result->distributeExcess = 1; - return result; - } - - struct NodeDistributeInfo* leftDistribute = getDisturb(node->left); - struct NodeDistributeInfo* rightDistribute = getDisturb(node->right); - - int coinsToLeft = 1 - leftDistribute->distributeExcess; - int coinsToRight = 1 - rightDistribute->distributeExcess; - - // Calculate moves as excess and depth between left and right subtrees. - result->distributeMoves = leftDistribute->distributeMoves + rightDistribute->distributeMoves + abs(coinsToLeft) + abs(coinsToRight); - result->distributeExcess = node->val - coinsToLeft - coinsToRight; - - free(leftDistribute); - free(rightDistribute); - - return result; -} - -// Depth-first search . -// On each node-step we try to recombinate coins between left and right subtree. -// We know that coins are the same number that nodes, and we can get coins by depth -// Runtime: O(n) -// Space: O(1) -int distributeCoins(struct TreeNode* root) { - return getDisturb(root)->distributeMoves; -} +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +struct NodeDistributeInfo { + int distributeMoves; + int distributeExcess; +}; + +struct NodeDistributeInfo* getDisturb(struct TreeNode* node) { + struct NodeDistributeInfo* result = malloc(sizeof(struct NodeDistributeInfo)); + + if (node == NULL) { + result->distributeMoves = 0; + result->distributeExcess = 1; + return result; + } + + struct NodeDistributeInfo* leftDistribute = getDisturb(node->left); + struct NodeDistributeInfo* rightDistribute = getDisturb(node->right); + + int coinsToLeft = 1 - leftDistribute->distributeExcess; + int coinsToRight = 1 - rightDistribute->distributeExcess; + + // Calculate moves as excess and depth between left and right subtrees. + result->distributeMoves = leftDistribute->distributeMoves + rightDistribute->distributeMoves + abs(coinsToLeft) + abs(coinsToRight); + result->distributeExcess = node->val - coinsToLeft - coinsToRight; + + free(leftDistribute); + free(rightDistribute); + + return result; +} + +// Depth-first search . +// On each node-step we try to recombinate coins between left and right subtree. +// We know that coins are the same number that nodes, and we can get coins by depth +// Runtime: O(n) +// Space: O(1) +int distributeCoins(struct TreeNode* root) { + return getDisturb(root)->distributeMoves; +} diff --git a/leetcode/src/98.c b/leetcode/src/98.c index 775fe9e1b7..c4cc8cd0b9 100644 --- a/leetcode/src/98.c +++ b/leetcode/src/98.c @@ -1,24 +1,26 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -// Depth first search approach. -// Runtime: O(n) -// Space: O(1) -bool checkIsBst(struct TreeNode* node, bool leftBoundInf, int leftBound, bool rightBoundInf, int rightBound){ - return - (node == NULL) - || (leftBoundInf || node->val > leftBound) - && (rightBoundInf || node->val < rightBound) - && checkIsBst(node->left, leftBoundInf, leftBound, false, node->val) - && checkIsBst(node->right, false, node->val, rightBoundInf, rightBound); -} - -bool isValidBST(struct TreeNode* root){ - return checkIsBst(root, true, INT_MIN, true, INT_MAX); -} +#include +#include +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +// Depth first search approach. +// Runtime: O(n) +// Space: O(1) +bool checkIsBst(struct TreeNode* node, bool leftBoundInf, int leftBound, bool rightBoundInf, int rightBound){ + return + (node == NULL) + || (leftBoundInf || node->val > leftBound) + && (rightBoundInf || node->val < rightBound) + && checkIsBst(node->left, leftBoundInf, leftBound, false, node->val) + && checkIsBst(node->right, false, node->val, rightBoundInf, rightBound); +} + +bool isValidBST(struct TreeNode* root){ + return checkIsBst(root, true, INT_MIN, true, INT_MAX); +} diff --git a/leetcode/src/985.c b/leetcode/src/985.c index 7a2343ab22..57e9b12f05 100644 --- a/leetcode/src/985.c +++ b/leetcode/src/985.c @@ -1,39 +1,40 @@ -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ - -// collecting sum Runtime: O(len(queries)), Space: O(1) -int* sumEvenAfterQueries(int* nums, int numsSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize){ - int summ = 0; - int* result = malloc(queriesSize * sizeof(int)); - *returnSize = queriesSize; - - for(int i = 0; i < numsSize; i++){ - if (nums[i] % 2 == 0) { - summ += nums[i]; - } - } - - for(int i = 0; i < queriesSize; i++){ - int* query = queries[i]; - int val = query[0]; - int index = query[1]; - - // sub index value from summ if it's even - if (nums[index] % 2 == 0) { - summ -= nums[index]; - } - - // modify the nums[index] value - nums[index] += val; - - // add index value from summ if it's even - if (nums[index] % 2 == 0) { - summ += nums[index]; - } - - result[i] = summ; - } - - return result; -} +#include +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +// collecting sum Runtime: O(len(queries)), Space: O(1) +int* sumEvenAfterQueries(int* nums, int numsSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize){ + int summ = 0; + int* result = malloc(queriesSize * sizeof(int)); + *returnSize = queriesSize; + + for(int i = 0; i < numsSize; i++){ + if (nums[i] % 2 == 0) { + summ += nums[i]; + } + } + + for(int i = 0; i < queriesSize; i++){ + int* query = queries[i]; + int val = query[0]; + int index = query[1]; + + // sub index value from summ if it's even + if (nums[index] % 2 == 0) { + summ -= nums[index]; + } + + // modify the nums[index] value + nums[index] += val; + + // add index value from summ if it's even + if (nums[index] % 2 == 0) { + summ += nums[index]; + } + + result[i] = summ; + } + + return result; +} diff --git a/leetcode/src/997.c b/leetcode/src/997.c index a599555fc3..05104d4217 100644 --- a/leetcode/src/997.c +++ b/leetcode/src/997.c @@ -1,29 +1,30 @@ -// Using hashtable. -// Runtime: O(n + len(trust)) -// Space: O(n) -int findJudge(int n, int** trust, int trustSize, int* trustColSize){ - int* personsToTrust = calloc(n + 1, sizeof(int)); - int* personsFromTrust = calloc(n + 1, sizeof(int)); - - for(int i = 0; i < trustSize; i++){ - int* currentTrust = trust[i]; - personsToTrust[currentTrust[1]] += 1; - personsFromTrust[currentTrust[0]] += 1; - } - - int potentialJudjeNumber = -1; - for(int i = 1; i < n + 1; i++){ - if (personsToTrust[i] == n - 1 && personsFromTrust[i] == 0){ - if (potentialJudjeNumber > -1){ - return -1; - } - - potentialJudjeNumber = i; - } - } - - free(personsToTrust); - free(personsFromTrust); - - return potentialJudjeNumber; -} +#include +// Using hashtable. +// Runtime: O(n + len(trust)) +// Space: O(n) +int findJudge(int n, int** trust, int trustSize, int* trustColSize){ + int* personsToTrust = calloc(n + 1, sizeof(int)); + int* personsFromTrust = calloc(n + 1, sizeof(int)); + + for(int i = 0; i < trustSize; i++){ + int* currentTrust = trust[i]; + personsToTrust[currentTrust[1]] += 1; + personsFromTrust[currentTrust[0]] += 1; + } + + int potentialJudjeNumber = -1; + for(int i = 1; i < n + 1; i++){ + if (personsToTrust[i] == n - 1 && personsFromTrust[i] == 0){ + if (potentialJudjeNumber > -1){ + return -1; + } + + potentialJudjeNumber = i; + } + } + + free(personsToTrust); + free(personsFromTrust); + + return potentialJudjeNumber; +}