<p>Given an integer array <code>nums</code> of length <code>n</code> where all the integers of <code>nums</code> are in the range <code>[1, n]</code> and each integer appears <strong>once</strong> or <strong>twice</strong>, return <em>an array of all the integers that appears <strong>twice</strong></em>.</p>

<p>You must write an algorithm that runs in <code>O(n)</code> time and uses only <em>constant</em> auxiliary space, excluding the space needed to store the output</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1]
<strong>Output:</strong> [2,3]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,2]
<strong>Output:</strong> [1]
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> nums = [1]
<strong>Output:</strong> []
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == nums.length</code></li>
	<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= n</code></li>
	<li>Each element in <code>nums</code> appears <strong>once</strong> or <strong>twice</strong>.</li>
</ul>

// class Solution {
// public:
//     vector<int> findDuplicates(vector<int>& arr) {

//          vector<int> ans;
//     int n = arr.size();
//      if(n==1);
//      return {};
//     vector<bool> visited(n, false);

//     for (int i = 0; i < n; i++) {
//         // Check if the element has already been visited
//         if (visited[arr[i]]) {
//             // Push the value into the answer vector
//             if (find(ans.begin(), ans.end(), arr[i]) == ans.end()) {
//                 ans.push_back(arr[i]); // Add only unique duplicates
//             }
//         } else {
//             visited[arr[i]] = true; // Mark the element as visited
//         }
//     }

//     // If no duplicates were found, return {-1}
//     if (ans.empty()) {
//         return {-1};
//     }

//     // Return the result sorted
//     sort(ans.begin(), ans.end());
//     return ans;
//     }
// };

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        stack<int> st;
        vector<int> ans;

         
        for (int i = 0; i < nums.size(); i++) {
            if (!st.empty() && nums[i] == st.top()) {
                ans.push_back(nums[i]);
            } else {
                st.push(nums[i]);
            }
        }
        // while (!st.empty()) {
        //     ans.push_back(st.top());
        //     st.pop();
        // }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};
38182