diff --git a/2561.RearrangingFruits.cpp b/2561.RearrangingFruits.cpp new file mode 100644 index 0000000..da6304c --- /dev/null +++ b/2561.RearrangingFruits.cpp @@ -0,0 +1,31 @@ + +#include +using namespace std; + +class Solution { +public: + vector rearrangeFruits(vector& fruits) { + + unordered_map freq; + for (int fruit : fruits) freq[fruit]++; + + + priority_queue> pq; + for (auto &p : freq) pq.push({p.second, p.first}); + + vector result; + pair prev = {-1, -1}; // last placed fruit + + while (!pq.empty()) { + auto cur = pq.top(); pq.pop(); + result.push_back(cur.second); + cur.first--; + + if (prev.first > 0) pq.push(prev); + prev = cur; + } + + return result; + } +}; + diff --git a/78.Subsets.cpp b/78.Subsets.cpp new file mode 100644 index 0000000..a157797 --- /dev/null +++ b/78.Subsets.cpp @@ -0,0 +1,34 @@ +// Subsets using Backtracking (DFS) +// ------------------------------- +// Intuition: Each element can be either taken or not taken → 2^n subsets +// Approach: Use DFS recursion with backtracking to explore both choices +// Time Complexity: O(n * 2^n) +// Space Complexity: O(n) recursion stack (excluding output) + +#include +using namespace std; + +class Solution { +public: + void dfs(int idx, vector& nums, vector& path, vector>& ans) { + if (idx == (int)nums.size()) { + ans.push_back(path); + return; + } + // Choice 1: not take nums[idx] + dfs(idx + 1, nums, path, ans); + + // Choice 2: take nums[idx] + path.push_back(nums[idx]); + dfs(idx + 1, nums, path, ans); + + path.pop_back(); // backtrack (undo choice) + } + + vector> subsets(vector& nums) { + vector> ans; + vector path; + dfs(0, nums, path, ans); + return ans; + } +};