diff --git a/dsa-solutions/lc-solutions/3000-3099/3000-maximum-area-of-diagonal-rectangle.md b/dsa-solutions/lc-solutions/3000-3099/3000-maximum-area-of-diagonal-rectangle.md new file mode 100644 index 000000000..d646a2a54 --- /dev/null +++ b/dsa-solutions/lc-solutions/3000-3099/3000-maximum-area-of-diagonal-rectangle.md @@ -0,0 +1,113 @@ +--- +id: 3000-maximum-area-of-diagonal-rectangle +title: Maximum area of longest diagonal rectangle (Leetcode) +sidebar_label: 3000-Maximum area of longest diagonal rectangle +description: Solution of Maximum area of longest diagonal rectangle +--- + + +## Problem Description + +You are given a 2D 0-indexed integer array dimensions. + +For all indices i,`0 <= i < dimensions.length`, dimensions[i][0] represents the length and dimensions[i][1] represents the width of the rectangle i. + +Return the area of the rectangle having the longest diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the maximum area. + +### Examples + +#### Example 1 + +- **Input:** $dimensions = [[9,3],[8,6]]$ +- **Output:** $48$ +- **Explanation:** For index = $0$, $\text{length} = 9$ and width = $3$. $\text{Diagonal length} = sqrt(9 \times 9 + 3 \times 3) = sqrt(90) ≈ 9.487$. + For $\text{index} = 1$, $length = 8$ and $\text{width} = 6$. $\text{Diagonal length} = sqrt(8 \times 8 + 6 \times 6) = sqrt(100) = 10$. + So, the rectangle at index 1 has a greater diagonal length therefore we return $area = 8 \times 6 = 48..$ + +#### Example 2 + +- **Input:** $dimensions = [[3,4],[4,3]]$ +- **Output:** $12$ +- **Explanation:**$ Length of diagonal is the same for both which is 5, so maximum area = 12$. + +### Constraints + +- $1 \leq dimensions.length \leq 100$ +- $dimensions[i].length == 2$ +- $1 <= dimensions[i][0], dimensions[i][1] <= 100$ + +### Intuition + +The problem requires finding the rectangle with the maximum diagonal length and, in case of a tie, returning the one with the maximum area. +To achieve this, we need to calculate the diagonal length for each rectangle and compare it with the current maximum diagonal length. +If the diagonal length is greater or equal (in case of a tie), we update the maximum diagonal length and check if the area of the current rectangle is greater than the maximum area. If so, we update the maximum area as well. + +### Approach + +The code uses a loop to iterate through each rectangle in the given dimensions vector. +It calculates the square of the diagonal length for each rectangle and compares it with the previous maximum diagonal length (diag). +If the current rectangle has a longer or equal diagonal length, it updates the maximum area (area) accordingly. +The area variable keeps track of the maximum area among rectangles with the longest diagonal. +Finally, the function returns the maximum area among rectangles with the longest diagonal. + +### Solution Code + +#### Python + +```py + class Solution: + def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int: + a,b = max(dimensions, key = lambda x: (x[0]*x[0]+x[1]*x[1], (x[0]*x[1]))) + return a*b +``` + +#### Java + +```java + + public int areaOfMaxDiagonal(int[][] dimensions) { + int diagSq = 0, area = 0; + for (int[] d : dimensions) { + int ds = d[0] * d[0] + d[1] * d[1]; + int ar = d[0] * d[1]; + if (ds > diagSq) { + area = ar; + diagSq = ds; + } + else if (ds == diagSq && ar > area) area = ar; + } + return area; + } +``` + +#### C++ + +```cpp +class Solution { +public: + int areaOfMaxDiagonal(vector>& dimensions) { + + double max_diagonal = 0; + int max_area = 0; + + for (const auto& rectangle : dimensions) { + int length = rectangle[0]; + int width = rectangle[1]; + + double diagonal_length = sqrt(pow(length, 2) + pow(width, 2)); + + if (diagonal_length > max_diagonal || (diagonal_length == max_diagonal && length * width > max_area)) { + max_diagonal = diagonal_length; + max_area = length * width; + } + } + + return max_area; + + } +}; +``` + +### Conclusion + +At last we can say that we can calculate maximum area of diagonal rectangle using timecomplexity of $o(n)$ and spacecomplexity of $o(1)$ using a simple for loop and some variable diff --git a/dsa-solutions/lc-solutions/3000-3099/3002-maximum-size-of-a-set-after-removals.md b/dsa-solutions/lc-solutions/3000-3099/3002-maximum-size-of-a-set-after-removals.md new file mode 100644 index 000000000..1ae5c7e84 --- /dev/null +++ b/dsa-solutions/lc-solutions/3000-3099/3002-maximum-size-of-a-set-after-removals.md @@ -0,0 +1,153 @@ +--- +id: maximum-size-of-a-set-after-removals +title: Maximum Size of a Set After Removals +sidebar_label: 3002 -Maximum Size of a Set After Removals +tags: + - Array + - Hash Table + - Greedy +description: "This is a solution to the Maximum Size of a Set After Removals problem on LeetCode." +--- + +## Problem Description + +You are given two 0-indexed integer arrays nums1 and nums2 of even length n. + +You must remove n / 2 elements from nums1 and n / 2 elements from nums2. After the removals, you insert the remaining elements of nums1 and nums2 into a set s. + +Return the maximum possible size of the set s. + +### Examples + +**Example 1:** + +``` +Input: nums1 = [1,2,1,2], nums2 = [1,1,1,1] +Output: 2 +Explanation: We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}. +It can be shown that 2 is the maximum possible size of the set s after the removals. + +``` + +**Example 2:** + +``` +Input: nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3] +Output: 5 +Explanation: We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}. +It can be shown that 5 is the maximum possible size of the set s after the removals. + +``` + +**Example 3:** + +``` +Input: nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6] +Output: 6 +Explanation: We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}. +It can be shown that 6 is the maximum possible size of the set s after the removals. +``` + +### Constraints + +- `n == nums1.length == nums2.length` +- `1 <= n <= 2 * 104` +- `n is even` +- `1 <= nums1[i], nums2[i] <= 109` + +## Solution for Minimum Moves to Capture The Queen Problem + +### Intuition + +To solve this problem, we can use a greedy approach. We aim to maximize the size of the set s after removing elements from nums1 and nums2. We can achieve this by removing elements that appear the most in both arrays. Additionally, we may need to remove elements from one array to balance the removals between the two arrays. + +### Approach + +Initialize variables length, n1, and n2. length represents half the length of the input arrays, while n1 and n2 are sets of unique elements from nums1 and nums2, respectively. + +Calculate the number of elements common to both n1 and n2 and store it in inter_num. + +Calculate the difference between the lengths of n1 and n2 and length, representing the excess elements in each array. + +Determine the maximum possible difference between the lengths of n1 and n2 and length, or the number of elements common to both arrays. Store this maximum difference in max_diff. + +Return the sum of the lengths of n1 and n2 minus max_diff, which represents the maximum possible size of the set s. + +### Solution Code + +#### Python + +```py +class Solution: + def maximumSetSize(self, nums1: list[int], nums2: list[int]) -> int: + length, n1, n2 = len(nums1) // 2, set(nums1), set(nums2) + inter_num = len(n1.intersection(n2)) + diff = 0 + + diff += len(n1) - length if len(n1) >= length else 0 + diff += len(n2) - length if len(n2) >= length else 0 + + max_diff=max(diff,inter_num) + + return (len(n1)+len(n2))-max_diff + +``` + +#### Java + +```java +class Solution { + public int maximumSetSize(int[] nums1, int[] nums2) { + int i,j,n=nums1.length; + Set set1=new HashSet<>(); + Set set2=new HashSet<>(); + Set set3=new HashSet<>(); + for(int x:nums1) + { + set1.add(x); + set3.add(x); + } + for(int x:nums2) + { + set2.add(x); + set3.add(x); + } + int common=set1.size()+set2.size()-set3.size(); + int n1=set1.size(),n2=set2.size(); + int ans=Math.min(n/2,n1-common); + ans+=Math.min(n/2,n2-common); + ans+=common; + ans=Math.min(n,ans); + return ans; + } +} + +``` + +#### C++ + +```cpp +class Solution { +public: + int maximumSetSize(vector& nums1, vector& nums2) { + set s1, s2, s; + int n = nums1.size(); + for (int x : nums1) { + s1.insert(x); + s.insert(x); + } + for (int x : nums2) { + s2.insert(x); + s.insert(x); + } + int ans = min(min(n/2, (int)s1.size()) + min(n/2, (int)s2.size()),(int) s.size()); + + return ans; + } +}; +``` + +#### Complexity Analysis + +- Time complexity: $O(n)$, where n is the total number of elements in both nums1 and nums2. Calculating the set intersection and differences takes linear time. +- Space complexity: $O(n)$ , where n is the total number of elements in both nums1 and nums2. The space complexity is dominated by the sets n1 and n2, which store unique elements from the input arrays. diff --git a/dsa-solutions/lc-solutions/3000-3099/3005-count-elements-with-maximum-frequency.md b/dsa-solutions/lc-solutions/3000-3099/3005-count-elements-with-maximum-frequency.md new file mode 100644 index 000000000..1c8565ef7 --- /dev/null +++ b/dsa-solutions/lc-solutions/3000-3099/3005-count-elements-with-maximum-frequency.md @@ -0,0 +1,148 @@ +--- +id: count-elements-with-maximum-frequency +title: Count Elements With Maximum Frequency +sidebar_label: 3005 -Count Elements With Maximum Frequency +tags: + - Array + - Hash Table + - Counting +description: "This is a solution to the Count Elements With Maximum Frequency problem on LeetCode." +--- + +## Problem Description + +You are given an array nums consisting of positive integers. + +Return the total frequencies of elements in nums such that those elements all have the maximum frequency. + +The frequency of an element is the number of occurrences of that element in the array. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,2,3,1,4] +Output: 4 +Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. +So the number of elements in the array with maximum frequency is 4. + +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,4,5] +Output: 5 +Explanation: All elements of the array have a frequency of 1 which is the maximum. +So the number of elements in the array with maximum frequency is 5. + +``` + +### Constraints + +- `1 <= nums.length <= 100` +- `1 <= nums[i] <= 100` + +## Solution for Count Elements With Maximum Frequency + +### Intuition + +To solve this problem, we can use a HashMap to count the frequency of each element in the given array. Then, we iterate through the values of the HashMap to find the maximum frequency. Finally, we iterate through the values again to count the total number of elements with the maximum frequency. + +### Approach + +Initialize a vector freq of size 101 to store the frequency of each number. This assumes that the numbers in the input vector are in the range [0, 100]. + +Iterate through the input vector and update the frequency of each number in the freq vector. + +Initialize variables ans and temp to keep track of the maximum frequency and the current frequency, respectively. + +Iterate through the freq vector from index 1 to 100. + +If the frequency at the current index is equal to temp, add it to the answer (ans). + +If the frequency at the current index is greater than temp, update ans to be the current frequency and update temp. +Return the final answer. + +### Solution Code + +#### Python + +```py +class Solution: + def maxFrequencyElements(self, nums: List[int]) -> int: + di=defaultdict(int) + m,c=0,0 + for i in nums: + di[i]+=1 + if di[i]>m: + m=di[i] + c=0 + if di[i]==m: + c+=1 + return m*c + + +``` + +#### Java + +```java +class Solution { + public int maxFrequencyElements(int[] nums) { + HashMap map = new HashMap(); + int mf = 0, m = -1; + for (Integer c : nums) { + if (map.containsKey(c)) map.put(c, map.get(c) + 1); + else map.put(c, 1); + } + for(Integer t: map.values()){ + if(t>m){ + m = t; + mf = 1; + }else if(t==m) mf++; + } + return mf*m; + } +} + +``` + +#### C++ + +```cpp +class Solution +{ +public: + int maxFrequencyElements(vector &nums) + { + vector freq(101, 0); + + for (int i = 0; i < nums.size(); i++) + { + freq[nums[i]]++; + } + + int ans = 0; + int temp = 0; + + for (int i = 1; i < 101; i++) + { + if (freq[i] == temp) { + ans += freq[i]; + } else if (freq[i] > temp) { + ans = freq[i]; + temp = freq[i]; + } + } + + return ans; + } +}; +``` + +#### Complexity Analysis + +- Time complexity: $O(nlog(n))$, where n is the total number of elements in nums +- Space complexity:$O(nlog(n))$, where n is the total number of elements in nums diff --git a/dsa-solutions/lc-solutions/3000-3099/3006-find-beautiful-indices-in-the-given-array-i.md b/dsa-solutions/lc-solutions/3000-3099/3006-find-beautiful-indices-in-the-given-array-i.md new file mode 100644 index 000000000..36b305310 --- /dev/null +++ b/dsa-solutions/lc-solutions/3000-3099/3006-find-beautiful-indices-in-the-given-array-i.md @@ -0,0 +1,182 @@ +--- +id: find-beautiful-indices-in-the-given-array-i +title: Find Beautiful Indices in the Given Array I +sidebar_label: 3006 -Find Beautiful Indices in the Given Array I +tags: + - Two pointer + - String + - Binary Search + - Rolling Hash + - String Matching + - Hash Function +description: "This is a solution to the Find Beautiful Indices in the Given Array I problem on LeetCode." +--- + +## Problem Description + +You are given a 0-indexed string s, a string a, a string b, and an integer k. + +An index i is beautiful if: + +- $0 \leq i \leq \text{s.length} - \text{a.length}$ +- $s[i..(i + \text{a.length} - 1)] == a$ +- There exists an index j such that: +- $0 \leq j \leq \text{s.length} - \text{b.length}$ +- $s[j..(j + \text{b.length} - 1)] == b$ +- $|j - i| \leq k$ + Return the array that contains beautiful indices in sorted order from smallest to largest. + +### Examples + +**Example 1:** + +``` +Input: s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15 +Output: [16,33] +Explanation: There are 2 beautiful indices: [16,33]. +- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15. +- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15. +Thus we return [16,33] as the result. + +``` + +**Example 2:** + +``` +Input: s = "abcd", a = "a", b = "a", k = 4 +Output: [0] +Explanation: There is 1 beautiful index: [0]. +- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4. +Thus we return [0] as the result. + +``` + +### Constraints + +- `1 <= k <= s.length <= 105` +- `1 <= a.length, b.length <= 10` + +## Solution For the Problem Find Beautiful Indices in the Given Array I + +### Intuition + +Basically the problem statement suggest that we need to find the index of string a matching in string s and then check if there is any index j which is matching with b in s and `abs(i - j) <= k`. +So to find the matching index need calculate the longest prefix which is suffix array ( LPS array ) and in that if the lps[i] matches with pattern string length then we found a match - KMP algo. +If you don't know KMP algo for pattern matching then first go through it then come back to solution. + +### Approach + +Get index of the matched pattern for the string a - lets call it v1 +Get index of the matched pattern for the string b - lets call it v2 +Check for possible combination of i & j in the v1 and v2. +to do so we need to check if the abs(i - j). If so then simple add it to answer. +If `v1[i] > v2[j]&& abs( i- j) > k` then keep moving pointer j till `v1[i] > v2[j]` +Check again if abs(i - j) or not. If it is less, then add it to ans + +### Solution Code + +#### Python + +```py + class Solution: + def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]: + f1=[] + i=0 + j=0 + while(i v){ + String t = a + "@" + s; + List lps = new ArrayList<>(); + lps.add(0); + for(int i = 1; i < t.length(); ++i){ + int ind = lps.get(i - 1); + while(ind > 0 && t.charAt(ind) != t.charAt(i)) { ind = lps.get(ind - 1); } + lps.add((t.charAt(ind) == t.charAt(i))?ind + 1 : 0); + } + for(int i = 0; i < lps.size(); ++i){ + if(lps.get(i) == a.length()) v.add(i - 2*a.length()); + } +} + +public List beautifulIndices(String s, String a, String b, int k) { + List ans = new ArrayList<>(); + List v1 = new ArrayList<>(); + List v2 = new ArrayList<>(); + getPatternMatchingIndex(s, a, v1); + getPatternMatchingIndex(s, b, v2); + for(int i = 0, j = 0; i < v1.size(); ++i){ + while(j < v2.size() && v1.get(i) > v2.get(j) && Math.abs(v1.get(i) - v2.get(j)) > k) j++; + if(j < v2.size() && Math.abs(v1.get(i) - v2.get(j)) <= k) ans.add(v1.get(i)); + } + return ans; +} + +``` + +#### C++ + +```cpp +void getPatternMatchingIndex(string& s, string& a, vector& v){ + string t = a + "@" + s; + vector lps(1, 0); + for(int i = 1; i < t.size(); ++i){ + int ind = lps[i-1]; + while(ind > 0 && t[ind] != t[i]) { ind = lps[ind-1]; } + lps.push_back((t[ind] == t[i])?ind + 1 : 0); + } + for(int i = 0; i < lps.size(); ++i){ + if(lps[i] == a.size()) v.push_back(i - 2*a.size()); + } +} + +vector beautifulIndices(string s, string a, string b, int k) { + vector ans, v1, v2; + getPatternMatchingIndex(s, a, v1); + getPatternMatchingIndex(s, b, v2); + for(int i = 0, j = 0; i < v1.size(); ++i){ + while(j < v2.size() && v1[i] > v2[j] && abs(v1[i] - v2[j]) > k) j++; + if(j < v2.size() && abs(v1[i] - v2[j]) <= k) ans.push_back(v1[i]); + } + return ans; +} +``` + +#### Complexity Analysis + +- Time complexity: $O(n)$, where n is the length of the string +- Space complexity: $O(n)$, where n is the length of the string diff --git a/dsa-solutions/lc-solutions/3000-3099/3010-divide-an-array-into-subarrays-with-minimum-cost-i.md b/dsa-solutions/lc-solutions/3000-3099/3010-divide-an-array-into-subarrays-with-minimum-cost-i.md new file mode 100644 index 000000000..724b7c5f5 --- /dev/null +++ b/dsa-solutions/lc-solutions/3000-3099/3010-divide-an-array-into-subarrays-with-minimum-cost-i.md @@ -0,0 +1,151 @@ +--- +id: divide-an-array-into-subarrays-with-minimum-cost-i +title: Divide an Array Into Subarrays With Minimum Cost I +sidebar_label: 3010 -Divide an Array Into Subarrays With Minimum Cost I +tags: + - Array + - Sorting + - Enumeration +description: "This is a solution to the Divide an Array Into Subarrays With Minimum Cost I problem on LeetCode." +--- + +## Problem Description + +You are given an array of integers nums of length n. + +The cost of an array is the value of its first element. For example, the cost of [1,2,3] is 1 while the cost of [3,4,1] is 3. + +You need to divide nums into 3 disjoint contiguous subarrays. + +Return the minimum possible sum of the cost of these subarrays. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,3,12] +Output: 6 +Explanation: The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6. +The other possible ways to form 3 subarrays are: +- [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15. +- [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16. + +``` + +**Example 2:** + +``` +Input: nums = [5,4,3] +Output: 12 +Explanation: The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12. +It can be shown that 12 is the minimum cost achievable. + +``` + +**Example 3:** + +``` +Input: nums = [10,3,1,1] +Output: 12 +Explanation: The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12. +It can be shown that 12 is the minimum cost achievable. + +``` + +### Constraints + +- `3 <= n <= 50` +- `1 <= nums[i] <= 50` + +## Solution For the Problem Divide an Array Into Subarrays With Minimum Cost I + +### Intuition + +cost = nums[0] + smallest + 2nd smallest + +Explanation +You have to divide array in 3 parts think of making 2 slice/cuts in array. No matter how you cut the array, first part of array will always come, cost of 1st part will be nums[0] and it will always be added. So nums[0]is fixed. +Now if you make other 2 cuts in the 'remaining array' at smallest element and 2nd smallest element then total cost will be: +cost = nums[0] + smallest ele + 2nd smallest ele + +example +[1 , 2 , 3 , 4 , 5 , 6 ,7 , 8] +1 is fixed +In remaining array smallest is 2 and next smallest is 3 +[1] +[2] +[3 , 4 , 5 , 6 ,7 , 8] + +### Approach + +Just iterate array from i=1 to end and find smallest and 2nd smallest elements and store them in a and b. + +return nums[0]+a+b. + +### Solution Code + +#### Python + +```py +class Solution(object): + def minimumCost(self, nums): + sum = nums[0] + nums = nums[1:] + nums.sort() + return sum + nums[0] + nums[1] + +``` + +#### Java + +```java + +class Solution { + public int minimumCost(int[] nums) { + int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; + + for (int x = 1; x < nums.length; x++) { + int curr = nums[x]; + + if (curr < first) { + second = first; + first = curr; + continue; + } + if (curr < second) { + second = curr; + } + } + return nums[0] + first + second; + } +} + +``` + +#### C++ + +```cpp +class Solution { +public: + int minimumCost(vector& nums) { + int x = nums[0]; + int a = nums[1] ,b = nums[2]; + for(int i = 2;inums[i]){ + b = a; + a = nums[i]; + } + else if(b>nums[i]) b = nums[i]; + + } + return x+a+b; + } +}; +``` + +#### Complexity Analysis + +- Time complexity: $O(n)$ We only traverse through the array once + +- Space complexity: $O(1)$ Since we just have 2 pointers diff --git a/dsa-solutions/lc-solutions/3000-3099/minimum-moves-to-capture-the-queen.md b/dsa-solutions/lc-solutions/3000-3099/minimum-moves-to-capture-the-queen.md new file mode 100644 index 000000000..fdda83052 --- /dev/null +++ b/dsa-solutions/lc-solutions/3000-3099/minimum-moves-to-capture-the-queen.md @@ -0,0 +1,245 @@ +--- +id: minimum-moves-to-capture-the-queen +title: Minimum Moves to Capture The Queen +sidebar_label: 3001 - Minimum Moves to Capture The Queen +tags: + - Array +description: "This is a solution to the Minimum Moves to Capture The Queen problem on LeetCode." +--- + +## Problem Description + +There is a 1-indexed 8 x 8 chessboard containing 3 pieces. + +You are given 6 integers a, b, c, d, e, and f where: + +(a, b) denotes the position of the white rook. +(c, d) denotes the position of the white bishop. +(e, f) denotes the position of the black queen. +Given that you can only move the white pieces, return the minimum number of moves required to capture the black queen. + +Note that: + +Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces. +Bishops can move any number of squares diagonally, but cannot jump over other pieces. +A rook or a bishop can capture the queen if it is located in a square that they can move to. +The queen does not move. + +### Examples + +**Example 1:** + +``` +Input: a = 1, b = 1, c = 8, d = 8, e = 2, f = 3 +Output: 2 +Explanation: We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3). +It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning. + +``` + +**Example 2:** + +``` +Input: a = 5, b = 3, c = 3, d = 4, e = 5, f = 2 +Output: 1 +Explanation: We can capture the black queen in a single move by doing one of the following: +- Move the white rook to (5, 2). +- Move the white bishop to (5, 2). + +``` + +### Constraints + +- `1 <= a, b, c, d, e, f <= 8` +- `No two pieces are on the same square.` + +## Solution for Minimum Moves to Capture The Queen Problem + +### Intuition + +Same Row or Column: +If the queen is in the same row (a == e) or the same column (b == f), it means it can be captured in one move. + +Same Diagonal: +If the absolute difference between the columns (abs(c - e)) is equal to the absolute difference between the rows (abs(d - f)), it means the queen is on the same diagonal and can be captured in one move. + +Otherwise: +If none of the above conditions are met, it implies that the queen cannot be captured in one move. + +Pieces in Between +For suppose a rook is standing in the way of bishop and vice-versa the min no of moves is two , to check whether the piece in between i have used the manhattan distance. + +### Approach + +Check for Same Row, Column, or Diagonal: +If the queen is in the same row, column, or diagonal as the starting point, calculate the Manhattan distance. + +Check for Obstacles: +While calculating the Manhattan distance, inspect the squares between the starting point and the queen's position. +If any square along the path contains another piece, consider it an obstacle. + +Minimum Moves Calculation: +Assess the minimum number of moves based on the presence of obstacles. +If no obstacles are present, it's likely a direct capture in one move. +If obstacles are encountered, it might require at least two moves to maneuver around them. + +Handle Piece-Specific Scenarios: +Adjust the approach based on the specific pieces involved. +For a rook, obstacles in the same row or column are significant. +For a bishop, obstacles along diagonals need consideration. + +Return Minimum Moves: +Return the calculated minimum number of moves. + +### Solution Code + +#### Python + +```py +class Solution: + def minMovesToCaptureTheQueen(self, a: int, b: int, c: int, d: int, e: int, f: int) -> int: + # rock and queen in the same row or col + if a == e: # same row + if a == c and (d - b) * (d - f) < 0: # bishop on the same row and between rock and queen + return 2 + else: + return 1 + elif b == f: # same col + if b == d and (c - a) * (c - e) < 0: + return 2 + else: + return 1 + # bishop and queen in the same diagonal + elif c - e == d - f: # \ diagonal + if a - e == b - f and (a - c) * (a - e) < 0: + return 2 + else: + return 1 + elif c - e == f - d: # / diagonal + if a - e == f - b and (a - c) * (a - e) < 0: + return 2 + else: + return 1 + return 2 + + + +``` + +#### Java + +```java +=public int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { + // ----- Rook ----- + if(a==e){ + if(a==c && ((b true means rook is between bishop and queen - so we need to move rook + boolean flag = false; + for(int i=c, j=d; i>0&&j>0; i--, j--){ + if(i==a && j==b) flag = true; + else if(i==e && j==f) { + if(flag) return 2; + else return 1; + } + } + + flag =false; + for(int i=c, j=d; i>0&&j<9; i--, j++){ + if(i==a && j==b) flag = true; + else if(i==e && j==f) { + if(flag) return 2; + else return 1; + } + } + + flag = false; + for(int i=c, j=d; i<9&&j<9; i++, j++){ + if(i==a && j==b) flag = true; + else if(i==e && j==f) { + if(flag) return 2; + else return 1; + } + } + + flag = false; + for(int i=c, j=d; i<9&&j>0; i++, j--){ + if(i==a && j==b) flag = true; + else if(i==e && j==f) { + if(flag) return 2; + else return 1; + } + } + + // for every condition Rook can capture the queen in 2 steps + return 2; +} + +``` + +#### C++ + +```cpp +class Solution { +public: + int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { + if(a == e){ + if(c == e){ + int d0 = abs(b-f) ; + int d1 = abs(b-d) ; + int d2 = abs(d-f); + if(d0 == d1+d2) + return 2; + else + return 1; + } + else + return 1; + } + else if(b == f){ + if(d == f){ + int d0 = abs(a-e) ; + int d1 = abs(a-c); + int d2 = abs(c-e) ; + if(d0 == d1+d2) + return 2; + else + return 1; + } + else + return 1; + + } + else if(abs(c-e) == abs(d - f)){ + if(abs(a-c) == abs(b-d)) { + int d0 = abs(c-e) + abs(d-f); + int d1 = abs(a-c) + abs(b-d); + int d2 = abs(e-a) + abs(f-b); + if(d0 == d1+d2) + return 2; + else + return 1; + } + else + return 1; + } + else + return 2; + + } +}; +``` + +### Conclusion + +THis code efficectively calculates the minimum number of moves using constant space and constant time