diff --git a/Common/Coding Templates/Binary Search.md b/Common/Coding Templates/Binary Search.md deleted file mode 100644 index e69de29..0000000 diff --git a/Common/Coding Templates/Binary Search/BinarySearch.cpp b/Common/Coding Templates/Binary Search/BinarySearch.cpp new file mode 100644 index 0000000..6b22b92 --- /dev/null +++ b/Common/Coding Templates/Binary Search/BinarySearch.cpp @@ -0,0 +1,110 @@ +#include +using namespace std; + +/* +------------------------------------------ +๐Ÿ”น Approach 1: Classic Iterative Binary Search +- Uses low, high, and mid pointers +- Repeatedly halves the search space +- Returns index if found +------------------------------------------ +*/ +int binarySearch(int arr[], int n, int target) { + int low = 0; + int high = n - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + if (arr[mid] == target) { + return mid; + } + else if (arr[mid] < target) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + + return -1; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 2: Cleaner Iterative Version +- Same logic as Approach 1 +- Direct return statements +- More concise code +------------------------------------------ +*/ +int binarySearch1(int arr[], int n, int target) { + int low = 0, high = n - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + if (arr[mid] == target) + return mid; + + if (arr[mid] < target) + low = mid + 1; + else + high = mid - 1; + } + + return -1; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 3: Recursive Binary Search +- Solves problem recursively +- Divides search range each call +- Elegant and educational +------------------------------------------ +*/ +int binarySearchRecursive(int arr[], int low, int high, int target) { + if (low > high) + return -1; + + int mid = low + (high - low) / 2; + + if (arr[mid] == target) + return mid; + + if (arr[mid] < target) + return binarySearchRecursive(arr, mid + 1, high, target); + + return binarySearchRecursive(arr, low, mid - 1, target); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 4: STL binary_search() +- Uses built-in C++ algorithm +- Returns true if element exists +- Simplest implementation +------------------------------------------ +*/ +bool binarySearch2(vector& arr, int target) { + return binary_search(arr.begin(), arr.end(), target); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 5: Using lower_bound() +- Finds first position where target + can be inserted +- Returns index if found +- Common in competitive programming +------------------------------------------ +*/ +int binarySearch3(vector& arr, int target) { + auto it = lower_bound(arr.begin(), arr.end(), target); + + if (it != arr.end() && *it == target) + return it - arr.begin(); + + return -1; +} \ No newline at end of file diff --git a/Common/Coding Templates/Binary Search/README.md b/Common/Coding Templates/Binary Search/README.md new file mode 100644 index 0000000..032ac7f --- /dev/null +++ b/Common/Coding Templates/Binary Search/README.md @@ -0,0 +1,82 @@ +# ๐Ÿ” Binary Search โ€“ C++ Solutions + +### ๐Ÿ’ก What is Binary Search? + +**Binary Search** is an efficient searching algorithm used to find an element in a **sorted array**. + +Instead of checking elements one by one like Linear Search, Binary Search repeatedly divides the search space into half. + +### Example + +Consider the sorted array: + +```text +[2, 5, 8, 12, 16, 23, 38] +``` + +Let's search for **16**. + +* Middle element = 12 +* Since 16 > 12, search the right half +* New middle = 23 +* Since 16 < 23, search the left half +* Element found = 16 โœ… + +This divide-and-conquer strategy makes Binary Search extremely fast. + +--- + +## ๐Ÿ“˜ What's Covered in This File? + +This program demonstrates **five different ways** to perform Binary Search in C++: + +| Approach | Description | +| -------- | -------------------------------- | +| 1 | Classic iterative Binary Search | +| 2 | Cleaner iterative implementation | +| 3 | Recursive Binary Search | +| 4 | STL `binary_search()` | +| 5 | STL `lower_bound()` | + +--- + +## ๐Ÿง  Why So Many Approaches? + +Each version introduces a different concept: + +* ๐Ÿ” Iterative problem solving +* ๐Ÿ”™ Recursion +* ๐Ÿ“š C++ Standard Template Library (STL) +* โšก Efficient searching techniques +* ๐Ÿ† Competitive programming patterns + +--- + +## ๐Ÿ—‚ File Structure + +* `BinarySearch.cpp` + +--- + +## ๐Ÿ” Sample Usage + +```cpp +#include +#include +using namespace std; + +int main() { + vector arr = {2, 5, 8, 12, 16, 23, 38}; + + int target = 16; + + int index = binarySearch(arr, target); + + if (index != -1) + cout << "Element found at index: " << index; + else + cout << "Element not found"; + + return 0; +} +``` diff --git a/Common/Coding Templates/README.md b/Common/Coding Templates/README.md new file mode 100644 index 0000000..31b31ea --- /dev/null +++ b/Common/Coding Templates/README.md @@ -0,0 +1,43 @@ +# ๐Ÿ’ป Coding Templates in C++ + +This section contains **essential coding patterns and templates** that are frequently used in problem solving, competitive programming, and technical interviews. + +These templates help you recognize patterns and solve problems efficiently instead of starting from scratch every time. + +--- + +## ๐Ÿ“˜ What's Inside? + +Each file provides a reusable template for a common algorithmic pattern. + +We will cover: + +* Binary Search patterns +* Two Pointers technique +* Sliding Window technique +* Optimized problem-solving approaches + +--- + +## ๐Ÿ“‚ Problem Directories + +Each problem will have its **own folder** with: +- Source code in C++ +- Step-by-step explanation + +### ๐Ÿ”— Problem List + +- [Binary Search](./Binary%20Search/BinarySearch.cpp) +- [Sliding Window](./Sliding%20Window/SlidingWindow.cpp) +- [Two Pointers](./Two%20Pointers/TwoPointers.cpp) + +> โš ๏ธ Visit Each file and check the code + +## ๐Ÿš€ Getting Started + +To run any C++ file: + +```bash +g++ filename.cpp -o output +./output +``` \ No newline at end of file diff --git a/Common/Coding Templates/Sliding Window.md b/Common/Coding Templates/Sliding Window.md deleted file mode 100644 index e69de29..0000000 diff --git a/Common/Coding Templates/Sliding Window/README.md b/Common/Coding Templates/Sliding Window/README.md new file mode 100644 index 0000000..95adc97 --- /dev/null +++ b/Common/Coding Templates/Sliding Window/README.md @@ -0,0 +1,86 @@ +# Sliding Window โ€“ C++ Solutions + +### ๐Ÿ’ก What is the Sliding Window Technique? + +The **Sliding Window** technique is a common algorithmic approach used to solve problems involving **subarrays**, **substrings**, or **contiguous sequences** efficiently. + +Instead of repeatedly processing the same elements, the window "slides" across the array or string while updating the result incrementally. + +This often reduces the time complexity from **O(nยฒ)** to **O(n)**. + +### Example + +Suppose we want to find the maximum sum of a subarray of size **3**: + +```text +[2, 1, 5, 1, 3, 2] +``` + +Window size = 3 + +```text +[2,1,5] โ†’ Sum = 8 +[1,5,1] โ†’ Sum = 7 +[5,1,3] โ†’ Sum = 9 +[1,3,2] โ†’ Sum = 6 +``` + +Maximum sum = **9** โœ… + +Instead of calculating every window from scratch, we: + +* Remove the outgoing element +* Add the incoming element +* Update the sum efficiently + +--- + +## ๐Ÿ“˜ What's Covered in This File? + +This program demonstrates **five common Sliding Window approaches** in C++: + +| Approach | Description | +| -------- | ------------------------------------------------------- | +| 1 | Fixed-size window (Maximum Sum Subarray) | +| 2 | Fixed-size window (Average of Subarrays) | +| 3 | Variable-size window (Smallest Subarray with Given Sum) | +| 4 | Longest Substring Without Repeating Characters | +| 5 | Maximum Consecutive Ones | + +--- + +## ๐Ÿง  Why Learn Sliding Window? + +The Sliding Window technique is widely used for: + +* ๐Ÿ“Š Array problems +* ๐Ÿ”ค String problems +* โšก Optimization +* ๐Ÿ† Competitive programming +* ๐Ÿ’ผ Technical interviews + +Many problems that seem O(nยฒ) can be solved in O(n) using Sliding Window. + +--- + +## ๐Ÿ—‚ File Structure + +* `SlidingWindow.cpp` + +--- + +## ๐Ÿ” Sample Usage + +```cpp +#include +#include +using namespace std; + +int main() { + vector arr = {2, 1, 5, 1, 3, 2}; + + cout << maxSumSubarray(arr, 3); + + return 0; +} +``` diff --git a/Common/Coding Templates/Sliding Window/SlidingWindow.cpp b/Common/Coding Templates/Sliding Window/SlidingWindow.cpp new file mode 100644 index 0000000..3c7d751 --- /dev/null +++ b/Common/Coding Templates/Sliding Window/SlidingWindow.cpp @@ -0,0 +1,150 @@ +#include +using namespace std; + +/* +------------------------------------------ +๐Ÿ”น Approach 1: Fixed-Size Sliding Window +(Maximum Sum Subarray of Size K) + +- Compute first window sum +- Slide window one position at a time +- Remove outgoing element +- Add incoming element +------------------------------------------ +*/ +int maxSumSubarray(vector& arr, int k) { + int n = arr.size(); + + int windowSum = 0; + + for (int i = 0; i < k; i++) { + windowSum += arr[i]; + } + + int maxSum = windowSum; + + for (int i = k; i < n; i++) { + windowSum += arr[i]; + windowSum -= arr[i - k]; + + maxSum = max(maxSum, windowSum); + } + + return maxSum; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 2: Fixed-Size Window +(Average of Every Subarray of Size K) + +- Maintain window sum +- Calculate average whenever + window size becomes K +------------------------------------------ +*/ +vector findAverages(vector& arr, int k) { + vector result; + + double windowSum = 0; + int start = 0; + + for (int end = 0; end < arr.size(); end++) { + windowSum += arr[end]; + + if (end >= k - 1) { + result.push_back(windowSum / k); + + windowSum -= arr[start]; + start++; + } + } + + return result; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 3: Variable-Size Window +(Smallest Subarray With Given Sum) + +- Expand window +- Shrink when sum >= target +- Track minimum length +------------------------------------------ +*/ +int smallestSubarray(vector& arr, int target) { + int start = 0; + int sum = 0; + + int minLength = INT_MAX; + + for (int end = 0; end < arr.size(); end++) { + sum += arr[end]; + + while (sum >= target) { + minLength = min(minLength, end - start + 1); + + sum -= arr[start]; + start++; + } + } + + return (minLength == INT_MAX) ? 0 : minLength; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 4: Longest Substring Without +Repeating Characters + +- Uses HashMap +- Expands and shrinks window +- Maintains unique characters +------------------------------------------ +*/ +int longestUniqueSubstring(string s) { + unordered_map freq; + + int start = 0; + int maxLength = 0; + + for (int end = 0; end < s.size(); end++) { + freq[s[end]]++; + + while (freq[s[end]] > 1) { + freq[s[start]]--; + start++; + } + + maxLength = max(maxLength, + end - start + 1); + } + + return maxLength; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 5: Maximum Consecutive Ones + +- Expand window while counting ones +- Reset when zero appears +- Track maximum streak +------------------------------------------ +*/ +int maxConsecutiveOnes(vector& nums) { + int current = 0; + int maximum = 0; + + for (int num : nums) { + if (num == 1) { + current++; + maximum = max(maximum, current); + } else { + current = 0; + } + } + + return maximum; +} \ No newline at end of file diff --git a/Common/Coding Templates/Two Pointers.md b/Common/Coding Templates/Two Pointers.md deleted file mode 100644 index e69de29..0000000 diff --git a/Common/Coding Templates/Two Pointers/README.md b/Common/Coding Templates/Two Pointers/README.md new file mode 100644 index 0000000..55247b5 --- /dev/null +++ b/Common/Coding Templates/Two Pointers/README.md @@ -0,0 +1,92 @@ +# Two Pointers โ€“ C++ Solutions + +### ๐Ÿ’ก What is the Two Pointers Technique? + +The **Two Pointers** technique is a powerful algorithmic pattern where two pointers traverse a data structure (usually an array or string) to solve problems efficiently. + +Instead of using nested loops, we move one or both pointers based on certain conditions, often reducing the time complexity from **O(nยฒ)** to **O(n)**. + +### Example + +Suppose we have a sorted array: + +```text +[1, 2, 3, 4, 6] +``` + +And we want to find two numbers whose sum is **6**. + +* Left pointer โ†’ 1 +* Right pointer โ†’ 6 + +```text +1 + 6 = 7 > 6 +``` + +Move right pointer left. + +```text +1 + 4 = 5 < 6 +``` + +Move left pointer right. + +```text +2 + 4 = 6 +``` + +โœ… Pair found! + +--- + +## ๐Ÿ“˜ What's Covered in This File? + +This program demonstrates **five common Two Pointer approaches** in C++: + +| Approach | Description | +| -------- | ----------------------------------- | +| 1 | Two Sum in Sorted Array | +| 2 | Remove Duplicates from Sorted Array | +| 3 | Move Zeroes to End | +| 4 | Valid Palindrome Check | +| 5 | Container With Most Water | + +--- + +## ๐Ÿง  Why Learn Two Pointers? + +The Two Pointers technique is useful for: + +* ๐Ÿ“Š Array manipulation +* ๐Ÿ”ค String processing +* โšก Optimization +* ๐Ÿ† Competitive programming +* ๐Ÿ’ผ Technical interviews + +Many brute-force O(nยฒ) solutions become O(n) using Two Pointers. + +--- + +## ๐Ÿ—‚ File Structure + +* `TwoPointers.cpp` + +--- + +## ๐Ÿ” Sample Usage + +```cpp +#include +#include +using namespace std; + +int main() { + vector arr = {1, 2, 3, 4, 6}; + + vector result = twoSum(arr, 6); + + cout << result[0] << " " << result[1]; + + return 0; +} +``` diff --git a/Common/Coding Templates/Two Pointers/TwoPointers.cpp b/Common/Coding Templates/Two Pointers/TwoPointers.cpp new file mode 100644 index 0000000..2f19e65 --- /dev/null +++ b/Common/Coding Templates/Two Pointers/TwoPointers.cpp @@ -0,0 +1,135 @@ +#include +using namespace std; + +/* +------------------------------------------ +๐Ÿ”น Approach 1: Two Sum in Sorted Array + +- Use left and right pointers +- Compare current sum with target +- Move pointers accordingly +------------------------------------------ +*/ +vector twoSum(vector& arr, int target) { + int left = 0; + int right = arr.size() - 1; + + while (left < right) { + int sum = arr[left] + arr[right]; + + if (sum == target) { + return {left, right}; + } + else if (sum < target) { + left++; + } + else { + right--; + } + } + + return {-1, -1}; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 2: Remove Duplicates +from Sorted Array + +- Slow pointer tracks unique position +- Fast pointer scans array +- Overwrites duplicates +------------------------------------------ +*/ +int removeDuplicates(vector& nums) { + if (nums.empty()) return 0; + + int left = 0; + + for (int right = 1; right < nums.size(); right++) { + if (nums[right] != nums[left]) { + left++; + nums[left] = nums[right]; + } + } + + return left + 1; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 3: Move Zeroes to End + +- One pointer finds non-zero elements +- Another places them correctly +- Maintains relative order +------------------------------------------ +*/ +void moveZeroes(vector& nums) { + int left = 0; + + for (int right = 0; right < nums.size(); right++) { + if (nums[right] != 0) { + swap(nums[left], nums[right]); + left++; + } + } +} + +/* +------------------------------------------ +๐Ÿ”น Approach 4: Valid Palindrome + +- Compare characters from both ends +- Move inward each iteration +- Returns true if palindrome +------------------------------------------ +*/ +bool isPalindrome(string s) { + int left = 0; + int right = s.size() - 1; + + while (left < right) { + if (s[left] != s[right]) { + return false; + } + + left++; + right--; + } + + return true; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 5: Container With Most Water + +- Two pointers start at ends +- Calculate area each step +- Move smaller height inward +------------------------------------------ +*/ +int maxArea(vector& height) { + int left = 0; + int right = height.size() - 1; + + int answer = 0; + + while (left < right) { + int width = right - left; + + int area = min(height[left], + height[right]) * width; + + answer = max(answer, area); + + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + + return answer; +} \ No newline at end of file diff --git a/Common/Combinatorics/Combination/Combination.cpp b/Common/Combinatorics/Combination/Combination.cpp new file mode 100644 index 0000000..539846b --- /dev/null +++ b/Common/Combinatorics/Combination/Combination.cpp @@ -0,0 +1,104 @@ +#include +using namespace std; + +/* +------------------------------------------ +๐Ÿ”น Approach 1: Factorial-Based nCr +- Uses n!, r!, (n-r)! +- Simple but can overflow easily +------------------------------------------ +*/ +long long factorial(int n) { + long long res = 1; + for (int i = 1; i <= n; i++) + res *= i; + return res; +} + +long long nCr1(int n, int r) { + return factorial(n) / + (factorial(r) * factorial(n - r)); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 2: Optimized Multiplicative Formula +- Avoids full factorial calculation +- Reduces overflow risk +------------------------------------------ +*/ +long long nCr2(int n, int r) { + if (r > n - r) + r = n - r; + + long long res = 1; + + for (int i = 0; i < r; i++) { + res *= (n - i); + res /= (i + 1); + } + + return res; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 3: Pascal's Triangle (Iterative DP) +- Builds row by row +- Based on recurrence: + nCr = (n-1)C(r-1) + (n-1)C(r) +------------------------------------------ +*/ +long long nCr3(int n, int r) { + vector> dp(n + 1, + vector(r + 1, 0)); + + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= min(i, r); j++) { + if (j == 0 || j == i) + dp[i][j] = 1; + else + dp[i][j] = dp[i - 1][j - 1] + + dp[i - 1][j]; + } + } + + return dp[n][r]; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 4: Recursive nCr +- Based on identity: + nCr = (n-1)C(r-1) + (n-1)C(r) +- Exponential time complexity +------------------------------------------ +*/ +long long nCr4(int n, int r) { + if (r == 0 || r == n) + return 1; + + return nCr4(n - 1, r - 1) + + nCr4(n - 1, r); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 5: DP (Memoization) +- Optimized recursive solution +- Avoids repeated calculations +------------------------------------------ +*/ +long long dp[100][100]; + +long long nCrMemo(int n, int r) { + if (r == 0 || r == n) + return 1; + + if (dp[n][r] != -1) + return dp[n][r]; + + return dp[n][r] = + nCrMemo(n - 1, r - 1) + + nCrMemo(n - 1, r); +} \ No newline at end of file diff --git a/Common/Combinatorics/Combination/README.md b/Common/Combinatorics/Combination/README.md new file mode 100644 index 0000000..1d4b437 --- /dev/null +++ b/Common/Combinatorics/Combination/README.md @@ -0,0 +1,64 @@ +# ๐Ÿงฎ Combinations (nCr) โ€“ C++ Solutions + +### ๐Ÿ’ก What is a Combination? + +A **combination** is a way of selecting items from a group where **order does NOT matter**. + +For example: + +* Choosing 2 students from {A, B, C}: + + * AB, AC, BC โ†’ these are combinations + +### ๐Ÿ“Œ Formula: + +{}^nC_r = \frac{n!}{r!(n-r)!} + +--- + +## ๐Ÿ“˜ Whatโ€™s Covered in This File? + +This program demonstrates **multiple ways to calculate nCr in C++**: + +| Approach | Description | +| -------- | -------------------------------- | +| 1 | Factorial-based nCr | +| 2 | Optimized multiplicative formula | +| 3 | Pascalโ€™s Triangle approach | +| 4 | Recursive nCr | +| 5 | DP (memoization) approach | + +--- + +## ๐Ÿง  Why Learn Combinations? + +Combinations are used in: + +* ๐Ÿ”ข Probability problems +* ๐Ÿ“Š Counting problems +* ๐Ÿง  Competitive programming +* ๐ŸŽฏ Interview questions +* ๐ŸŒณ DP & combinatorics problems + +--- + +## ๐Ÿ—‚ File Structure + +* `Combinations.cpp` + +--- + +## ๐Ÿ” Sample Usage + +```cpp id="cn1n7x" +#include +using namespace std; + +int main() { + int n = 5, r = 2; + + cout << nCr(n, r); + + return 0; +} +``` \ No newline at end of file diff --git a/Common/Combinatorics/Factorial/Factorial.cpp b/Common/Combinatorics/Factorial/Factorial.cpp new file mode 100644 index 0000000..b6a5b08 --- /dev/null +++ b/Common/Combinatorics/Factorial/Factorial.cpp @@ -0,0 +1,99 @@ +#include +using namespace std; + +/* +------------------------------------------ +๐Ÿ”น Approach 1: Iterative Factorial +- Multiply numbers from 1 to n +- Simple and efficient +------------------------------------------ +*/ +long long factorial(int n) { + long long result = 1; + + for (int i = 1; i <= n; i++) { + result *= i; + } + + return result; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 2: Recursive Factorial +- Uses recurrence relation +- Elegant but uses stack space +------------------------------------------ +*/ +long long factorial1(int n) { + if (n == 0 || n == 1) + return 1; + + return n * factorial1(n - 1); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 3: Tail Recursive Factorial +- Optimized recursion +- Carries result forward +------------------------------------------ +*/ +long long factorial2(int n, long long result = 1) { + if (n == 0) + return result; + + return factorial2(n - 1, result * n); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 4: STL-style accumulate +- Uses reduce-like logic +- Functional programming style +------------------------------------------ +*/ +long long factorial3(int n) { + vector v(n); + + iota(v.begin(), v.end(), 1); + + return accumulate(v.begin(), v.end(), 1LL, multiplies()); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 5: Large Factorial (String) +- Handles very large numbers +- Uses manual multiplication +- Useful for competitive programming +------------------------------------------ +*/ +string multiply(string num, int x) { + int carry = 0; + string result = ""; + + for (int i = num.size() - 1; i >= 0; i--) { + int prod = (num[i] - '0') * x + carry; + result.push_back((prod % 10) + '0'); + carry = prod / 10; + } + + while (carry) { + result.push_back((carry % 10) + '0'); + carry /= 10; + } + + reverse(result.begin(), result.end()); + return result; +} + +string factorialBig(int n) { + string result = "1"; + + for (int i = 2; i <= n; i++) { + result = multiply(result, i); + } + + return result; +} \ No newline at end of file diff --git a/Common/Combinatorics/Factorial/README.md b/Common/Combinatorics/Factorial/README.md new file mode 100644 index 0000000..ad914b5 --- /dev/null +++ b/Common/Combinatorics/Factorial/README.md @@ -0,0 +1,63 @@ +# ๐Ÿงฎ Factorial โ€“ C++ Solutions + +### ๐Ÿ’ก What is Factorial? + +The **factorial** of a number `n` (written as `n!`) is the product of all positive integers from **1 to n**. + +### Definition: + +n! = n \times (n-1) \times (n-2) \times \cdots \times 1 + +### Example: + +* 5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = **120** +* 4! = 4 ร— 3 ร— 2 ร— 1 = **24** +* 0! = **1** (special case) + +--- + +## ๐Ÿ“˜ Whatโ€™s Covered in This File? + +This program demonstrates **multiple ways to calculate factorial in C++**: + +| Approach | Description | +| -------- | ------------------------------------- | +| 1 | Iterative approach using loop | +| 2 | Recursive approach | +| 3 | Tail recursion optimization | +| 4 | Using STL style `accumulate` logic | +| 5 | Handling large factorial using string | + +--- + +## ๐Ÿง  Why Learn Factorial? + +Factorial is a **core building block** for many topics: + +* ๐Ÿ”ข Permutations & Combinations +* ๐Ÿ“Š Probability problems +* ๐Ÿง  Recursion understanding +* ๐Ÿ† Competitive programming + +--- + +## ๐Ÿ—‚ File Structure + +* `Factorial.cpp` + +--- + +## ๐Ÿ” Sample Usage + +```cpp id="f8h1kq" +#include +using namespace std; + +int main() { + int n = 5; + + cout << factorial(n); + + return 0; +} +``` diff --git a/Common/Combinatorics/Permutation/Permutation.cpp b/Common/Combinatorics/Permutation/Permutation.cpp new file mode 100644 index 0000000..94b3a82 --- /dev/null +++ b/Common/Combinatorics/Permutation/Permutation.cpp @@ -0,0 +1,103 @@ +#include +using namespace std; + +/* +------------------------------------------ +๐Ÿ”น Approach 1: Formula-Based nPr +- Uses factorial formula +- Simple but may overflow +------------------------------------------ +*/ +long long factorial(int n) { + long long res = 1; + for (int i = 1; i <= n; i++) + res *= i; + return res; +} + +long long nPr1(int n, int r) { + return factorial(n) / factorial(n - r); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 2: Optimized Iterative nPr +- Avoids full factorial computation +- More efficient and safer +------------------------------------------ +*/ +long long nPr2(int n, int r) { + long long res = 1; + for (int i = 0; i < r; i++) { + res *= (n - i); + } + return res; +} + +/* +------------------------------------------ +๐Ÿ”น Approach 3: Using STL next_permutation +- Generates permutations of array/string +- Easy and commonly used +------------------------------------------ +*/ +void printPermutations(string s) { + sort(s.begin(), s.end()); + + do { + cout << s << endl; + } while (next_permutation(s.begin(), s.end())); +} + +/* +------------------------------------------ +๐Ÿ”น Approach 4: Backtracking +- Swap-based recursion +- Generates all permutations +------------------------------------------ +*/ +void backtrack(vector& arr, int idx) { + if (idx == arr.size()) { + for (int x : arr) + cout << x << " "; + cout << endl; + return; + } + + for (int i = idx; i < arr.size(); i++) { + swap(arr[i], arr[idx]); + backtrack(arr, idx + 1); + swap(arr[i], arr[idx]); + } +} + +/* +------------------------------------------ +๐Ÿ”น Approach 5: Recursive Lexicographic Style +- Builds permutations step by step +- Uses visited array +------------------------------------------ +*/ +void permute(vector& arr, + vector& current, + vector& used) { + + if (current.size() == arr.size()) { + for (int x : current) + cout << x << " "; + cout << endl; + return; + } + + for (int i = 0; i < arr.size(); i++) { + if (!used[i]) { + used[i] = true; + current.push_back(arr[i]); + + permute(arr, current, used); + + current.pop_back(); + used[i] = false; + } + } +} \ No newline at end of file diff --git a/Common/Combinatorics/Permutation/README.md b/Common/Combinatorics/Permutation/README.md new file mode 100644 index 0000000..e564dd7 --- /dev/null +++ b/Common/Combinatorics/Permutation/README.md @@ -0,0 +1,66 @@ +# ๐Ÿ”€ Permutations โ€“ C++ Solutions + +### ๐Ÿ’ก What is a Permutation? + +A **permutation** is an arrangement of items where **order matters**. + +For example: + +* From {A, B, C}: + + * ABC, ACB, BAC, BCA, CAB, CBA โ†’ these are permutations + +--- + +## ๐Ÿ“Œ Formula: + +{}^nP_r = \frac{n!}{(n-r)!} + +--- + +## ๐Ÿ“˜ Whatโ€™s Covered in This File? + +This program demonstrates **multiple ways to compute and generate permutations in C++**: + +| Approach | Description | +| -------- | -------------------------- | +| 1 | Formula-based nPr | +| 2 | STL `next_permutation()` | +| 3 | Backtracking generation | +| 4 | Recursive swapping method | +| 5 | Lexicographic permutations | + +--- + +## ๐Ÿง  Why Learn Permutations? + +Permutations are used in: + +* ๐Ÿ”ข Arrangement problems +* ๐Ÿง  Backtracking problems +* ๐Ÿ† Competitive programming +* ๐ŸŽฏ Interview questions +* ๐Ÿ” Cryptography basics + +--- + +## ๐Ÿ—‚ File Structure + +* `Permutations.cpp` + +--- + +## ๐Ÿ” Sample Usage + +```cpp id="p1q7kd" +#include +using namespace std; + +int main() { + int n = 5, r = 2; + + cout << nPr(n, r); + + return 0; +} +``` diff --git a/Common/Combinatorics/Readme.md b/Common/Combinatorics/Readme.md index e69de29..b19e174 100644 --- a/Common/Combinatorics/Readme.md +++ b/Common/Combinatorics/Readme.md @@ -0,0 +1,44 @@ +# ๐Ÿงฎ Combinatorics in C++ + +Combinatorics is one of the most important topics in mathematics and competitive programming. It deals with **counting, arrangement, and selection of elements**, forming the foundation for probability, DP, and many algorithmic problems. + +This repository introduces **Combinatorics in C++**, designed to help beginners understand core concepts like factorial, permutations, and combinations with clean implementations. + +--- + +## ๐Ÿ“˜ What's Inside? + +Each file in this section focuses on a fundamental combinatorics concept used in coding interviews and competitive programming. + +We will cover: + +* Calculating Factorial +* Computing Permutations (nPr) +* Computing Combinations (nCr) +* Optimized mathematical formulas +* Recursive and iterative approaches + +--- + +## ๐Ÿ“‚ Problem Directories + +Each problem will have its **own folder** with: +- Source code in C++ +- Step-by-step explanation + +### ๐Ÿ”— Problem List + +- [Combination](./Combination/Combination.cpp) +- [Factorial](./Factorial/Factorial.cpp) +- [Permutation](./Permutation/Permutation.cpp) + +> โš ๏ธ Visit Each file and check the code + +## ๐Ÿš€ Getting Started + +To run any C++ file: + +```bash +g++ filename.cpp -o output +./output +``` \ No newline at end of file diff --git a/Common/Math/Armstrog Number/ReadMe.Md b/Common/Math/Armstrog Number/ReadMe.Md index fb14c67..5af2bb6 100644 --- a/Common/Math/Armstrog Number/ReadMe.Md +++ b/Common/Math/Armstrog Number/ReadMe.Md @@ -73,3 +73,4 @@ int main() { // Similarly, test other versions: // isArmstrong1(n), isArmstrong2(n), isArmstrong3(n) } +``` \ No newline at end of file diff --git a/Common/Math/Count Digits/README.md b/Common/Math/Count Digits/README.md index 7812a08..a3f081a 100644 --- a/Common/Math/Count Digits/README.md +++ b/Common/Math/Count Digits/README.md @@ -46,9 +46,10 @@ Output: 3 --- ## ๐Ÿ—‚ File Structure - +``` Count Digits/ โ”œโ”€โ”€ even_digit_count.cpp # Full C++ implementation โ”œโ”€โ”€ README.md # Explanation and usage -โ””โ”€โ”€ Makefile # Build and run the code \ No newline at end of file +โ””โ”€โ”€ Makefile # Build and run the code +``` \ No newline at end of file diff --git a/Common/Math/Even/README.md b/Common/Math/Even/README.md index 864798a..cd4d963 100644 --- a/Common/Math/Even/README.md +++ b/Common/Math/Even/README.md @@ -25,13 +25,14 @@ This program demonstrates **four different approaches** to check if a number is --- ## ๐Ÿ—‚ File Structure - +``` Even/ โ”‚ โ”œโ”€โ”€ even_number.cpp # All approaches with comments โ”œโ”€โ”€ README.md # This file โ””โ”€โ”€ Makefile # Build and run the program +``` --- ## ๐Ÿ” Sample Usage @@ -51,4 +52,5 @@ int main() { // Try others: // even_bitwise(n), even_division(n), even_recursive(n) -} \ No newline at end of file +} +``` \ No newline at end of file diff --git a/Common/Math/Extract Digits/README.md b/Common/Math/Extract Digits/README.md index af42991..2d21e64 100644 --- a/Common/Math/Extract Digits/README.md +++ b/Common/Math/Extract Digits/README.md @@ -54,18 +54,9 @@ This is the foundation for many number-based algorithms. --- ## ๐Ÿ“‚ File Structure - +``` ExtractDigit/ โ”œโ”€โ”€ extract_digit.cpp # Full working code โ”œโ”€โ”€ README.md # Explanation and approach - โ””โ”€โ”€ Makefile # Build and run the code - - - - - - - - - +``` \ No newline at end of file diff --git a/Common/Math/GCD_HCF_Calculation/README.md b/Common/Math/GCD_HCF_Calculation/README.md index a138457..bac18cf 100644 --- a/Common/Math/GCD_HCF_Calculation/README.md +++ b/Common/Math/GCD_HCF_Calculation/README.md @@ -57,8 +57,9 @@ Efficient and used in real-world applications, competitive coding, cryptography, --- ## ๐Ÿ“‚ File Structure - +``` GCD_HCF_Calculations/ โ”œโ”€โ”€ gcd.cpp # Full C++ source with both methods โ”œโ”€โ”€ README.md # Explanation and documentation -โ”œโ”€โ”€ Makefile # Build and run commands \ No newline at end of file +โ””โ”€โ”€ Makefile # Build and run commands +``` \ No newline at end of file diff --git a/Common/Math/Odd/README.md b/Common/Math/Odd/README.md index 24d1917..e556513 100644 --- a/Common/Math/Odd/README.md +++ b/Common/Math/Odd/README.md @@ -25,13 +25,13 @@ This program explores **four different ways** to check if a number is odd in C++ --- ## ๐Ÿ—‚ File Structure - +``` Odd/ โ”‚ โ”œโ”€โ”€ odd_number.cpp # All approaches with full comments โ”œโ”€โ”€ README.md # This file - โ””โ”€โ”€ Makefile # Build and run commands +``` --- ## ๐Ÿ” Sample Usage @@ -48,7 +48,7 @@ int main() { } else { cout << n << " is even\n"; } - // Try others: // odd_bitwise(n), odd_division(n), odd_recursive(n) -} \ No newline at end of file +} +``` \ No newline at end of file diff --git a/Common/Math/Palindrome/README.md b/Common/Math/Palindrome/README.md index 0d1cef5..d419790 100644 --- a/Common/Math/Palindrome/README.md +++ b/Common/Math/Palindrome/README.md @@ -52,8 +52,9 @@ Different problems may restrict: --- ## ๐Ÿ“‚ File Structure - +``` PalindromeCheck/ โ”œโ”€โ”€ palindrome_number_array.cpp # C++ source file with all implementations โ”œโ”€โ”€ README.md # Documentation and explanation -โ””โ”€โ”€ Makefile # Build and run the code \ No newline at end of file +โ””โ”€โ”€ Makefile # Build and run the code +``` \ No newline at end of file diff --git a/Common/Math/Prime/README.md b/Common/Math/Prime/README.md index 93e183e..cb442fa 100644 --- a/Common/Math/Prime/README.md +++ b/Common/Math/Prime/README.md @@ -30,14 +30,13 @@ This file demonstrates **three distinct approaches** to determine if a number is --- ## ๐Ÿ—‚ File Structure - +``` Prime/ โ”‚ โ”œโ”€โ”€ prime_number.cpp # All three approaches with comments โ”œโ”€โ”€ README.md # This file - -โ”œโ”€โ”€ Makefile # Build and run commands - +โ””โ”€โ”€ Makefile # Build and run commands +``` --- ## ๐Ÿ” Sample Usage @@ -56,3 +55,4 @@ int main() { return 0; } +``` \ No newline at end of file diff --git a/Common/Math/Print Divisors/README.md b/Common/Math/Print Divisors/README.md index 21e8798..4daf2e4 100644 --- a/Common/Math/Print Divisors/README.md +++ b/Common/Math/Print Divisors/README.md @@ -62,8 +62,9 @@ For `n = 36`, the divisors are: --- ## ๐Ÿ“‚ File Structure - +``` DivisorTechniques/ โ”œโ”€โ”€ print_all_divisors.cpp # All four approaches in one file โ”œโ”€โ”€ README.md # Full explanation and breakdown -โ”œโ”€โ”€ Makefile # Build and run commands +โ””โ”€โ”€ Makefile # Build and run commands +``` \ No newline at end of file diff --git a/Common/Math/ReadMe.Md b/Common/Math/ReadMe.Md index 5545648..7f62644 100644 --- a/Common/Math/ReadMe.Md +++ b/Common/Math/ReadMe.Md @@ -24,7 +24,7 @@ Each problem will have its **own folder** with: ### ๐Ÿ”— Problem List -- [Armstrong Number](./Armstrog%20Number//Armstrong.cpp) +- [Armstrong Number](./Armstrog%20Number/Armstrong.cpp) - [Check Even](./Even/even_number.cpp) - [Check Odd](./Odd/odd_number.cpp) - [Check Prime](./Prime/prime_number.cpp) diff --git a/Common/Math/Reverse Number/README.md b/Common/Math/Reverse Number/README.md index 4c6945e..bf4e8d4 100644 --- a/Common/Math/Reverse Number/README.md +++ b/Common/Math/Reverse Number/README.md @@ -59,7 +59,9 @@ Output: 9 --- ## ๐Ÿ“‚ Folder Structure +``` ReverseNumberTechniques/ โ”œโ”€โ”€ reverse_number.cpp # Full code with all 4 approaches โ”œโ”€โ”€ README.md # Detailed explanation and usage -โ”œโ”€โ”€ Makefile # Build and run commands +โ””โ”€โ”€ Makefile # Build and run commands +``` \ No newline at end of file