Easy and Well Explained C++ sol. ✔️✔️✔️
Intuition\nTo find the minimum time to reach an element for the second time, we need to keep track of both its first occurrence and the last occurrence in the i
# Intuition\nTo find the minimum time to reach an element for the second time, we need to keep track of both its first occurrence and the last occurrence in the input vector nums. By knowing these two positions, we can determine the time it takes to reach that element again.\n\nWe can use two unordered maps, pre and fir, to store the last occurrence and the first occurrence of each element, respectively.\n\nDuring the first loop through the nums vector, we calculate the time difference between the current occurrence and the last occurrence of each element. We then divide this time difference by 2 to get the time taken to reach that element for the second time. We use the ans map to store the maximum of this value and the value already present in the ans map for each element. This helps us find the minimum time to reach any element for the second time.\n\nAfter the first loop, the ans map contains the minimum time to reach each element for the second time. However, this time is calculated only for elements that are encountered at least twice in the nums vector.\n\nTo cover all elements (even those that appear only once in the vector), we loop through the elements stored in the pre map (which contains elements with multiple occurrences). For each element in the pre map, we calculate the time difference between its last occurrence (stored in pre[it.first]) and its first occurrence (stored in fir[it.first]). We divide this time difference by 2 to find the time taken to reach the element for the second time. Again, we use the ans map to store the maximum of this value and the value already present in the ans map for each element.\n\nBy the end of the second loop, the ans map will contain the minimum time taken to reach any element for the second time, considering both elements that have multiple occurrences and elements with a single occurrence.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n    int minimumSeconds(vector<int>& nums) {\n        unordered_map<int, int> pre, fir, ans;\n        int n = size(nums);\n        for(int i = 0; i<n; ++i)\n        {\n            if(pre.count(nums[i])) ans[nums[i]] = max(ans[nums[i]], (i-pre[nums[i]])/2);\n            pre[nums[i]] = i;\n            if(!fir.count(nums[i])) fir[nums[i]] = i;\n        }\n        int res = size(nums);\n        for(auto it: pre)\n        {\n            ans[it.first] = max(ans[it.first] ,(n-it.second+fir[it.first])/2);\n            res = min(res, ans[it.first]);\n        }\n        return res;\n    }\n};\n```\n\n\n\n
['C++']