question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
count-number-of-maximum-bitwise-or-subsets
Easy python solution using recursion and backtracking
easy-python-solution-using-recursion-and-o700
Code\n\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n def subs(idx,nums,N,lst,l):\n if idx>=N:\n
Lalithkiran
NORMAL
2023-04-20T15:43:03.403273+00:00
2023-04-20T15:43:03.403351+00:00
530
false
# Code\n```\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n def subs(idx,nums,N,lst,l):\n if idx>=N:\n val=0\n for i in lst:\n val |= i\n l.append(val)\n return\n lst.append(nums[idx])\n subs(idx+1,nums,N,lst,l)\n lst.pop()\n subs(idx+1,nums,N,lst,l)\n return \n \n lst=[]\n l=[]\n subs(0,nums,len(nums),lst,l)\n cnt=Counter(l)\n return max([i for i in cnt.values()])\n \n```
2
0
['Backtracking', 'Bit Manipulation', 'Recursion', 'Python3']
0
count-number-of-maximum-bitwise-or-subsets
EASY||Bit Manipulation||C++
easybit-manipulationc-by-rohit_18kumar-onop
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rohit_18kumar
NORMAL
2023-03-31T14:27:37.073801+00:00
2023-03-31T14:27:37.073850+00:00
125
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int x=0;\n int n=nums.size();\n for(auto it:nums){\n x|=it;\n }\n int count=0;\n vector<int>arr;\n for(int i=0;i<(1<<n);i++){\n int y=0;\n for(int j=0;j<n;j++){\n if(i&(1<<j)){\n y|=nums[j];\n }\n }\n if(y==x){\n count++;\n }\n }\n return count;\n \n }\n};\n```
2
0
['C++']
0
count-number-of-maximum-bitwise-or-subsets
Javascript backtracking solution 81 ms, faster than 100.00%,43.1 MB, less than 11.11%!!
javascript-backtracking-solution-81-ms-f-snxd
```\n/*\n * @param {number[]} nums\n * @return {number}\n /\nvar countMaxOrSubsets = function(nums) {\n let res = 0;\n let max = 0;\n function backtrac
HabibovUlugbek
NORMAL
2023-03-31T11:24:40.342274+00:00
2023-03-31T11:24:40.342316+00:00
50
false
```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countMaxOrSubsets = function(nums) {\n let res = 0;\n let max = 0;\n function backtrack(nums,start, val){ \n if(val === max)res++\n \n for(let i = start;i<nums.length; i++){\n backtrack(nums,i+1,val|nums[i])\n }\n \n }\n \n for(let num of nums) max |= num;\n backtrack(nums,0, 0)\n return res;\n \n \n};
2
0
['Backtracking', 'Bit Manipulation', 'JavaScript']
0
count-number-of-maximum-bitwise-or-subsets
C++ | DP
c-dp-by-pikachuu-jz5q
Code\n\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int maxVal = 0;\n for(int num: nums) {\n maxVal = m
pikachuu
NORMAL
2023-01-15T18:06:55.635218+00:00
2023-01-15T18:06:55.635251+00:00
76
false
# Code\n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int maxVal = 0;\n for(int num: nums) {\n maxVal = maxVal | num;\n }\n vector<int> DP(maxVal + 1, 0);\n DP[nums[0]] = 1;\n for(int i = 1; i < nums.size(); i++) {\n for(int j = maxVal; j > 0; j--) {\n if(DP[j]) {\n DP[j | nums[i]] += DP[j];\n }\n }\n DP[nums[i]]++;\n }\n return DP[maxVal];\n }\n};\n```
2
0
['Array', 'Dynamic Programming', 'Bit Manipulation', 'C++']
0
count-number-of-maximum-bitwise-or-subsets
C++||Backtracking||Recursion||Easy to Understand
cbacktrackingrecursioneasy-to-understand-otcj
```\nclass Solution {\npublic:\n int ans=0;\n void backtrack(vector &nums,int target,int idx,int curr_xor)\n {\n if(idx>=nums.size())\n {
return_7
NORMAL
2022-07-12T05:27:39.668444+00:00
2022-07-12T05:27:39.668496+00:00
219
false
```\nclass Solution {\npublic:\n int ans=0;\n void backtrack(vector<int> &nums,int target,int idx,int curr_xor)\n {\n if(idx>=nums.size())\n {\n if(curr_xor==target)\n {\n ans++;\n }\n return ;\n }\n \n backtrack(nums,target,idx+1,curr_xor);\n backtrack(nums,target,idx+1,nums[idx]|curr_xor);\n \n }\n int countMaxOrSubsets(vector<int>& nums)\n {\n int target=0;\n for(int i=0;i<nums.size();i++)\n {\n target|=nums[i];\n }\n backtrack(nums,target,0,0);\n return ans;\n\n \n }\n};\n//if you like the solution plz upvote.
2
0
['Backtracking', 'Recursion', 'C']
0
count-number-of-maximum-bitwise-or-subsets
C++ | Subsets Approach
c-subsets-approach-by-ama29n-fum5
\nint countMaxOrSubsets(vector<int>& nums) {\n int ans = 0, maxOr = INT_MIN;\n int limit = pow(2, nums.size());\n for(int i = 0; i < limit;
ama29n
NORMAL
2022-01-08T19:37:54.229435+00:00
2022-01-08T19:38:38.992259+00:00
182
false
```\nint countMaxOrSubsets(vector<int>& nums) {\n int ans = 0, maxOr = INT_MIN;\n int limit = pow(2, nums.size());\n for(int i = 0; i < limit; i++) {\n int Or = 0;\n for(int j = 0; j < nums.size(); j++) { \n\t\t\t\tif((i & (1 << j)) == 0) Or |= nums[j];\n\t\t\t}\n if(Or > maxOr) { maxOr = Or; ans = 1; } \n\t\t\telse if(Or == maxOr) ans++;\n }\n return ans;\n }\n```
2
0
[]
0
count-number-of-maximum-bitwise-or-subsets
python 100% faster
python-100-faster-by-saurabht462-o60j
```\ndef countMaxOrSubsets(self, nums: List[int]) -> int:\n target=0\n for n in nums:\n target|=n\n self.ans=set()\n def
saurabht462
NORMAL
2021-10-17T10:43:19.473625+00:00
2021-10-17T10:49:00.230201+00:00
133
false
```\ndef countMaxOrSubsets(self, nums: List[int]) -> int:\n target=0\n for n in nums:\n target|=n\n self.ans=set()\n def helper(i,curr,arr):\n if curr==target:\n self.ans.add(tuple(arr.copy()))\n if i==len(nums):\n return\n helper(i+1,curr,arr)\n helper(i+1,curr|nums[i],arr+[i])\n \n helper(0,0,[])\n return len(self.ans)
2
1
[]
0
count-number-of-maximum-bitwise-or-subsets
Easy C++ solution | O(2^n * n )
easy-c-solution-o2n-n-by-rac101ran-jvwh
\nclass Solution {\npublic:\n int cnt[300005];\n int countMaxOrSubsets(vector<int>& nums) {\n int len=(1<<(int)nums.size());\n int ans=0;\n
rac101ran
NORMAL
2021-10-17T08:55:50.097697+00:00
2021-10-17T08:56:26.651267+00:00
281
false
```\nclass Solution {\npublic:\n int cnt[300005];\n int countMaxOrSubsets(vector<int>& nums) {\n int len=(1<<(int)nums.size());\n int ans=0;\n for(int i=0; i<len; i++) {\n int z=i,pos=0,orr=0;\n while(z) {\n if((z&1)==1) {\n orr|=nums[pos]; \n }\n pos++;\n z>>=1;\n }\n cnt[orr]++;\n ans=max(ans,cnt[orr]);\n }\n return ans;\n }\n};\n```
2
0
['Math', 'C', 'Bitmask']
0
count-number-of-maximum-bitwise-or-subsets
[Python3] Beats 100% Solution | Easy to understand
python3-beats-100-solution-easy-to-under-rgnk
python\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n ans = {}\n subSet = [[]]\n max_or = 0\n for i in
leefycode
NORMAL
2021-10-17T05:11:40.516874+00:00
2021-10-17T05:11:40.516927+00:00
233
false
```python\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n ans = {}\n subSet = [[]]\n max_or = 0\n for i in range(len(nums)):\n for j in range(len(subSet)):\n new = [nums[i]] + subSet[j]\n # print(new)\n x = new[0]\n for k in range(1, len(new)):\n x |= new[k]\n x = max(max_or, x)\n if x in ans:\n ans[x] += 1\n else:\n ans[x] = 1\n subSet.append(new)\n return ans[x]\n```
2
1
['Python3']
1
count-number-of-maximum-bitwise-or-subsets
100% fast | easy python solution using Combinations from Itertools
100-fast-easy-python-solution-using-comb-9jv5
Combination returns tuples as output thats why make sure to convert it to list before append in a array because tuples does not supports OR Operation.\n```\ncla
shivamsingh99
NORMAL
2021-10-17T04:31:19.017033+00:00
2021-10-17T04:31:19.017067+00:00
345
false
Combination returns tuples as output thats why make sure to convert it to list before append in a array because tuples does not supports OR Operation.\n```\nclass Solution:\n from itertools import combinations \n def countMaxOrSubsets(self, nums: List[int]) -> int:\n d = {}\n o = 0\n arr = []\n for i in range(1,len(nums)+1):\n comb = combinations(nums,i)\n for i in comb:\n arr.append(list(i))\n for i in arr:\n x = o|i[0]\n for j in i:\n x = x|j\n if x not in d:\n d[x] = 1\n else:\n d[x] += 1\n return d[max(d)]
2
0
['Python']
1
count-number-of-maximum-bitwise-or-subsets
(C++) 2044. Count Number of Maximum Bitwise-OR Subsets
c-2044-count-number-of-maximum-bitwise-o-iu10
\n\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int target = 0, n = nums.size(); \n for (auto& x : nums) target |=
qeetcode
NORMAL
2021-10-17T04:06:37.158905+00:00
2021-10-18T04:07:13.240055+00:00
242
false
\n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int target = 0, n = nums.size(); \n for (auto& x : nums) target |= x; \n \n map<pair<int, int>, int> memo; \n function<int(int, int)> fn = [&](int i, int mask) -> int {\n if (mask == target) return pow(2, n-i); \n if (i == n) return 0; \n if (memo.count({i, mask}) == 0) \n memo[{i, mask}] = fn(i+1, mask | nums[i]) + fn(i+1, mask); \n return memo[{i, mask}]; \n }; \n \n return fn(0, 0); \n }\n};\n```\n\nAdding a solution inspired by @lee215\n```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int most = 0; \n unordered_map<int, int> mp = {{0, 1}}; \n for (int x : nums) {\n most |= x; \n unordered_map<int, int> tmp = mp; \n for (auto& [k, v] : tmp) mp[x | k] += v; \n }\n return mp[most]; \n }\n};\n```
2
0
['C']
0
count-number-of-maximum-bitwise-or-subsets
java | recursion | backtracking
java-recursion-backtracking-by-qin10-1yij
```\nclass Solution {\n int count = 0;\n public int countMaxOrSubsets(int[] nums) {\n int maxOr = 0;\n for (int num : nums)\n max
qin10
NORMAL
2021-10-17T04:03:26.398118+00:00
2021-11-05T16:16:48.142688+00:00
118
false
```\nclass Solution {\n int count = 0;\n public int countMaxOrSubsets(int[] nums) {\n int maxOr = 0;\n for (int num : nums)\n maxOr |= num;\n \n getMaxSub(nums, 0, 0, maxOr);\n return count;\n }\n \n private void getMaxSub(int[] arr, int i, int curOr, int maxOr) {\n if(i == arr.length) {\n if(curOr == maxOr) count++;\n \n return;\n }\n \n getMaxSub(arr, i + 1, curOr | arr[i], maxOr); //use curr arr[i]\n getMaxSub(arr, i + 1, curOr, maxOr); // not use curr arr[i]\n }\n}
2
2
[]
1
count-number-of-maximum-bitwise-or-subsets
C++ dp bitwise O(2^n)
c-dp-bitwise-o2n-by-colinyoyo26-bdnu
\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size(), mx = 0, ans = 0;\n int dp[1 << 17]{};\n
colinyoyo26
NORMAL
2021-10-17T04:00:39.371089+00:00
2021-11-14T16:22:18.187198+00:00
200
false
```\nclass Solution {\npublic:\n int countMaxOrSubsets(vector<int>& nums) {\n int n = nums.size(), mx = 0, ans = 0;\n int dp[1 << 17]{};\n for (auto t : nums) mx |= t;\n for (int i = 1, j = 1; i < (1 << n); i++) {\n j += (i == (1 << j));\n dp[i] = dp[i ^ (1 << (j - 1))] | nums[j - 1];\n ans += dp[i] == mx;\n }\n return ans;\n }\n};\n```\n
2
0
[]
1
count-number-of-maximum-bitwise-or-subsets
Dynamic Programming | Iterative | Short & Readable
dynamic-programming-iterative-short-read-o9ca
IntuitionWe need to find the number of subsets that achieve the maximum possible bitwise OR. By iterating through nums, we maintain a frequency map of OR result
amanabiy
NORMAL
2025-03-31T22:29:15.240454+00:00
2025-03-31T22:29:15.240454+00:00
17
false
# Intuition We need to find the number of subsets that achieve the maximum possible bitwise OR. By iterating through nums, we maintain a frequency map of OR results and their counts. ## Code ```python3 [] class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: count = defaultdict(lambda: 0) count[0] = 1 for num in nums: # cloning here since we can't modify a hashtable while iterating for key, c in list(count.items()): count[key | num] += c return count[max(count.keys())] # Return count of max OR value ``` ```rust [] use std::collections::HashMap; impl Solution { pub fn count_max_or_subsets(nums: Vec<i32>) -> i32 { let mut count = HashMap::from([(0, 1)]); for &num in &nums { // cloning here since we can't modify a hashtable while iterating for (&key, &c) in count.clone().iter() { *count.entry(key | num).or_insert(0) += c; } } count[count.keys().max().unwrap()] } } ```
1
0
['Hash Table', 'Dynamic Programming', 'Python3', 'Rust']
0
count-number-of-maximum-bitwise-or-subsets
Counting Subsets with Maximum Bitwise OR Using Recursion and Backtracking
counting-subsets-with-maximum-bitwise-or-w6jj
IntuitionThe problem requires finding the number of different non-empty subsets of an array that have the maximum possible bitwise OR. My first thought was to g
x7Fg9_K2pLm4nQwR8sT3vYz5bDcE6h
NORMAL
2025-03-19T13:42:33.469630+00:00
2025-03-19T13:42:33.469630+00:00
17
false
# Intuition The problem requires finding the number of different non-empty subsets of an array that have the maximum possible bitwise OR. My first thought was to generate all possible subsets of the array, compute the bitwise OR for each subset, and then count how many subsets achieve the maximum OR value. # Approach 1. Generate Subsets: Use a recursive function to generate all possible subsets of the array. 2. Compute Bitwise OR: For each subset, compute its bitwise OR by performing a bitwise OR operation on all its elements. 3. Track Maximum OR: Keep track of the maximum OR value encountered and count how many subsets achieve this value. 4. Return Result: Return the count of subsets with the maximum OR value. # Complexity - Time complexity: $$O(2^n*n)$$ - Space complexity: $$O(2^n)$$ # Code ```cpp [] class Solution { public: void createsubsets(vector<int>nums,int i,vector<int>& o,vector<vector<int>>& ans){ if (i>=nums.size()){ans.push_back(o);return;} createsubsets(nums,i+1,o,ans); o.push_back(nums[i]); createsubsets(nums,i+1,o,ans); o.pop_back(); } int countMaxOrSubsets(vector<int>& nums) { vector<vector<int>>ans; vector<int>o; createsubsets(nums,0,o,ans); unordered_map<int,int>mp; int answ=INT_MIN; for (int i=0;i<ans.size();i++){ int h=0; for (int j=0;j<ans[i].size();j++){h=h|ans[i][j];} mp[h]++; } int answer=0; for (auto &it:mp){answer=max(answer,it.second);} return answer; } }; ```
1
0
['C++']
0
count-number-of-maximum-bitwise-or-subsets
beats 100% easy backtracking solution
beats-100-easy-backtracking-solution-by-c0mqi
Complexity Time complexity:O(2^n) Space complexity:O(1) Code
s_malay
NORMAL
2025-03-15T07:13:44.679449+00:00
2025-03-15T07:13:44.679449+00:00
26
false
# Complexity - Time complexity:O(2^n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int helper(int i,vector<int>&nums,int maxor,int orr) { if(i==nums.size()) { if(orr==maxor) return 1; return 0; } int prev=orr; int take=helper(i+1,nums,maxor,(orr|nums[i])); int notake=helper(i+1,nums,maxor,prev); return take+notake; } int countMaxOrSubsets(vector<int>& nums) { int maxor=0; for(auto it:nums) maxor=maxor|it; return helper(0,nums,maxor,0); } }; ```
1
0
['Array', 'Backtracking', 'Bit Manipulation', 'Enumeration', 'C++']
0
count-number-of-maximum-bitwise-or-subsets
C#
c-by-adchoudhary-9x68
Code
adchoudhary
NORMAL
2025-03-06T03:24:57.750379+00:00
2025-03-06T03:24:57.750379+00:00
6
false
# Code ```csharp [] public class Solution { public int CountMaxOrSubsets(int[] nums) { int maxOr = 0; int n = nums.Length; foreach (int num in nums) { maxOr |= num; } int count = 0; int totalSubsets = 1 << n; for (int mask = 1; mask < totalSubsets; mask++) { int currentOr = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { currentOr |= nums[i]; } } if (currentOr == maxOr) { count++; } } return count; } } ```
1
0
['C#']
0
count-number-of-maximum-bitwise-or-subsets
THE BEST CODE TO BEAT 95+% OF ALL SOLUTIONS ON LEETCODE. Good luck to everyone!!!! 💻🚀🔥💡
the-best-code-to-beat-95-of-all-solution-v10p
IntuitionApproachComplexity Time complexity: Space complexity: Code
nilfhunter
NORMAL
2025-01-11T15:11:45.300073+00:00
2025-01-11T15:11:45.300073+00:00
21
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: max_or = 0 count = 0 # Вычисляем максимальное побитовое ИЛИ for num in nums: max_or |= num # Оптимизация: Используем итеративный перебор всех подмножеств n = len(nums) for subset in range(1 << n): # Перебираем все 2^n подмножеств current_or = 0 for i in range(n): if subset & (1 << i): # Проверяем, включён ли i-й элемент current_or |= nums[i] if current_or == max_or: count += 1 return count ```
1
0
['Python3']
0
count-number-of-maximum-bitwise-or-subsets
THE BEST CODE TO BEAT 95+% OF ALL SOLUTIONS ON LEETCODE. Good luck to everyone!!!! 💻🚀🔥💡
the-best-code-to-beat-95-of-all-solution-ctz4
IntuitionApproachComplexity Time complexity: Space complexity: Code
nilfhunter
NORMAL
2025-01-11T15:11:40.649865+00:00
2025-01-11T15:11:40.649865+00:00
21
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: max_or = 0 count = 0 # Вычисляем максимальное побитовое ИЛИ for num in nums: max_or |= num # Оптимизация: Используем итеративный перебор всех подмножеств n = len(nums) for subset in range(1 << n): # Перебираем все 2^n подмножеств current_or = 0 for i in range(n): if subset & (1 << i): # Проверяем, включён ли i-й элемент current_or |= nums[i] if current_or == max_or: count += 1 return count ```
1
0
['Python3']
0
count-number-of-maximum-bitwise-or-subsets
✔✔Easy, backtracking, Bit Manipulation 😃🙌
easy-backtracking-bit-manipulation-by-pm-zeig
Intuition We are given an integer array nums and we need to calculate the maximum number of possible sets with maximum possible bitwise OR of a subset of nums.
PM_25
NORMAL
2025-01-07T06:01:48.062050+00:00
2025-01-07T06:01:48.062050+00:00
22
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> - We are given an integer array `nums` and we need to calculate the maximum number of possible sets with **maximum possible bitwise OR of a subset of `nums`**. ## Approach <!-- Describe your approach to solving the problem. --> - **Step-1**: Let `n` be the size of array `nums` and `maxBitwiseOR` be the maximum possible bitwise OR of `nums`. - **Step-2**: We calculate the `maxBitwiseOR` by iterating over the `nums` and performing bitwise **OR** operation on it. - **Step-3** Then we call `maxCountOfBitwise` function which perform operations as follows: - Parameters: `nums`, `maxBitwiseOR` max value of bitwise OR of `nums`, `i` current index and `curr` the bitwise OR of current subset. 1. If current index `i` equal size of `nums` then we just check whether it is equal to `maxBitwiseOR` - IF *YES* return `1` - ELSE return `0` 2. Else we calculate the bitwise of remaining elements of `nums` by: 1. Including current element : `bitwiseORwith` 2. By excluding current element : `bitwiseORwithout` 3. Finally return the sum of both `bitwiseORwith` and `bitwiseORwithout`. - **Step-4**: The function `maxCountOfBitwise` returns the result. ``` Example-1: maxBitwiseOR = 3; [3 , 1] / \ include `3` [3] [] exclude `3` / \ / \ include `1` [3,1] [3] [1] [] exclude `1` | | | | exclude `1`<--| |--> include `1` _________________|_______|______|________|__________________ Bitwise-OR: {3|1=3} {3} {1} {0} ____________________________________________________________ - The last level constitutes of Bitwise-OR of all elements of subset. ``` ## Complexity - Time complexity: $$O(2^{n})$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(log n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> ## Code ```cpp [] class Solution { public: int maxCountOfBitwise(vector<int>& nums, int maxBitwiseOR, int i, int curr){ if(i == nums.size()) return (curr == maxBitwiseOR) ? 1 : 0; int bitwiseORwith = maxCountOfBitwise(nums, maxBitwiseOR, i+1, curr|nums[i]); int bitwiseORwithout = maxCountOfBitwise(nums, maxBitwiseOR, i+1, curr); return bitwiseORwith + bitwiseORwithout; } int countMaxOrSubsets(vector<int>& nums) { int maxBitwiseOR = 0, n = nums.size(); for(int &i : nums) maxBitwiseOR |= i; return maxCountOfBitwise(nums, maxBitwiseOR, 0, 0); } }; ```
1
0
['Array', 'Backtracking', 'Bit Manipulation', 'C++']
0
count-number-of-maximum-bitwise-or-subsets
Simple solution
simple-solution-by-shreyas_kumar_m-s1le
Code
Shreyas_kumar_m
NORMAL
2024-12-28T17:00:51.872722+00:00
2024-12-28T17:00:51.872722+00:00
21
false
# Code ```javascript [] /** * @param {number[]} nums * @return {number} */ var countMaxOrSubsets = function(nums) { let maxOr = 0; let count =0; for(let i=0;i<nums.length;i++){ maxOr |=nums[i]; } for(let i=1;i<(1<<nums.length);i++){ let curr = 0; for(let j=0;j<nums.length;j++){ if(i & (1<<j)){ curr |= nums[j]; } } if(curr == maxOr){ count++; } } return count; }; ```
1
0
['JavaScript']
0
count-number-of-maximum-bitwise-or-subsets
Solution with hashmap beats 99.80%. Detailed explanation
solution-with-hashmap-beats-9980-detaile-iovz
Intuition\n Describe your first thoughts on how to solve this problem. \nWe will use dynamic programming approach with hashmaps to solve the problem.\n\nFirst s
MaxEtzo
NORMAL
2024-10-20T16:29:38.245588+00:00
2024-10-20T16:31:15.479011+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will use dynamic programming approach with hashmaps to solve the problem.\n\nFirst sub-problem is to generate all subsets. To do that we start with an empty subset. Then we iterate through ```nums``` and generate new subsets with any given number from ```nums``` by adding it the all previous / existing subsets. \n\nFor example, if the input ```nums = [1,2,3]```:\n1. Start with an empty subset: ```subs = [[0]]```\n2. Extend with new subsets by adding 1 to all exsisting subsets: ```subs = [[0], [0,1]]```\n3. Add 2 to all subsets: ```subs = [[0],[0,1],[0,2],[0,1,2]]```\n4. Add 3 to all subsets: ```subs = [[0],[0,1],[0,2],[0,1,2],[0,3],[0,1,3],[0,2,3],[0,1,2,3]]```\n\nWe see that the number of subsets grows exponentially (with the base 2), i.e. ```len(subs) == 2**(len(nums))```. We don\'t need to store the subsets completely, but only their bitwise-ORs. The last element will always contain the maximum. So a simple program below works and beats approx. 80% of all submissions:\n```python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int: \n subOrs = [0] # bitwise-OR of an empty set\n for n in nums:\n subLen = len(subOrs)\n for i in range(subLen):\n subOrs.append(n | subOrs[i])\n \n return sum([1 for o in subOrs if o == subOrs[-1]])\n```\nThe next section will describe how to optimize the program to beat the 99.8% of all submission. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Optimzation 1**\nWe recognize that we don\'t need to store "good" subsets, i.e. those subsets bitwise-ORs of which already equal to the maximum. Adding a new number to the good subset will not change the bitwise-OR, otherwise it means that the prior OR was not the maximum. Instead, when the new number from ```nums``` is added, we simply double the amount of "good" subsets. Then we iterate through the "bad" subsets and see whether the new subset ("bad" subset + new value) must be added to the the *count* of "good" ones or the *list* of "bad" ones. \n\nThe downside of this approach is that it requires precalculating maximum bitwise-OR at the start. Here is the code below (beats approx. 85% of all submission):\n```python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int: \n maxOr = 0\n for n in nums:\n maxOr |= n\n\n badOrs = [0] # bitwise-Or of an empty set\n goodCnt = 0\n for n in nums:\n goodCnt *= 2\n badCnt = len(badOrs)\n for i in range(badCnt):\n newOr = n | badOrs[i] \n if newOr == maxOr:\n goodCnt += 1\n else:\n badOrs.append(n | badOrs[i])\n \n return goodCnt\n```\n\n**Optimization 2**\nWhen looking inside "bad" subsets, we realize that many have the same bitwise-OR. Yet we store them individually in the list and when adding a new number, we OR it with the each of them. The final bit of optimization is to replace ```badOrs``` list with a hashmap and count the number of corresponding subsets. This way we avoid repeating the same operation multiple times (for different subsets with the same OR). The final solution beats 99.80% of all submissions (the code in the **Code** section below)\n\n# Complexity\n- Time complexity:\n**O(N*maxOr)** - Factor of N comes from the outer loop: number of elements in ```nums```. The second term is the inner loop over "bad" subsets (with bitwise-OR not equal to the maximum). It\'s easy to create an example when all the subsets generate unique bitwise-ORs. For example if each number in the ```nums``` is a unique power of 2, and only the subset with all elements would result in the maximum bitwise-OR. Therefore the second term is limited by maximum OR ```maxOr``` \n\n- Space complexity:\n**O(maxOr)** - hashmap to store bitwise-ORs of "bad" subsets.\n\n# Code\n```python3 []\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int: \n maxOr = 0\n for n in nums:\n maxOr |= n\n\n badOrs = defaultdict(int)\n badOrs[0] = 1\n goodCnt = 0\n for n in nums:\n goodCnt *= 2\n tmpMap = badOrs.copy()\n for o in tmpMap.keys():\n newOr = n | o\n if maxOr != newOr:\n badOrs[newOr] += tmpMap[o]\n else:\n goodCnt += tmpMap[o]\n \n return goodCnt\n```\n![Screenshot 2024-10-19 181837.png](https://assets.leetcode.com/users/images/58aeabab-33ac-41b4-91d1-199cd0b84c13_1729441868.4538226.png)\n\n
1
0
['Hash Table', 'Dynamic Programming', 'Python3']
0
count-number-of-maximum-bitwise-or-subsets
Using Recursion.
using-recursion-by-sa_hilll94-wemy
\n# Approach\n Describe your approach to solving the problem. \n1. Find the maxOR by performing OR operation over all the elements of nums[i]\n2. Use recursion
sa_hilll94
NORMAL
2024-10-19T19:24:08.136944+00:00
2024-10-19T19:39:25.581165+00:00
11
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find the `maxOR` by performing OR operation over all the elements of `nums[i]`\n2. Use recursion to find the subsets and then perform OR with the element.\n3. At base case, compare it with maxOR.\n\n# Complexity\n- Time complexity:$$O(2^n)$$ \n`an array of size n, the number of subsets of the array is 2^n. Hence, the recursive function is called 2^n times, making the time complexity for this part O(2^n).`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n int Recursion(int index, int currOR, int maxOR, vector<int>nums)\n {\n // Base Case\n if(index==nums.size())\n {\n if(currOR == maxOR)\n {\n return 1;\n }\n else\n {\n return 0;\n }\n }\n\n int take = Recursion (index+1, currOR | nums[index], maxOR, nums);\n\n int notTake = Recursion (index+1, currOR, maxOR, nums);\n\n return take+notTake;\n\n }\n int countMaxOrSubsets(vector<int>& nums) {\n\n int maxOR = 0;\n \n for(int num : nums)\n {\n maxOR |= num;\n }\n\n int currOR = 0;\n\n return Recursion(0,currOR,maxOR, nums);\n }\n};\n```
1
0
['Recursion', 'C++']
0
count-number-of-maximum-bitwise-or-subsets
Solution (5ms)
solution-5ms-by-phantom2097-w8rv
\n\n\n# Complexity\n- Time complexity:\nO(2^n)\n\n- Space complexity:\nO(n)\n\n# Code\nkotlin []\nclass Solution {\n fun countMaxOrSubsets(nums: IntArray): I
Phantom2097
NORMAL
2024-10-19T10:45:04.185353+00:00
2024-10-19T10:45:04.185378+00:00
5
false
![\u0421\u043D\u0438\u043C\u043E\u043A \u044D\u043A\u0440\u0430\u043D\u0430 2024-10-19 134318.png](https://assets.leetcode.com/users/images/b368b1a0-4b05-4b21-9417-2404a353fcbf_1729334622.9553323.png)\n\n\n# Complexity\n- Time complexity:\n$$O(2^n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```kotlin []\nclass Solution {\n fun countMaxOrSubsets(nums: IntArray): Int {\n var max = 0\n nums.forEach { max = max or it }\n var result = 0\n\n fun helper(idx: Int, value: Int, count: Int): Int {\n var newCount = count\n if (value == max) {\n newCount++\n }\n if (idx == nums.size) {\n return newCount\n }\n for (j in idx + 1 ..< nums.size) {\n newCount += helper(j + 1, value or nums[j], 0)\n }\n return helper(idx + 1, value or nums[idx], newCount)\n }\n for (i in 0 ..< nums.size) {\n result += helper(i + 1, nums[i], 0)\n }\n return result\n }\n\n \n}\n```
1
0
['Kotlin']
0
robot-collisions
✅💯🔥Explanations No One Will Give You🎓🧠Very Detailed Approach🎯🔥Extremely Simple And Effective🔥
explanations-no-one-will-give-youvery-de-kmf1
\n \n \n You\u2019ve got to get up every morning with determination if you\u2019re going to go to bed with satisfaction.\n
heir-of-god
NORMAL
2024-07-13T05:24:40.769111+00:00
2024-07-13T05:52:35.596152+00:00
27,138
false
<blockquote>\n <p>\n <b>\n You\u2019ve got to get up every morning with determination if you\u2019re going to go to bed with satisfaction.\n </b> \n </p>\n <p>\n --- George Lorimer ---\n </p>\n</blockquote>\n\n# \uD83D\uDC51Problem Explanation and Understanding:\n\n## \uD83C\uDFAF Problem Description\nYou are given `n` robots each of which have its position, health and direction all represented with arrays. These robots in one moment of time start moving with equal speed each in its `direction`. Every time two robots share 1 cell it turns into collide with this rules:\n- If one robot has more health then decrease its health by 1 and remove the robot with less health\n- If robots have equal amount of health - remove them both\nYou want to return health of robots which stay alive in order they were given\n\n## \uD83D\uDCE5\u2935\uFE0F Input:\n`1 <= positions.length == healths.length == directions.length == n <= 10^5`\n- Integer array `positions` | 1 <= positions[i] <= 10^9 ; all positions are distinct\n- Integer array `healths` | 1 <= healths[i] <= 10^9\n- String array `directions` | directions[i] in (\'L\', \'R\')\n\n## \uD83D\uDCE4\u2934\uFE0F Output:\nThe array of healths of robots which will stay alive in order they were given\n\n---\n\n# 1\uFE0F\u20E3\uD83E\uDDE0 Approach: Smart Simulation With Sorting\n\n# \uD83E\uDD14 Intuition\n- The first thing that came to my mind was to simulate this process, but it is clear that due to the fact that the positions are not sorted, this is quite difficult to do.\n- However, what dissuaded me from sorting for a while was that we need to return the health of the robots in the order in which we were given them (which usually means that sorting is not necessary).\n- Okay, let\'s imagine that we sorted the robots. Now we can go through this sorted list and add robots to the stack one by one. Why the stack? Because if we meet a robot that goes to the left, then the first enemy it meets is the last robot that goes to the right that we met.\n- Thus, the whole logic is that every time we meet a robot that goes to the right, we add it to the stack and every time we meet a robot that goes to the left, we fight it with the last robot on the stack until the last the robot on the stack does not go left (Which means there are no more robots on the left that go right) or until the robot dies.\n- For better understanding, let\'s look at an example.\n- `P.S. You can do the same thing but in reverse - go from right to left in the array, append left robots and fight right robots`\n\n### Dry Run\n\nLet\'s look at this example\n\n```\npositions = [3, 1, 4, 2]\nhealths = [10, 5, 11, 10]\ndirections = "RLLR"\n```\n\n**Setup before loop:**\n1. **n** = 4\n2. **robots** list after combining positions, healths, directions, and indices:\n```\nrobots = [[3, 10, \'R\', 0], [1, 5, \'L\', 1], [4, 11, \'L\', 2], [2, 10, \'R\', 3]]\n```\n3. **robots** list after sorting by positions:\n\n```\nrobots = [[1, 5, \'L\', 1], [2, 10, \'R\', 3], [3, 10, \'R\', 0], [4, 11, \'L\', 2]]\n```\n4. **stack**: []\n\n**Inside the loop:**\n\n| Loop Index | Robot | Stack State | Action |\n|------------|----------------------------|------------------------------------|--------------------------------------------------------|\n| 0 | [1, 5, \'L\', 1] | [] | Append to stack |\n| | | [[1, 5, \'L\', 1]] | |\n| 1 | [2, 10, \'R\', 3] | [[1, 5, \'L\', 1]] | Append to stack |\n| | | [[1, 5, \'L\', 1], [2, 10, \'R\', 3]] | |\n| 2 | [3, 10, \'R\', 0] | [[1, 5, \'L\', 1], [2, 10, \'R\', 3]] | Append to stack |\n| | | [[1, 5, \'L\', 1], [2, 10, \'R\', 3], [3, 10, \'R\', 0]] | |\n| 3 | [4, 11, \'L\', 2] | [[1, 5, \'L\', 1], [2, 10, \'R\', 3], [3, 10, \'R\', 0]] | Collide with last robot in stack |\n| | | | Last robot health < current robot health |\n| | | [[1, 5, \'L\', 1], [2, 10, \'R\', 3]] | Last robot is removed from stack |\n| | | | Current robot health decreased by 1 (to 10) |\n| | | [[1, 5, \'L\', 1], [2, 10, \'R\', 3]] | Collide with new last robot in stack |\n| | | | Last robot health == current robot health |\n| | | [[1, 5, \'L\', 1]] | Last robot removed from the stack and this robot won\'t be added |\n\n---\n\n**Final Stack State:**\n\n```\n[[1, 5, \'L\', 1]]\n```\n\n**Sorted Stack by Original Indices:**\n\n```\n[[1, 5, \'L\', 1]]\n```\n\n**Final Output:**\n\n```\n[5]\n```\n\n# \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB Coding \n- Create a list `robots` that combines `positions`, `healths`, `directions`, and the original indices into a list of lists.\n- Sort the `robots` list based on the positions.\n- Initialize an empty list `stack` to keep track of the surviving robots.\n- Iterate through each `robot` in the sorted `robots` list:\n - If the current robot is moving right (`"R"`) or the stack is empty or the last robot in the stack is moving left (`"L"`), append the current robot to the stack and continue to the next robot.\n - If the current robot is moving left (`"L"`):\n - Set a flag `add` to `True`.\n - While the stack is not empty, the last robot in the stack is moving right (`"R"`), and `add` is `True`:\n - Get the health of the last robot in the stack as `last_health`.\n - If the current robot\'s health is greater than `last_health`, pop the last robot from the stack and decrease the current robot\'s health by 1.\n - If the current robot\'s health is less than `last_health`, decrease the last robot\'s health by 1 and set `add` to `False`.\n - If the current robot\'s health is equal to `last_health`, pop the last robot from the stack and set `add` to `False`.\n - If `add` is `True`, append the current robot to the stack.\n- Return a list of the healths of the surviving robots, sorted by their original indices.\n\n# \uD83D\uDCDA Complexity Analysis\n- \u23F0 Time complexity: O(n * log n), since we use sorting twice in the code which lead to 2 * n * log n -> O(n log n) \n- \uD83E\uDDFA Space complexity: O(n), since 1. Sorting functions can use extra memory. 2. We creating new list `robots` of size `n`\n\n# \uD83D\uDCBB Code\n``` python []\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n n = len(positions)\n robots = [[positions[ind], healths[ind], directions[ind], ind] for ind in range(n)]\n robots.sort()\n stack = []\n\n for robot in robots:\n if robot[2] == "R" or not stack or stack[-1][2] == "L":\n stack.append(robot)\n continue\n\n if robot[2] == "L":\n add = True\n while stack and stack[-1][2] == "R" and add:\n last_health = stack[-1][1]\n if robot[1] > last_health:\n stack.pop()\n robot[1] -= 1\n elif robot[1] < last_health:\n stack[-1][1] -= 1\n add = False\n else:\n stack.pop()\n add = False\n\n if add:\n stack.append(robot)\n\n return [robot[1] for robot in sorted(stack, key=lambda robot: robot[3])]\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n = positions.size();\n vector<vector<int>> robots;\n\n for (int i = 0; i < n; ++i) {\n robots.push_back({positions[i], healths[i], directions[i], i});\n }\n\n sort(robots.begin(), robots.end());\n\n vector<vector<int>> stack;\n\n for (auto& robot : robots) {\n if (robot[2] == \'R\' || stack.empty() || stack.back()[2] == \'L\') {\n stack.push_back(robot);\n continue;\n }\n\n if (robot[2] == \'L\') {\n bool add = true;\n while (!stack.empty() && stack.back()[2] == \'R\' && add) {\n int last_health = stack.back()[1];\n if (robot[1] > last_health) {\n stack.pop_back();\n robot[1] -= 1;\n } else if (robot[1] < last_health) {\n stack.back()[1] -= 1;\n add = false;\n } else {\n stack.pop_back();\n add = false;\n }\n }\n\n if (add) {\n stack.push_back(robot);\n }\n }\n }\n\n vector<int> result;\n sort(stack.begin(), stack.end(), [](vector<int>& a, vector<int>& b) {\n return a[3] < b[3];\n });\n\n for (auto& robot : stack) {\n result.push_back(robot[1]);\n }\n\n return result;\n }\n};\n```\n``` JavaScript []\nvar survivedRobotsHealths = function(positions, healths, directions) {\n let n = positions.length;\n let robots = [];\n\n for (let i = 0; i < n; ++i) {\n robots.push([positions[i], healths[i], directions[i], i]);\n }\n\n robots.sort((a, b) => a[0] - b[0]);\n\n let stack = [];\n\n for (let robot of robots) {\n if (robot[2] === \'R\' || stack.length === 0 || stack[stack.length - 1][2] === \'L\') {\n stack.push(robot);\n continue;\n }\n\n if (robot[2] === \'L\') {\n let add = true;\n while (stack.length > 0 && stack[stack.length - 1][2] === \'R\' && add) {\n let last_health = stack[stack.length - 1][1];\n if (robot[1] > last_health) {\n stack.pop();\n robot[1] -= 1;\n } else if (robot[1] < last_health) {\n stack[stack.length - 1][1] -= 1;\n add = false;\n } else {\n stack.pop();\n add = false;\n }\n }\n\n if (add) {\n stack.push(robot);\n }\n }\n }\n\n stack.sort((a, b) => a[3] - b[3]);\n\n let result = [];\n for (let robot of stack) {\n result.push(robot[1]);\n }\n\n return result;\n};\n```\n``` Java []\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n List<int[]> robots = new ArrayList<>();\n\n for (int i = 0; i < n; ++i) {\n robots.add(new int[]{positions[i], healths[i], directions.charAt(i), i});\n }\n\n Collections.sort(robots, (a, b) -> Integer.compare(a[0], b[0]));\n\n Stack<int[]> stack = new Stack<>();\n\n for (int[] robot : robots) {\n if (robot[2] == \'R\' || stack.isEmpty() || stack.peek()[2] == \'L\') {\n stack.push(robot);\n continue;\n }\n\n if (robot[2] == \'L\') {\n boolean add = true;\n while (!stack.isEmpty() && stack.peek()[2] == \'R\' && add) {\n int last_health = stack.peek()[1];\n if (robot[1] > last_health) {\n stack.pop();\n robot[1] -= 1;\n } else if (robot[1] < last_health) {\n stack.peek()[1] -= 1;\n add = false;\n } else {\n stack.pop();\n add = false;\n }\n }\n\n if (add) {\n stack.push(robot);\n }\n }\n }\n\n List<int[]> resultList = new ArrayList<>(stack);\n resultList.sort(Comparator.comparingInt(a -> a[3]));\n\n List<Integer> result = new ArrayList<>();\n for (int[] robot : resultList) {\n result.add(robot[1]);\n }\n\n return result;\n }\n}\n```\n``` C []\ntypedef struct {\n int position;\n int health;\n char direction;\n int index;\n} Robot;\n\nint compareByPosition(const void* a, const void* b) {\n return ((Robot*)a)->position - ((Robot*)b)->position;\n}\n\nint compareByIndex(const void* a, const void* b) {\n return ((Robot*)a)->index - ((Robot*)b)->index;\n}\n\nint* survivedRobotsHealths(int* positions, int positionsSize, int* healths, int healthsSize, char* directions, int* returnSize) {\n int n = positionsSize;\n Robot* robots = (Robot*)malloc(n * sizeof(Robot));\n Robot* stack = (Robot*)malloc(n * sizeof(Robot));\n int stackSize = 0;\n\n for (int i = 0; i < n; ++i) {\n robots[i].position = positions[i];\n robots[i].health = healths[i];\n robots[i].direction = directions[i];\n robots[i].index = i;\n }\n\n qsort(robots, n, sizeof(Robot), compareByPosition);\n\n for (int i = 0; i < n; ++i) {\n Robot robot = robots[i];\n if (robot.direction == \'R\' || stackSize == 0 || stack[stackSize - 1].direction == \'L\') {\n stack[stackSize++] = robot;\n continue;\n }\n\n if (robot.direction == \'L\') {\n int add = 1;\n while (stackSize > 0 && stack[stackSize - 1].direction == \'R\' && add) {\n int last_health = stack[stackSize - 1].health;\n if (robot.health > last_health) {\n stackSize--;\n robot.health -= 1;\n } else if (robot.health < last_health) {\n stack[stackSize - 1].health -= 1;\n add = 0;\n } else {\n stackSize--;\n add = 0;\n }\n }\n\n if (add) {\n stack[stackSize++] = robot;\n }\n }\n }\n\n qsort(stack, stackSize, sizeof(Robot), compareByIndex);\n\n int* result = (int*)malloc(stackSize * sizeof(int));\n *returnSize = stackSize;\n for (int i = 0; i < stackSize; ++i) {\n result[i] = stack[i].health;\n }\n\n free(robots);\n free(stack);\n\n return result;\n}\n```\n\n## \uD83D\uDCA1\uD83D\uDCA1\uD83D\uDCA1I encourage you to check out [my profile](https://leetcode.com/heir-of-god/) and [Project-S](https://github.com/Heir-of-God/Project-S) project for detailed explanations and code for different problems (not only Leetcode). Happy coding and learning!\uD83D\uDCDA\n\n### Please consider *upvote*\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F because I try really hard not just to put here my code and rewrite testcase to show that it works but explain you WHY it works and HOW. Thank you\u2764\uFE0F\n\n## If you have any doubts or questions feel free to ask them in comments. I will be glad to help you with understanding\u2764\uFE0F\u2764\uFE0F\u2764\uFE0F\n\n![There is image for upvote](https://assets.leetcode.com/users/images/fde74702-a4f6-4b9f-95f2-65fa9aa79c48_1716995431.3239644.png)\n
221
5
['Array', 'Stack', 'C', 'Sorting', 'Simulation', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
16
robot-collisions
✅Beats 100% -Explained with [ Video ] -C++/Java/Python/JS - Sorting - O( n log n) - Explained
beats-100-explained-with-video-cjavapyth-cky0
\n\n\n\n# YouTube Video Explanation:\n\n### To watch the video please click on "Watch On Youtube" option available the left bottom corner of the thumbnail.\n\n
lancertech6
NORMAL
2024-07-13T03:39:17.270441+00:00
2024-07-13T06:44:23.666841+00:00
14,073
false
![Screenshot 2024-07-13 090031.png](https://assets.leetcode.com/users/images/d3206d04-1bc9-4527-8bd0-a51cbc712938_1720841908.0593297.png)\n\n\n\n# YouTube Video Explanation:\n\n### To watch the video please click on "Watch On Youtube" option available the left bottom corner of the thumbnail.\n\n<!-- **If you want a video for this question please write in the comments** -->\n\n\nhttps://youtu.be/h_YTOvo65ng\n\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 2700 Subscribers*\n*Current Subscribers: 2621*\n\nFollow me on Instagram : https://www.instagram.com/divyansh.nishad/\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves robots moving on a line, each with a specific direction (\'L\' for left or \'R\' for right) and health. If two robots collide, one or both may be destroyed based on their health. The goal is to determine the health of the robots that survive all collisions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialization:**\n - Track the initial indices of the robots.\n - Sort robots by their positions to process them from left to right.\n - Use a stack to manage right-moving robots and handle collisions with left-moving robots.\n\n2. **Processing Robots:**\n - For each robot, if it moves right (\'R\'), push it onto the stack.\n - If it moves left (\'L\'), pop from the stack to handle potential collisions until the current robot\'s health is depleted or no more collisions are possible.\n\n3. **Collisions Handling:**\n - Compare the health of the left-moving and right-moving robots.\n - Update the health based on the collision rules:\n - If one robot has more health, it survives and its health decreases by one.\n - If both have the same health, both are destroyed.\n\n4. **Collect Surviving Robots:**\n - After processing all robots, gather the health of the surviving robots in the original order.\n\n# Complexity\n- **Time Complexity:** `(O(n log n))`\n - Sorting the robots based on their positions takes \\(O(n log n)\\).\n - Processing each robot and managing collisions takes \\(O(n)\\).\n\n- **Space Complexity:** `(O(n))`\n - Sorting in Python typically uses Timsort with a worst-case space complexity of \\(O(n)\\).\n - The stack used to manage collisions can hold up to \\(O(n)\\) elements in the worst case.\n\n\n\n# Step By Step Explanation\n\n### Initial State\n- **Positions:** [3, 5, 2, 6]\n- **Healths:** [10, 10, 15, 12]\n- **Directions:** "RLRL"\n- **Indices:** [0, 1, 2, 3] (representing positions 3, 5, 2, 6 respectively)\n\n### After Sorting Indices by Positions\n- **Positions:** [2, 3, 5, 6]\n- **Healths:** [15, 10, 10, 12]\n- **Directions:** "RLRL"\n- **Indices:** [2, 0, 1, 3]\n\n### Execution with Stack Operations\nWe will iterate over the sorted indices and use a stack to handle collisions between robots.\n\n1. **Index 2 (Position 2, Health 15, Direction R)**\n - Stack: [2,0]\n - No collision (stack is empty), robot is ignored as it moves left.\n\n2. **Index 0 (Position 3, Health 10, Direction R)**\n - Stack: [2,0]\n - Add to stack (robot moves right).\n\n3. **Index 1 (Position 5, Health 10, Direction L)**\n - Stack: [2]\n - Collision detected with stack top (index 0).\n - Both have equal health (10), so both are destroyed.\n - Stack: []\n - Updated Healths: [0, 0, 15, 12]\n\n4. **Index 3 (Position 6, Health 12, Direction L)**\n - Stack: [2]\n - Collision detected with stack top (index 2).\n\t\t- Stack: []\n - Updated Healths: [0, 0, 14, 0]\n\n### Final Healths (after collision resolution)\n- **Healths:** [0, 0, 14, 0]\n\n### Collecting Surviving Robots\' Healths\n- Only robot 2 remains with health 14.\n\n### Output\n- **Result:** [14]\n\n### Detailed Dry Run Table\n\n| Step | Current Index | Position | Health | Direction | Stack | Action | Updated Healths |\n|------|---------------|----------|--------|-----------|-------|--------|----------------------|\n| 1 | 2 | 2 | 15 | L | [] | Ignore | [10, 10, 15, 12] |\n| 2 | 0 | 3 | 10 | R | [0] | Push | [10, 10, 15, 12] |\n| 3 | 1 | 5 | 10 | L | [0] | Pop | [0, 0, 15, 12] |\n| 4 | 3 | 6 | 12 | L | [] | Pop | [0, 0, 15-1, 0] = [0, 0, 14, 0] |\n\n\n\n# Code\n```java []\nclass Solution {\n\n public List<Integer> survivedRobotsHealths(\n int[] positions,\n int[] healths,\n String directions\n ) {\n int n = positions.length;\n Integer[] indices = new Integer[n];\n List<Integer> result = new ArrayList<>();\n Stack<Integer> stack = new Stack<>();\n\n for (int index = 0; index < n; ++index) {\n indices[index] = index;\n }\n\n Arrays.sort(\n indices,\n (lhs, rhs) -> Integer.compare(positions[lhs], positions[rhs])\n );\n\n for (int currentIndex : indices) {\n // Add right-moving robots to the stack\n if (directions.charAt(currentIndex) == \'R\') {\n stack.push(currentIndex);\n } else {\n while (!stack.isEmpty() && healths[currentIndex] > 0) {\n // Pop the top robot from the stack for collision check\n int topIndex = stack.pop();\n\n // Top robot survives, current robot is destroyed\n if (healths[topIndex] > healths[currentIndex]) {\n healths[topIndex] -= 1;\n healths[currentIndex] = 0;\n stack.push(topIndex);\n } else if (healths[topIndex] < healths[currentIndex]) {\n // Current robot survives, top robot is destroyed\n healths[currentIndex] -= 1;\n healths[topIndex] = 0;\n } else {\n // Both robots are destroyed\n healths[currentIndex] = 0;\n healths[topIndex] = 0;\n }\n }\n }\n }\n\n // Collect surviving robots\n for (int index = 0; index < n; ++index) {\n if (healths[index] > 0) {\n result.add(healths[index]);\n }\n }\n return result;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions,\n vector<int>& healths, string directions) {\n int n = positions.size();\n vector<int> indices(n), result;\n stack<int> stack;\n\n for (int index = 0; index < n; ++index) {\n indices[index] = index;\n }\n\n sort(indices.begin(), indices.end(),\n [&](int lhs, int rhs) { return positions[lhs] < positions[rhs]; });\n\n for (int currentIndex : indices) {\n // Add right-moving robots to the stack\n if (directions[currentIndex] == \'R\') {\n stack.push(currentIndex);\n } else {\n while (!stack.empty() && healths[currentIndex] > 0) {\n // Pop the top robot from the stack for collision check\n int topIndex = stack.top();\n stack.pop();\n\n // Top robot survives, current robot is destroyed\n if (healths[topIndex] > healths[currentIndex]) {\n healths[topIndex] -= 1;\n healths[currentIndex] = 0;\n stack.push(topIndex);\n } else if (healths[topIndex] < healths[currentIndex]) {\n // Current robot survives, top robot is destroyed\n healths[currentIndex] -= 1;\n healths[topIndex] = 0;\n } else {\n // Both robots are destroyed\n healths[currentIndex] = 0;\n healths[topIndex] = 0;\n }\n }\n }\n }\n\n // Collect surviving robots\n for (int index = 0; index < n; ++index) {\n if (healths[index] > 0) {\n result.push_back(healths[index]);\n }\n }\n return result;\n }\n};\n```\n```Python []\nclass Solution:\n def survivedRobotsHealths(self, positions, healths, directions):\n n = len(positions)\n indices = list(range(n))\n result = []\n stack = deque()\n\n # Sort indices based on their positions\n indices.sort(key=lambda x: positions[x])\n\n for current_index in indices:\n # Add right-moving robots to the stack\n if directions[current_index] == "R":\n stack.append(current_index)\n else:\n while stack and healths[current_index] > 0:\n # Pop the top robot from the stack for collision check\n top_index = stack.pop()\n\n if healths[top_index] > healths[current_index]:\n # Top robot survives, current robot is destroyed\n healths[top_index] -= 1\n healths[current_index] = 0\n stack.append(top_index)\n elif healths[top_index] < healths[current_index]:\n # Current robot survives, top robot is destroyed\n healths[current_index] -= 1\n healths[top_index] = 0\n else:\n # Both robots are destroyed\n healths[current_index] = 0\n healths[top_index] = 0\n\n # Collect surviving robots\n for index in range(n):\n if healths[index] > 0:\n result.append(healths[index])\n\n return result\n```\n```JavaScript []\n/**\n * @param {number[]} positions\n * @param {number[]} healths\n * @param {string} directions\n * @return {number[]}\n */\nvar survivedRobotsHealths = function(positions, healths, directions) {\n const n = positions.length;\n const indices = Array.from({ length: n }, (_, i) => i);\n const result = [];\n const stack = [];\n\n // Sort indices based on positions\n indices.sort((lhs, rhs) => positions[lhs] - positions[rhs]);\n\n for (const currentIndex of indices) {\n if (directions[currentIndex] === \'R\') {\n stack.push(currentIndex);\n } else {\n while (stack.length > 0 && healths[currentIndex] > 0) {\n const topIndex = stack.pop();\n\n if (healths[topIndex] > healths[currentIndex]) {\n healths[topIndex] -= 1;\n healths[currentIndex] = 0;\n stack.push(topIndex);\n } else if (healths[topIndex] < healths[currentIndex]) {\n healths[currentIndex] -= 1;\n healths[topIndex] = 0;\n } else {\n healths[currentIndex] = 0;\n healths[topIndex] = 0;\n }\n }\n }\n }\n\n // Collect surviving robots\n for (let index = 0; index < n; ++index) {\n if (healths[index] > 0) {\n result.push(healths[index]);\n }\n }\n\n return result; \n};\n```\n![upvote.png](https://assets.leetcode.com/users/images/eadb683f-1338-450a-b818-a0096337f062_1720841667.784396.png)\n\n
96
5
['Array', 'Stack', 'Sorting', 'Simulation', 'Python', 'C++', 'Java', 'JavaScript']
10
robot-collisions
[Java/C++/Python] Stack Soluton
javacpython-stack-soluton-by-lee215-984k
Explanation\nNeed to sort all robots index ind (from 0 to n - 1),\nsort them by their positions first.\n\nUse a stack to keep all the robot moving to right.\nNo
lee215
NORMAL
2023-06-25T04:02:51.136884+00:00
2023-06-25T04:02:51.136920+00:00
5,639
false
# **Explanation**\nNeed to sort all robots index `ind` (from `0` to `n - 1`),\nsort them by their `positions` first.\n\nUse a `stack` to keep all the robot moving to right.\nNow we iterate robots one by one,\n\nIf it\'s moving to right,\nwon\'t collide with robots in the `stack`.\n\nIf it\'s moving to left,\ncompare its `healths[i]` with the top robot in `stack`.\n\nFinally we return the robot with positive `healths[i]`.\n<br>\n\n# **Complexity**\nTime `O(nlogn)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public List<Integer> survivedRobotsHealths(int[] positions, int[] h, String directions) {\n int n = positions.length;\n List<Integer> ind = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n ind.add(i);\n }\n ind.sort((a, b) -> Integer.compare(positions[a], positions[b]));\n\n Deque<Integer> stack = new ArrayDeque<>();\n for (int i : ind) {\n if (directions.charAt(i) == \'R\') {\n stack.push(i);\n continue;\n }\n while (!stack.isEmpty() && h[i] > 0) {\n if (h[stack.peek()] < h[i]) {\n h[stack.pop()] = 0;\n h[i] -= 1;\n } else if (h[stack.peek()] > h[i]) {\n h[stack.peek()] -= 1;\n h[i] = 0;\n } else {\n h[stack.pop()] = 0;\n h[i] = 0;\n }\n }\n }\n\n List<Integer> res = new ArrayList<>();\n for (int v : h) {\n if (v > 0) {\n res.add(v);\n }\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& h, string directions) {\n int n = positions.size();\n vector<int> ind(n), stack, res;\n for (int i = 0; i < n; i++)\n ind[i] = i;\n sort(ind.begin(), ind.end(), [&](int a, int b) {\n return positions[a] < positions[b];\n });\n for (int i : ind) {\n if (directions[i] == \'R\') {\n stack.push_back(i);\n continue;\n }\n while (!stack.empty() && h[i] > 0) {\n if (h[stack.back()] < h[i]) {\n h[stack.back()] = 0, stack.pop_back();\n h[i] -= 1;\n } else if (h[stack.back()] > h[i]) {\n h[stack.back()] -= 1;\n h[i] = 0;\n } else {\n h[stack.back()] = 0, stack.pop_back();\n h[i] = 0;\n }\n }\n }\n for (int v : h) {\n if (v > 0) {\n res.push_back(v);\n }\n }\n return res;\n }\n```\n\n**Python**\n```py\n def survivedRobotsHealths(self, positions: List[int], h: List[int], directions: str) -> List[int]:\n n = len(positions)\n ind = sorted(range(n), key=positions.__getitem__)\n stack = []\n for i in ind:\n if directions[i] == \'R\':\n stack.append(i)\n continue\n while stack and h[i] > 0:\n if h[stack[-1]] < h[i]:\n h[stack.pop()] = 0\n h[i] -= 1\n elif h[stack[-1]] > h[i]:\n h[stack[-1]] -= 1\n h[i] = 0\n else:\n h[stack.pop()] = 0\n h[i] = 0\n return [v for v in h if v > 0]\n```\n
78
0
['C', 'Python', 'Java']
11
robot-collisions
C++ Detailed Approach Using Stack || Sorting
c-detailed-approach-using-stack-sorting-f1lxt
\n# Approach\n\nInside the function, a struct named Robot is defined, which has four members: position, health, direction, and index. This struct represents the
Aditya00
NORMAL
2023-06-25T04:45:01.152987+00:00
2023-07-03T12:34:53.664993+00:00
6,872
false
\n# Approach\n\nInside the function, a struct named Robot is defined, which has four members: position, health, direction, and index. This struct represents the properties of a robot.\n\nThe function begins by initializing a vector of Robot structs called vals. Each struct is created using the corresponding elements from the input vectors, and the index is set to the current index in the loop. This vector is then sorted based on the position of the robots using a lambda function.\n\nNext, another vector of Robot structs called stack is initialized. The function iterates over each robot in the sorted vals vector. If the robot\'s direction is \'R\' (right), it is simply pushed onto the stack.\n\nFor robots with direction other than \'R\', the function checks if they can eliminate any robots on the stack. It continues popping robots from the stack as long as the top robot\'s health is less than or equal to the current robot\'s health and its direction is \'R\'. If the health of the top robot is equal to the current robot\'s health, that robot is also popped and marked as gone. Otherwise, the health of the current robot is decreased and the top robot on the stack is popped. If no elimination occurs, the current robot is pushed onto the stack.\n\nAfter processing all robots, the stack is sorted based on the original indices of the robots using another lambda function.\n\nFinally, the health values of the robots in the stack are extracted and stored in a vector called result, which is then returned as the output of the function.\n# Complexity \n- Time : O(n logn)\n- space : O(n)\n\n# C++ Code\n![image.png](https://assets.leetcode.com/users/images/1c1fb0db-ef1c-412e-83b7-c1cf4ceca6b2_1688387689.2878623.png)\n\n```\nclass Solution {\npublic:\n\n struct Robot {\n int position;\n int health;\n char direction;\n int index;\n };\n\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string& directions) {\n int n = positions.size();\n vector<Robot> vals;\n for (int i = 0; i < n; i++) {\n vals.push_back({positions[i], healths[i], directions[i], i});\n }\n sort(vals.begin(), vals.end(), [](const Robot& a, const Robot& b) {\n return a.position < b.position;\n });\n\n vector<Robot> stack;\n for (auto& robot : vals) {\n if (robot.direction == \'R\') {\n stack.push_back(robot);\n continue;\n }\n\n // Check if the robot should be eliminated\n bool gone = false;\n\n // Process the stack to eliminate robots with lower health\n while (!stack.empty() && stack.back().health <= robot.health && stack.back().direction == \'R\') {\n if (stack.back().health == robot.health) {\n stack.pop_back();\n gone = true;\n break;\n }\n robot.health--;\n stack.pop_back();\n }\n\n // If the robot is not yet eliminated and there is a robot facing right with higher health\n if (!gone && !stack.empty() && stack.back().direction == \'R\' && stack.back().health > robot.health) {\n stack.back().health--;\n gone = true;\n }\n\n // If the robot is not eliminated, add it to the stack\n if (!gone) {\n stack.push_back(robot);\n }\n }\n\n sort(stack.begin(), stack.end(), [](const Robot& a, const Robot& b) {\n return a.index < b.index;\n });\n\n vector<int> result;\n for (const auto& robot : stack) {\n result.push_back(robot.health);\n }\n\n return result;\n }\n};\n\n```
70
1
['Stack', 'Sorting', 'Python', 'C++']
6
robot-collisions
💯✅🔥Detailed Easy Java ,Python3 ,C++ Solution|| 42 ms ||≧◠‿◠≦✌
detailed-easy-java-python3-c-solution-42-yy8w
Approach\n\nThe approach used in the provided code is as follows:\n\n1. Create a Robot struct/class to store the robot\'s position, health, direction, and index
suyalneeraj09
NORMAL
2024-07-13T02:06:56.028752+00:00
2024-07-13T02:09:36.224831+00:00
5,863
false
## Approach\n\nThe approach used in the provided code is as follows:\n\n1. Create a `Robot` struct/class to store the robot\'s position, health, direction, and index.\n2. Create a vector/list of `Robot` objects and populate it with the given positions, healths, and directions.\n3. Sort the `Robot` vector/list based on the position in ascending order.\n4. Iterate through the sorted `Robot` vector/list:\n - If the current robot\'s direction is \'R\', add it to the stack.\n - If the current robot\'s direction is \'L\':\n - Check if the current robot should be eliminated by processing the stack.\n - If the current robot is not eliminated, add it to the stack.\n5. Sort the stack based on the robot\'s index in ascending order.\n6. Create a result vector/list and populate it with the health values of the robots in the stack.\n7. Return the result vector/list.\n\n---\n\n## Intuition\n\nThe intuition behind the approach is to simulate the robot battle process by considering the robots\' positions, directions, and health values. By sorting the robots based on their positions, we can process them from left to right, which simplifies the logic for eliminating robots.\n\nThe stack is used to keep track of the robots facing right. When a robot facing left encounters a robot facing right, it checks the health values of the robots in the stack. If the robot facing left has a lower health value, it is eliminated. If the robot facing left has a higher health value, it reduces the health of the robot facing right by 1.\n\nBy processing the robots in this manner, we can determine the surviving robots and their corresponding health values.\n\nSure, let\'s go through the step-by-step explanation using the input list `[5, 4, 3, 2, 1]`.\n\n---\n## Step By Step Explanation Of Code\n\n## Step 1: Create a vector/list of Robot objects\nWe create a vector/list of `Robot` objects, where each `Robot` object represents a robot with its position, health, direction, and index.\n\n```\nRobots:\n[\n {position: 5, health: 5, direction: \'R\', index: 0},\n {position: 4, health: 4, direction: \'R\', index: 1},\n {position: 3, health: 3, direction: \'R\', index: 2},\n {position: 2, health: 2, direction: \'R\', index: 3},\n {position: 1, health: 1, direction: \'R\', index: 4}\n]\n```\n\n## Step 2: Sort the Robots based on position\nWe sort the `Robot` objects based on their position in ascending order.\n\n```\nSorted Robots:\n[\n {position: 1, health: 1, direction: \'R\', index: 4},\n {position: 2, health: 2, direction: \'R\', index: 3},\n {position: 3, health: 3, direction: \'R\', index: 2},\n {position: 4, health: 4, direction: \'R\', index: 1},\n {position: 5, health: 5, direction: \'R\', index: 0}\n]\n```\n\n## Step 3: Process the Robots\nWe iterate through the sorted `Robot` objects and process them one by one.\n\n1. The first robot has a direction of \'R\', so we add it to the stack.\n * Stack: `[{position: 1, health: 1, direction: \'R\', index: 4}]`\n\n2. The second robot has a direction of \'R\', so we add it to the stack.\n * Stack: `[{position: 2, health: 2, direction: \'R\', index: 3}, {position: 1, health: 1, direction: \'R\', index: 4}]`\n\n3. The third robot has a direction of \'R\', so we add it to the stack.\n * Stack: `[{position: 3, health: 3, direction: \'R\', index: 2}, {position: 2, health: 2, direction: \'R\', index: 3}, {position: 1, health: 1, direction: \'R\', index: 4}]`\n\n4. The fourth robot has a direction of \'R\', so we add it to the stack.\n * Stack: `[{position: 4, health: 4, direction: \'R\', index: 1}, {position: 3, health: 3, direction: \'R\', index: 2}, {position: 2, health: 2, direction: \'R\', index: 3}, {position: 1, health: 1, direction: \'R\', index: 4}]`\n\n5. The fifth robot has a direction of \'R\', so we add it to the stack.\n * Stack: `[{position: 5, health: 5, direction: \'R\', index: 0}, {position: 4, health: 4, direction: \'R\', index: 1}, {position: 3, health: 3, direction: \'R\', index: 2}, {position: 2, health: 2, direction: \'R\', index: 3}, {position: 1, health: 1, direction: \'R\', index: 4}]`\n\nAt this point, the stack contains all the robots facing right.\n\n## Step 4: Sort the stack based on index\nWe sort the stack based on the robot\'s index in ascending order.\n\n```\nSorted Stack:\n[\n {position: 1, health: 1, direction: \'R\', index: 4},\n {position: 2, health: 2, direction: \'R\', index: 3},\n {position: 3, health: 3, direction: \'R\', index: 2},\n {position: 4, health: 4, direction: \'R\', index: 1},\n {position: 5, health: 5, direction: \'R\', index: 0}\n]\n```\n\n## Step 5: Create the result\nWe create the result vector/list by extracting the health values from the sorted stack.\n\n```\nResult: [1, 2, 3, 4, 5]\n```\n\nThe final result is `[1, 2, 3, 4, 5]`, which represents the health values of the surviving robots.\n\n---\n\n\n## Time Complexity\n\nThe time complexity of the provided code is O(n log n), where n is the number of robots. This is due to the sorting operations performed on the `Robot` vector/list and the stack.\n\n1. Sorting the `Robot` vector/list based on positions: O(n log n)\n2. Processing the robots and updating the stack: O(n)\n3. Sorting the stack based on indices: O(n log n)\n\nThe overall time complexity is dominated by the sorting operations, which are O(n log n).\n\n---\n\n## Space Complexity\n\nThe space complexity of the provided code is O(n), where n is the number of robots. This is because we create a `Robot` vector/list of size n to store the robot information and a stack to keep track of the robots facing right.\n\nThe additional space required for the result vector/list is also O(n), as it stores the health values of the surviving robots.\n\n---\n# Code\n```java []\nimport java.util.*;\n\nclass Solution {\n static class Robot {\n int position;\n int health;\n char direction;\n int index;\n\n Robot(int position, int health, char direction, int index) {\n this.position = position;\n this.health = health;\n this.direction = direction;\n this.index = index;\n }\n }\n\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n List<Robot> vals = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n vals.add(new Robot(positions[i], healths[i], directions.charAt(i), i));\n }\n vals.sort((a, b) -> a.position - b.position);\n\n List<Robot> stack = new ArrayList<>();\n for (Robot robot : vals) {\n if (robot.direction == \'R\') {\n stack.add(robot);\n continue;\n }\n\n boolean gone = false;\n while (!stack.isEmpty() && stack.get(stack.size() - 1).health <= robot.health && stack.get(stack.size() - 1).direction == \'R\') {\n if (stack.get(stack.size() - 1).health == robot.health) {\n stack.remove(stack.size() - 1);\n gone = true;\n break;\n }\n robot.health--;\n stack.remove(stack.size() - 1);\n }\n\n if (!gone && !stack.isEmpty() && stack.get(stack.size() - 1).direction == \'R\' && stack.get(stack.size() - 1).health > robot.health) {\n stack.get(stack.size() - 1).health--;\n gone = true;\n }\n\n if (!gone) {\n stack.add(robot);\n }\n }\n\n stack.sort((a, b) -> a.index - b.index);\n\n List<Integer> result = new ArrayList<>();\n for (Robot robot : stack) {\n result.add(robot.health);\n }\n\n return result;\n }\n}\n```\n```python3 []\nfrom typing import List\n\nclass Solution:\n class Robot:\n def __init__(self, position: int, health: int, direction: str, index: int):\n self.position = position\n self.health = health\n self.direction = direction\n self.index = index\n\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n n = len(positions)\n vals = [self.Robot(positions[i], healths[i], directions[i], i) for i in range(n)]\n vals.sort(key=lambda x: x.position)\n\n stack = []\n for robot in vals:\n if robot.direction == \'R\':\n stack.append(robot)\n continue\n\n gone = False\n while stack and stack[-1].health <= robot.health and stack[-1].direction == \'R\':\n if stack[-1].health == robot.health:\n stack.pop()\n gone = True\n break\n robot.health -= 1\n stack.pop()\n\n if not gone and stack and stack[-1].direction == \'R\' and stack[-1].health > robot.health:\n stack[-1].health -= 1\n gone = True\n\n if not gone:\n stack.append(robot)\n\n stack.sort(key=lambda x: x.index)\n\n return [robot.health for robot in stack]\n```\n```C++ []\nclass Solution {\npublic:\n\n struct Robot {\n int position;\n int health;\n char direction;\n int index;\n };\n\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string& directions) {\n int n = positions.size();\n vector<Robot> vals;\n for (int i = 0; i < n; i++) {\n vals.push_back({positions[i], healths[i], directions[i], i});\n }\n sort(vals.begin(), vals.end(), [](const Robot& a, const Robot& b) {\n return a.position < b.position;\n });\n\n vector<Robot> stack;\n for (auto& robot : vals) {\n if (robot.direction == \'R\') {\n stack.push_back(robot);\n continue;\n }\n\n // Check if the robot should be eliminated\n bool gone = false;\n\n // Process the stack to eliminate robots with lower health\n while (!stack.empty() && stack.back().health <= robot.health && stack.back().direction == \'R\') {\n if (stack.back().health == robot.health) {\n stack.pop_back();\n gone = true;\n break;\n }\n robot.health--;\n stack.pop_back();\n }\n\n // If the robot is not yet eliminated and there is a robot facing right with higher health\n if (!gone && !stack.empty() && stack.back().direction == \'R\' && stack.back().health > robot.health) {\n stack.back().health--;\n gone = true;\n }\n\n // If the robot is not eliminated, add it to the stack\n if (!gone) {\n stack.push_back(robot);\n }\n }\n\n sort(stack.begin(), stack.end(), [](const Robot& a, const Robot& b) {\n return a.index < b.index;\n });\n\n vector<int> result;\n for (const auto& robot : stack) {\n result.push_back(robot.health);\n }\n\n return result;\n }\n};\n```\n---\n![upvote.png](https://assets.leetcode.com/users/images/e6f4f26f-a7f5-465b-8ec1-aa665db072f9_1719537871.6475258.png)
43
3
['Array', 'Stack', 'C++', 'Java', 'Python3']
14
robot-collisions
Beats 97% users.... Trust this editorial solution....
beats-97-users-trust-this-editorial-solu-y12g
\n\n# Code\n\nclass Solution:\n\n def survivedRobotsHealths(\n\n self, positions: List[int], healths: List[int], directions: str\n\n ) -> List[int]
Aim_High_212
NORMAL
2024-07-13T03:31:21.774230+00:00
2024-07-13T03:31:21.774257+00:00
170
false
\n\n# Code\n```\nclass Solution:\n\n def survivedRobotsHealths(\n\n self, positions: List[int], healths: List[int], directions: str\n\n ) -> List[int]:\n\n n = len(positions)\n\n indices = list(range(n))\n\n result = []\n\n stack = deque()\n\n # Sort indices based on their positions\n\n indices.sort(key=lambda x: positions[x])\n\n for current_index in indices:\n\n # Add right-moving robots to the stack\n\n if directions[current_index] == "R":\n\n stack.append(current_index)\n\n else:\n\n while stack and healths[current_index] > 0:\n\n # Pop the top robot from the stack for collision check\n\n top_index = stack.pop()\n\n if healths[top_index] > healths[current_index]:\n\n # Top robot survives, current robot is destroyed\n\n healths[top_index] -= 1\n\n healths[current_index] = 0\n\n stack.append(top_index)\n\n elif healths[top_index] < healths[current_index]:\n\n # Current robot survives, top robot is destroyed\n\n healths[current_index] -= 1\n\n healths[top_index] = 0\n\n else:\n\n # Both robots are destroyed\n\n healths[current_index] = 0\n\n healths[top_index] = 0\n\n # Collect surviving robots\n\n for index in range(n):\n\n if healths[index] > 0:\n\n result.append(healths[index])\n\n return result\n\n \n```
29
0
['Array', 'Stack', 'C', 'Sorting', 'Simulation', 'C++', 'Java', 'Python3', 'JavaScript']
1
robot-collisions
CPP | Sorting | Stack
cpp-sorting-stack-by-amirkpatna-3272
Intuition\n Describe your first thoughts on how to solve this problem. \nInitially I did not thought that positions are not sorted hence got 1 wa.\nThen sorted
amirkpatna
NORMAL
2023-06-25T04:01:14.289254+00:00
2023-06-25T04:03:00.482671+00:00
3,478
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInitially I did not thought that positions are not sorted hence got 1 wa.\nThen sorted according to postions and used stack to solve this problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- If a robot is going to left and your stack is empty that means their is no robot to stop your current robot.\n- If your robot is going towards right just push in your stack.\n- If your robot is moving towards left and your stack is non empty.\n 1. if the health of current robot is equal to the robot which is coming from its left i.e towards right then make health of both robots to 0.\n 2. if the health of current robot is lesser to the robot which is coming from its left i.e towards right then make health of current robot to 0 and push the previous robot back in the stack and decrease it\'s health with 1.\n 3. if the health of current robot is greater to the robot which is coming from its left i.e towards right then make health of prev robot to 0 and decrease health of curr robot with 1 and continue with more prev robots if there.\n\n# Complexity\n- Time complexity: `O(nlogn)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n void performOperations(vector<int> &h,stack<int> &st,int i) {\n while(!st.empty()) {\n int top = st.top();\n st.pop();\n if(h[top] > h[i]) {\n h[top] -= 1;\n h[i] = 0;\n st.push(top);\n return ;\n } else if(h[top] == h[i]) {\n h[i] = 0, h[top] = 0;\n return ;\n }\n else {\n h[i] -= 1;\n h[top] = 0;\n }\n }\n }\n vector<int> survivedRobotsHealths(vector<int>& v, vector<int>& h, string s) {\n stack<int> st;\n int n = v.size();\n vector<int> idx(n);\n for(int i = 0; i < n; i += 1) idx[i] = i;\n sort(idx.begin(),idx.end(),[&](int i, int j) {\n return v[i] < v[j]; \n });\n for(int j = 0; j < n; j += 1) {\n int i = idx[j];\n if(s[i] == \'L\' && st.empty()) continue;\n else if(s[i] == \'R\') st.push(i);\n else {\n performOperations(h, st, i);\n }\n }\n vector<int> ans;\n for(int x : h) {\n if(x) ans.push_back(x);\n }\n return ans;\n }\n};\n```
25
1
['Stack', 'Sorting', 'C++']
5
robot-collisions
Sort (position, index) &Use vector as stack|96ms Beats 100%
sort-position-index-use-vector-as-stack9-3igc
Intuition\n Describe your first thoughts on how to solve this problem. \nVery similar to the problem Leetcode 735. Asteroid Collision\n# Approach\n Describe you
anwendeng
NORMAL
2024-07-13T01:39:23.050145+00:00
2024-07-13T10:17:11.614358+00:00
3,376
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nVery similar to the problem [Leetcode 735. Asteroid Collision](https://leetcode.com/problems/asteroid-collision/solutions/3789944/c-stack-vs-vector-python-list/)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Build a container `robot` over the info pair `(position, idx)`\n2. Sort `robot` according to `greater`, since the `stack` will store the idx for the robot with \'L\'\n3. Use C++ std::vector to do the job as a stack\n4. Transverse the `robot` & push its index `i` to the `stack`, when the direction of robot is \'L\'\n5. Otherwise proceed the while loop\n```\nwhile(!stack.empty() && healths[i]>0){//when healths[i]==0 robot is removed\n int j=stack.back();// idx for the robot[j] on the top of the stack\n int x=healths[j]-healths[i];// 3 conditions to do\n if (x>0) healths[j]--, healths[i]=0;// robot[j] survives\n else if (x<0)// robot[i] survives, remove robot[j] \n healths[j]=0, healths[i]--, stack.pop_back();\n else // both removed\n healths[i]=healths[j]=0, stack.pop_back();\n}\n\n```\n6. Pick up all robots with heath>0 & return `ans`\n7. An alternative version is to sort `robot` w.r.t. the default ordering, the `stack` will store the index for `robot` with \'R\'. The container `stack` can use C-array with a variable `top`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n $$O(n)$$\n# Code|C++ 112ms Beats 100%\n```\nclass Solution {\npublic:\n using int2=pair<int, int>;// (position, idx)\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string& directions) {\n const int n=positions.size();\n vector<int2> robot(n);\n for(int i=0; i<n; i++)// 0-indexed is fine\n robot[i]={positions[i], i};\n sort(robot.begin(), robot.end(), greater<>());\n\n vector<int> stack;\n for(auto& [pos, i]: robot){\n if (directions[i]==\'L\') stack.push_back(i);\n else{\n while(!stack.empty() && healths[i]>0){\n int j=stack.back();\n int x=healths[j]-healths[i];\n if (x>0) healths[j]--, healths[i]=0;\n else if (x<0) healths[j]=0, healths[i]--, stack.pop_back();\n else healths[i]=healths[j]=0, stack.pop_back();\n }\n }\n }\n vector<int> ans;\n for(int x: healths)\n if (x>0) ans.push_back(x);\n return ans;\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# C++ using array as stack & sort wrt less||96ms beats 100%\n```\nclass Solution {\npublic:\n using int2=pair<int, int>;// (position, idx)\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string& directions) {\n const int n=positions.size();\n vector<int2> robot(n);\n for(int i=0; i<n; i++)// 0-indexed is fine\n robot[i]={positions[i], i};\n sort(robot.begin(), robot.end());\n\n int stack[n], top=-1;\n for(auto& [_, i]: robot){\n if (directions[i]==\'R\') stack[++top]=i;\n else{\n while(top!=-1 && healths[i]>0){\n int j=stack[top];\n int x=healths[j]-healths[i];\n if (x>0) healths[j]--, healths[i]=0;\n else if (x<0) healths[j]=0, healths[i]--, top--;\n else healths[i]=healths[j]=0, top--;\n }\n }\n }\n vector<int> ans;\n for(int x: healths)\n if (x>0) ans.push_back(x);\n return ans;\n }\n};\n```
21
0
['Array', 'Stack', 'Sorting', 'Simulation', 'C++']
11
robot-collisions
Solution using stack in C++, Java & Python
solution-using-stack-in-c-java-python-by-bk1b
Intuition\nSort the robot by positions. Scan all robots from left to right. The key point is that all robots are moving with the same speed, so if they move to
cpcs
NORMAL
2023-06-25T12:55:12.089745+00:00
2023-07-08T18:03:07.155443+00:00
1,934
false
# Intuition\nSort the robot by positions. Scan all robots from left to right. The key point is that all robots are moving with the same speed, so if they move to the same direction they will never collide. And if they move to the different position, say a robot is moving to the left, then it collide with the ones moving to the right in order (based on the positions of the robots that are moving to the left, the rightmost one on its left collides first).\n\n# Approach\nScan all the robots from left to right one by one.\n(1) If it\'s moving to the right, we just push it to the stack for future use.\n(2) If it\'s moving to the left, then we pop robots from the stack one by one. Processing the collisions until the current robot disappears or the stack is empty.\n\n# Complexity\n- Time complexity:\nO(nlogn) because of sorting.\n\n- Space complexity:\nO(n)\n\n# Code\nC++\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n const int n = positions.size();\n vector<int> ind(n);\n for (int i = 0; i < n; ++i) {\n ind[i] = i;\n }\n sort(ind.begin(), ind.end(), [&](const int x, const int y) {\n return positions[x] < positions[y];\n });\n stack<int> s;\n for (int x : ind) {\n if (directions[x] == \'L\') {\n while (!s.empty()) {\n const int y = s.top();\n if (healths[x] == healths[y]) {\n healths[x] = healths[y] = 0;\n s.pop();\n break;\n }\n if (healths[x] > healths[y]) {\n --healths[x];\n healths[y] = 0;\n s.pop();\n } else {\n healths[x] = 0;\n --healths[y];\n break;\n }\n } \n } else {\n s.push(x);\n }\n }\n vector<int> r;\n for (int x : healths) {\n if (x) {\n r.push_back(x);\n }\n }\n return r;\n }\n};\n```\n\nJava:\n```\nimport java.util.*;\n\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n List<Integer> ind = new ArrayList<>();\n for (int i = 0; i < n; ++i) {\n ind.add(i);\n }\n Collections.sort(ind, (x, y) -> Integer.compare(positions[x], positions[y]));\n Stack<Integer> s = new Stack<>();\n for (int x : ind) {\n if (directions.charAt(x) == \'L\') {\n while (!s.empty()) {\n int y = s.peek();\n if (healths[x] == healths[y]) {\n healths[x] = 0;\n healths[y] = 0;\n s.pop();\n break;\n }\n if (healths[x] > healths[y]) {\n healths[x]--;\n healths[y] = 0;\n s.pop();\n } else {\n healths[x] = 0;\n healths[y]--;\n break;\n }\n } \n } else {\n s.push(x);\n }\n }\n List<Integer> result = new ArrayList<>();\n for (int x : healths) {\n if (x != 0) {\n result.add(x);\n }\n }\n return result;\n }\n}\n```\nPython\n```\nfrom typing import List\n\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n n = len(positions)\n ind = [i for i in range(n)]\n ind.sort(key=lambda x: positions[x])\n s = []\n for x in ind:\n if directions[x] == \'L\':\n while s:\n y = s[-1]\n if healths[x] == healths[y]:\n healths[x] = healths[y] = 0\n s.pop()\n break\n if healths[x] > healths[y]:\n healths[x] -= 1\n healths[y] = 0\n s.pop()\n else:\n healths[x] = 0\n healths[y] -= 1\n break\n else:\n s.append(x)\n r = [x for x in healths if x]\n return r\n\n```
20
0
['Python', 'C++', 'Java', 'Python3']
4
robot-collisions
✅🚀 🔥 || Beats 100% || || Java, Python, C++, JS, Go || Beginner Friendly🔥✨🌟
beats-100-java-python-c-js-go-beginner-f-tpym
\n\n# Intuition\n\n\nThe problem involves simulating collisions between robots moving on a line. The key insights are:\n\n1. Collisions only occur between robot
kartikdevsharma_
NORMAL
2024-07-13T04:16:36.274814+00:00
2024-08-24T04:42:41.614600+00:00
300
false
\n\n# Intuition\n\n\nThe problem involves simulating collisions between robots moving on a line. The key insights are:\n\n1. Collisions only occur between robots moving towards each other (one moving left, one moving right).\n2. The order of collisions matters, so we need to process them in the correct sequence.\n3. We can use a stack to keep track of potential collisions.\n\n# Approach\n\n1. Sort the robots based on their positions to process them in order from left to right.\n2. Use a stack to keep track of robots moving right.\n3. For each robot moving left, simulate collisions with robots moving right (from the stack).\n4. Update health values based on collision outcomes.\n5. Collect the health of surviving robots in their original order.\n\n# Complexity\n\n- Time complexity: O(n log n)\n - Sorting the robots takes O(n log n) time.\n - Processing each robot takes O(n) time in the worst case (if all robots collide).\n - The final collection of surviving robots takes O(n) time.\n - Overall, the dominant factor is the sorting, so the time complexity is O(n log n).\n\n- Space complexity: O(n)\n - We use additional space for the indices array and the stack, both of which can contain up to n elements in the worst case.\n - The answer list also takes up to O(n) space.\n\n# Code Explanation\n\nI\'ll break down the code and explain each part in detail:\n\n```java\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n```\nThis is the class and method definition. The method takes three parameters:\n- `positions`: An array of integers representing the positions of robots.\n- `healths`: An array of integers representing the health of each robot.\n- `directions`: A string where each character (\'L\' or \'R\') represents the direction of each robot.\n`n` is the number of robots.\n\n```java\n Integer[] indices = new Integer[n];\n for (int i = 0; i < n; i++) {\n indices[i] = i;\n }\n```\nThis creates an array of Integer objects, `indices`, where each element is the index of a robot. This will be used to sort the robots by position while keeping track of their original indices.\n\n```java\n // Sort indices based on positions\n Arrays.sort(indices, (a, b) -> positions[a] - positions[b]);\n```\nThis sorts the `indices` array based on the positions of the robots. The lambda expression `(a, b) -> positions[a] - positions[b]` is a comparator that compares robots by their positions. After this step, `indices` contains the indices of robots sorted by their positions.\n\n```java\n Deque<Integer> stack = new ArrayDeque<>();\n boolean[] eliminated = new boolean[n];\n```\n- `stack` is used to keep track of robots moving right (\'R\'). We use a Deque for efficient push and pop operations.\n- `eliminated` is a boolean array to mark which robots have been eliminated in collisions.\n\n```java\n for (int index : indices) {\n if (directions.charAt(index) == \'L\') {\n```\nThis loop iterates through the sorted indices. For each robot, it first checks if it\'s moving left (\'L\').\n\n```java\n while (!stack.isEmpty() && !eliminated[index]) {\n int top = stack.peek();\n```\nIf the robot is moving left, it checks for collisions with robots moving right (stored in the stack). It continues this process until either the stack is empty or the current robot is eliminated.\n\n```java\n if (healths[index] < healths[top]) {\n eliminated[index] = true;\n healths[top]--;\n } else if (healths[index] > healths[top]) {\n stack.pop();\n eliminated[top] = true;\n healths[index]--;\n } else {\n stack.pop();\n eliminated[top] = true;\n eliminated[index] = true;\n break;\n }\n }\n```\nThis block handles the collision logic:\n- If the left-moving robot has less health, it\'s eliminated and the right-moving robot loses 1 health.\n- If the left-moving robot has more health, the right-moving robot is eliminated, removed from the stack, and the left-moving robot loses 1 health.\n- If they have equal health, both are eliminated and the loop breaks.\n\n```java\n } else {\n stack.push(index);\n }\n }\n```\nIf the robot is moving right (\'R\'), it\'s simply pushed onto the stack.\n\n```java\n List<Integer> result = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n if (!eliminated[i]) {\n result.add(healths[i]);\n }\n }\n return result;\n }\n}\n```\nFinally, this creates the result list. It iterates through all robots in their original order, adding the health of non-eliminated robots to the result list.\n\n\n\n### Code\n```java []\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n Integer[] indices = new Integer[n];\n for (int i = 0; i < n; i++) {\n indices[i] = i;\n }\n \n // Sort indices based on positions\n Arrays.sort(indices, (a, b) -> positions[a] - positions[b]);\n \n Deque<Integer> stack = new ArrayDeque<>();\n boolean[] eliminated = new boolean[n];\n \n for (int index : indices) {\n if (directions.charAt(index) == \'L\') {\n while (!stack.isEmpty() && !eliminated[index]) {\n int top = stack.peek();\n if (healths[index] < healths[top]) {\n eliminated[index] = true;\n healths[top]--;\n } else if (healths[index] > healths[top]) {\n stack.pop();\n eliminated[top] = true;\n healths[index]--;\n } else {\n stack.pop();\n eliminated[top] = true;\n eliminated[index] = true;\n break;\n }\n }\n } else {\n stack.push(index);\n }\n }\n \n List<Integer> result = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n if (!eliminated[i]) {\n result.add(healths[i]);\n }\n }\n return result;\n }\n}\n```\n```python []\nfrom typing import List\n\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n n = len(positions)\n indices = sorted(range(n), key=lambda i: positions[i])\n stack = []\n \n for i in indices:\n if directions[i] == \'R\':\n stack.append(i)\n else:\n while stack and healths[i] > 0:\n j = stack[-1]\n if healths[i] < healths[j]:\n healths[j] -= 1\n healths[i] = 0\n elif healths[i] > healths[j]:\n healths[i] -= 1\n healths[j] = 0\n stack.pop()\n else:\n healths[i] = healths[j] = 0\n stack.pop()\n break\n \n return [h for h in healths if h > 0]\n```\n## Approach 2\n# Intuition\n\nThe problem involves simulating collisions between robots moving on a line. The key insights are:\n\n1. Collisions only occur between robots moving towards each other (one moving left, one moving right).\n2. The order of collisions matters, so we need to process them in the correct sequence.\n3. We can use a stack-like structure to keep track of potential collisions.\n4. By combining position and index information, we can optimize sorting and reduce memory usage.\n\n# Approach\n\n1. Combine position and index information into a single long value for efficient sorting.\n2. Sort the robots based on their positions to process them in order from left to right.\n3. Use the sorted array itself as a stack-like structure to keep track of robots moving right.\n4. For each robot moving left, simulate collisions with robots moving right (from the stack).\n5. Update health values based on collision outcomes.\n6. Collect the health of surviving robots.\n\n# Complexity\n\n- Time complexity: O(n log n)\n - Sorting the robots takes O(n log n) time.\n - Processing each robot takes O(n) time in the worst case (if all robots collide).\n - The final collection of surviving robots takes O(n) time.\n - Overall, the dominant factor is the sorting, so the time complexity is O(n log n).\n\n- Space complexity: O(n)\n - We use the `robots` array which contains n elements.\n - The answer list also takes up to O(n) space.\n - No additional data structures are used, optimizing space usage.\n\n# Code Explanation\n\nLet\'s break down the code and explain each part in detail:\n\n```java\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n var robots = new long[positions.length];\n for (int i = 0; i < robots.length; i++) {\n robots[i] = (((long) positions[i]) << 32) | i;\n }\n```\n- We create a `long` array `robots` to store both position and index information for each robot.\n- For each robot, we combine its position (shifted left by 32 bits) with its index using bitwise operations.\n- This allows us to sort based on position while keeping track of the original indices.\n\n```java\n Arrays.sort(robots);\n```\n- We sort the `robots` array, which effectively sorts the robots by their positions.\n\n```java\n int sl = 0;\n for (long posAndIndex : robots) {\n int robot = (int) posAndIndex;\n```\n- `sl` acts as a stack pointer for our stack-like structure.\n- We iterate through the sorted `robots` array.\n- `robot` is extracted as the original index of the current robot (lower 32 bits of `posAndIndex`).\n\n```java\n if(directions.charAt(robot) == \'R\') {\n robots[sl++] = robot;\n }\n```\n- If the robot is moving right, we "push" its index onto our stack (which is just the `robots` array itself).\n- `sl` is incremented to point to the next empty position in the stack.\n\n```java\n else {\n while(sl != 0 && healths[robot] != 0) {\n int other = (int) robots[sl - 1];\n```\n- If the robot is moving left, we simulate collisions with robots moving right (stored in our stack).\n- We continue this process while there are robots in the stack and the current robot hasn\'t been eliminated.\n- `other` is the index of the top robot in our stack.\n\n```java\n if (healths[other] > healths[robot]) {\n healths[robot] = 0;\n healths[other]--;\n } else if (healths[other] < healths[robot]) {\n healths[other] = 0;\n healths[robot]--;\n sl--;\n } else {\n healths[other] = 0;\n healths[robot] = 0;\n sl--;\n }\n }\n }\n }\n```\n- This block handles the collision logic:\n - If the right-moving robot has more health, the left-moving robot is eliminated and the right-moving robot loses 1 health.\n - If the left-moving robot has more health, the right-moving robot is eliminated, removed from the stack, and the left-moving robot loses 1 health.\n - If they have equal health, both are eliminated and the right-moving robot is removed from the stack.\n\n```java\n var ans = new ArrayList<Integer>(positions.length);\n for (int health : healths) {\n if (health > 0) ans.add(health);\n }\n return ans;\n }\n}\n```\n- Finally, we create the result list by iterating through the `healths` array and adding non-zero health values.\n- This preserves the original order of the surviving robots.\n\n\n```java []\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n var robots = new long[positions.length];\n for (int i = 0; i < robots.length; i++) {\n robots[i] = (((long) positions[i]) << 32) | i;\n }\n Arrays.sort(robots);\n int sl = 0;\n for (long posAndIndex : robots) {\n int robot = (int) posAndIndex;\n if(directions.charAt(robot) == \'R\') {\n robots[sl++] = robot;\n } else {\n while(sl != 0 && healths[robot] != 0) {\n int other = (int) robots[sl - 1];\n if (healths[other] > healths[robot]) {\n healths[robot] = 0;\n healths[other]--;\n } else if (healths[other] < healths[robot]) {\n healths[other] = 0;\n healths[robot]--;\n sl--;\n } else {\n healths[other] = 0;\n healths[robot] = 0;\n sl--;\n }\n }\n }\n }\n var ans = new ArrayList<Integer>(positions.length);\n for (int health : healths) {\n if (health > 0) ans.add(health);\n }\n return ans;\n }\n}\n```\n```python []\n# This solution isnt based on the approach2 we used for java and other lang\ndef survivedRobotsHealths(positions: List[int], healths: List[int], directions: str) -> List[int]:\n left, right = [], []\n for i in sorted(range(len(positions)), key=lambda i: positions[i]):\n if directions[i] == \'R\': right.append(i)\n else:\n while right and healths[right[-1]] < healths[i]:\n right.pop()\n healths[i] -= 1\n if not right: left.append(i)\n elif healths[right[-1]] == healths[i]: right.pop()\n else: healths[right[-1]] -= 1\n return [healths[i] for i in sorted(left+right)]\n\n\nit = iter(stdin)\noutput = open("user.out","w")\nfor array in it:\n output.write(dumps(survivedRobotsHealths(loads(array),loads(next(it)),loads(next(it)))).replace(\' \', \'\') + \'\\n\')\nexit()\n```\n\n```cpp []\n#include <vector>\n#include <string>\n#include <algorithm>\n\nclass Solution {\npublic:\n std::vector<int> survivedRobotsHealths(std::vector<int>& positions, std::vector<int>& healths, std::string directions) {\n int n = positions.size();\n std::vector<long long> robots(n);\n for (int i = 0; i < n; ++i) {\n robots[i] = (static_cast<long long>(positions[i]) << 32) | i;\n }\n std::sort(robots.begin(), robots.end());\n \n int sl = 0;\n for (long long pos_and_index : robots) {\n int robot = pos_and_index & 0xFFFFFFFF;\n if (directions[robot] == \'R\') {\n robots[sl++] = robot;\n } else {\n while (sl > 0 && healths[robot] > 0) {\n int other = robots[sl - 1];\n if (healths[other] > healths[robot]) {\n healths[robot] = 0;\n healths[other]--;\n } else if (healths[other] < healths[robot]) {\n healths[other] = 0;\n healths[robot]--;\n sl--;\n } else {\n healths[other] = healths[robot] = 0;\n sl--;\n }\n }\n }\n }\n \n std::vector<int> ans;\n for (int health : healths) {\n if (health > 0) ans.push_back(health);\n }\n return ans;\n }\n};\n\n```\n```javascript []\n/**\n * @param {number[]} positions\n * @param {number[]} healths\n * @param {string} directions\n * @return {number[]}\n */\nvar survivedRobotsHealths = function(positions, healths, directions) {\n const robots = positions.map((pos, i) => BigInt(pos) << 32n | BigInt(i));\n robots.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);\n \n let sl = 0;\n for (let posAndIndex of robots) {\n const robot = Number(posAndIndex & 0xFFFFFFFFn);\n if (directions[robot] === \'R\') {\n robots[sl++] = robot;\n } else {\n while (sl > 0 && healths[robot] > 0) {\n const other = robots[sl - 1];\n if (healths[other] > healths[robot]) {\n healths[robot] = 0;\n healths[other]--;\n } else if (healths[other] < healths[robot]) {\n healths[other] = 0;\n healths[robot]--;\n sl--;\n } else {\n healths[other] = healths[robot] = 0;\n sl--;\n }\n }\n }\n }\n \n return healths.filter(health => health > 0);\n};\n\n```\n\n```go []\nfunc survivedRobotsHealths(positions []int, healths []int, directions string) []int {\n robots := make([]int64, len(positions))\n for i, pos := range positions {\n robots[i] = int64(pos)<<32 | int64(i)\n }\n sort.Slice(robots, func(i, j int) bool { return robots[i] < robots[j] })\n \n sl := 0\n for _, posAndIndex := range robots {\n robot := int(posAndIndex & 0xFFFFFFFF)\n if directions[robot] == \'R\' {\n robots[sl] = int64(robot)\n sl++\n } else {\n for sl > 0 && healths[robot] > 0 {\n other := int(robots[sl-1])\n if healths[other] > healths[robot] {\n healths[robot] = 0\n healths[other]--\n } else if healths[other] < healths[robot] {\n healths[other] = 0\n healths[robot]--\n sl--\n } else {\n healths[other], healths[robot] = 0, 0\n sl--\n }\n }\n }\n }\n \n ans := []int{}\n for _, health := range healths {\n if health > 0 {\n ans = append(ans, health)\n }\n }\n return ans\n}\n```\n
13
0
['Array', 'Stack', 'Sorting', 'Simulation', 'C++', 'Java', 'Go', 'Python3', 'JavaScript']
2
robot-collisions
[C++, Java, Python] With Visuals | Stack | Sorting | Asteroid Collision
c-java-python-with-visuals-stack-sorting-vh3t
This problem has been asked in Atlassian OA for Intern 2023.\nVery similar to 735. Asteroid Collision\n\n\n# Intuition\nAssume we sort robots by their initial p
shivamaggarwal513
NORMAL
2023-06-25T04:03:45.455325+00:00
2023-06-26T10:47:13.920714+00:00
1,983
false
This problem has been asked in Atlassian OA for Intern 2023.\nVery similar to [735. Asteroid Collision\n](https://leetcode.com/problems/asteroid-collision/)\n\n# Intuition\nAssume we sort robots by their initial positions. Then, we traverse robots from left to right positions.\n\nLet\'s try few cases\n- First robot goes left: nothing happens, it keeps going on left. This robot can never collide anyone as this is the leftmost robot going left.\n```\n R1\n <--\n```\n- Second robot also goes left: nothing happens, it keeps going on.\n```\n R1 R2\n <-- <--\n```\n- Every robot going left will not collide with anyone and will proceed towards $-\\infty$.\n- Third robot goes right: no collision happens (until now)\n```\n R1 R2 R3\n <-- <-- -->\n```\n- Fourth robot goes left: now the collision will take place. (Atleast one of them will lose). There are 3 cases:\n```\n R1 R2 R3 R4\n <-- <-- --> <--\n```\n 1. `R3 > R4`: `R3` wins and `R4` loses. `R3` keeps going right with health -1.\n```\n R1 R2 R3\n <-- <-- -->\n```\n 2. `R3 = R4`: Both lose.\n```\n R1 R2\n <-- <--\n```\n 3. `R3 < R4`: `R3` loses and `R4` wins. `R4` keeps going left upto $-\\infty$ with health -1.\n```\n R1 R2 R4\n <-- <-- <--\n```\n\n---\n\nIn general case, there will be some robots going left upto $-\\infty$. We don\'t consider them anymore as they are not going to collide with anyone in future. Then there will be some robots going right. These might collide with someone coming from left in future.\n```\n R1 R2 R3 ... R(x) R(x+1) R(x+2) ... R(y) R(curr)\n <-- <-- <-- <-- --> --> --> <--\n```\n\n`R(curr)` i.e., our current robot, will collide with robots `R(y)` to `R(x+1)` or some of them.\n```\n R1 R2 R3 ... R(x) [ R(x+1) R(x+2) ... R(y) ] R(curr)\n <-- <-- <-- <-- [ --> --> --> ] <--\n```\n- `R(curr)` will win from every robot with lesser health.\n- But it will lose from the robot which is going right with bigger health.\n- Or it might encounter a same health robot where both will lose.\n- Or it might win from every robot which was going right (`R(y)` to `R(x+1)`), and then `R(curr)` continues its journey towards $-\\infty$.\n\nThis gives the intuition of using stack to simulate robots that are available to us until now (or the robots that are not lost until now).\n\n# Approach\n- Sort the robots by their initial position. Traverse from left to right maintaing stack of available robots. Topmost element of stack will represent rightmost robot.\n- If the current robot is going right, no collision happens and robot is added to stack.\n- If the current robot is going left, collisions will start happening with every robot in stack which is going right.\n- Pop the robots that lose while decreasing health of current robot.\n - We might get a robot going right with equal health. Both of them loses.\n - We might get a robot going right with greater health. It wins and its health decreases. Current robot loses.\n - Or current robot might win from every robot which was going right.\n- At last, we will have the robots that are not lost. Sort them by their initial index and return.\n\n# Code\n```C++ []\nclass Robot {\npublic:\n int position, health, index;\n char direction;\n\n Robot(int position = 0, int health = 0, char direction = 0, int index = 0)\n : position(position), health(health), direction(direction), index(index) {}\n};\n\nclass Solution {\nprivate:\n void makeCollisions(stack<Robot>& s, Robot& robot) {\n // current robot will collide with every robot in stack that is going right\n while (!s.empty() && s.top().direction == \'R\' && s.top().health < robot.health) {\n // current robot wins\n s.pop();\n robot.health--;\n }\n if (!s.empty() && s.top().direction == \'R\') { // current robot loses\n if (s.top().health == robot.health) {\n // last collision was with a robot of same health, both removed\n s.pop();\n } else {\n // last collision was with a robot of bigger health, it wins\n s.top().health--;\n }\n } else {\n // current robot wins from every robot going right\n // it continues going left towards -infinity\n s.push(robot);\n }\n }\n\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string& directions) {\n int n = positions.size();\n vector<Robot> robots(n);\n for (int i = 0; i < n; i++) {\n robots[i] = Robot(positions[i], healths[i], directions[i], i);\n }\n // sort by initial position\n sort(robots.begin(), robots.end(), \n [](Robot& r1, Robot& r2) { return r1.position < r2.position; });\n stack<Robot> s;\n for (Robot& robot: robots) {\n if (robot.direction == \'R\') { // going right\n s.push(robot);\n } else { // going left\n makeCollisions(s, robot);\n }\n }\n robots.clear();\n while (!s.empty()) {\n robots.push_back(s.top());\n s.pop();\n }\n // sort by initial index\n sort(robots.begin(), robots.end(),\n [](Robot& r1, Robot& r2) { return r1.index < r2.index; });\n vector<int> result;\n for (auto& robot: robots) {\n result.push_back(robot.health);\n }\n return result;\n }\n};\n```\n```Java []\nclass Robot {\n public int position, health, index;\n public char direction;\n\n public Robot(int position, int health, char direction, int index) {\n this.position = position;\n this.health = health;\n this.direction = direction;\n this.index = index;\n }\n}\n\nclass Solution {\n Stack<Robot> s;\n\n private void makeCollisions(Robot robot) {\n // current robot will collide with every robot in stack that is going right\n while (!s.isEmpty() && s.peek().direction == \'R\' && s.peek().health < robot.health) {\n // current robot wins\n s.pop();\n robot.health--;\n }\n if (!s.isEmpty() && s.peek().direction == \'R\') { // current robot loses\n if (s.peek().health == robot.health) {\n // last collision was with a robot of same health, both removed\n s.pop();\n } else {\n // last collision was with a robot of bigger health, it wins\n s.peek().health--;\n }\n } else {\n // current robot wins from every robot going right\n // it continues going left towards -infinity\n s.push(robot);\n }\n }\n\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n List<Robot> robots = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n robots.add(new Robot(positions[i], healths[i], directions.charAt(i), i));\n }\n // sort by initial position\n Collections.sort(robots, (r1, r2) -> r1.position - r2.position);\n s = new Stack<>();\n for (Robot robot : robots) {\n if (robot.direction == \'R\') { // going right\n s.push(robot);\n } else { // going left\n makeCollisions(robot);\n }\n }\n robots.clear();\n while (!s.isEmpty()) {\n robots.add(s.pop());\n }\n // sort by initial index\n Collections.sort(robots, (r1, r2) -> r1.index - r2.index);\n List<Integer> result = new ArrayList<>();\n for (Robot robot : robots) {\n result.add(robot.health);\n }\n return result;\n }\n}\n```\n```Python []\nclass Robot:\n def __init__(self, position: int, health: int, direction: str, index: int):\n self.position = position\n self.health = health\n self.direction = direction\n self.index = index\n \nclass Solution:\n def makeCollisions(self, s: List[Robot], robot: Robot):\n # current robot will collide with every robot in stack that is going right\n while s and s[-1].direction == \'R\' and s[-1].health < robot.health:\n # current robot wins\n s.pop()\n robot.health -= 1\n if s and s[-1].direction == \'R\': # current robot loses\n if s[-1].health == robot.health:\n # last collision was with a robot of same health, both removed\n s.pop()\n else:\n # last collision was with a robot of bigger health, it wins\n s[-1].health -= 1\n else:\n # current robot wins from every robot going right\n # it continues going left towards -infinity\n s.append(robot)\n \n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n n = len(positions)\n robots = [\n Robot(pos, health, direction, i)\n for i, (pos, health, direction) in enumerate(zip(positions, healths, directions))\n ]\n # sort by initial position\n robots.sort(key=lambda x: x.position)\n s = []\n for robot in robots:\n if robot.direction == \'R\': # going right\n s.append(robot)\n else: # going left\n self.makeCollisions(s, robot)\n robots = s\n # sort by initial index\n robots.sort(key=lambda x: x.index)\n return [robot.health for robot in robots]\n```\n\n# Complexity\nSorting time complexity is $O(n \\log n)$. Every robot is pushed and popped from the stack atmost once. Therefore, simulating stack\'s time complexity is $O(n)$.\n- Time complexity: $O(n \\log n)$\n- Space complexity: $O(n)$
13
0
['Stack', 'Sorting', 'C++', 'Java', 'Python3']
4
robot-collisions
Stack
stack-by-votrubac-o2i4
We process robots left-to-right, so we sort them first.\n\nIf a robot goes right, we add it to the stack.\n \nIf a robot goes left, we colide it with the rob
votrubac
NORMAL
2023-06-25T04:02:55.873243+00:00
2023-06-25T05:43:45.178756+00:00
1,463
false
We process robots left-to-right, so we sort them first.\n\nIf a robot goes right, we add it to the stack.\n \nIf a robot goes left, we colide it with the robot on top of the stack:\n- If the health of the robot on top of the stack is lower:\n\t- We set its health to zero.\n\t- We remove it from the stack and decrement the health of the "L"-robot.\n- Otherwise, we set the health of "L"-robot to zero.\n\t- And decrement the healt of the robot on top of the stack.\n\n**C++**\n```cpp\nvector<int> survivedRobotsHealths(vector<int>& pos, vector<int>& healths, string dirs) {\n vector<int> ids(pos.size()), st;\n iota(begin(ids), end(ids), 0);\n sort(begin(ids), end(ids), [&](int i, int j){ return pos[i] < pos[j]; });\n for (int id : ids) {\n if (dirs[id] == \'R\')\n st.push_back(id);\n else {\n while (!st.empty() && healths[id]) {\n if (healths[id] >= healths[st.back()]) {\n healths[id] = healths[id] == healths[st.back()] ? 0 : healths[id] - 1;\n healths[st.back()] = 0;\n st.pop_back();\n }\n else {\n --healths[st.back()];\n healths[id] = 0;\n }\n }\n }\n }\n healths.erase(remove(begin(healths), end(healths), 0), end(healths));\n return healths;\n}\n```
12
0
[]
3
robot-collisions
Collapse a linked list | Simple simulation approach with explanation ✅
collapse-a-linked-list-simple-simulation-bumv
Intuition\nThe first thing that comes to mind is that if we could run a simulation of the scenario, it would be easy to get the survivors. In an analog setup, s
reas0ner
NORMAL
2024-07-13T12:23:45.337329+00:00
2024-07-13T13:42:02.910923+00:00
368
false
# Intuition\nThe first thing that comes to mind is that if we could run a simulation of the scenario, it would be easy to get the survivors. In an analog setup, simulating this kind of scenario is often easy, but programmatically this might need a lot of updates to each robot in a loop, like a game loop. So, a pure simulation is too computationally expensive. Can a partial simulation be possible?\n\nOne of the things to check is whether the line in the question: **robots move simultaneously at the same speed** matters or not. If it were a time based loop, certain collisions would be happening in a certain time. What if each robot moved one by one in a sequence of our choosing instead of at the same time? We can **observe it does not matter** and the result stays same, **as long as the correct robots collide**.\n\n# Approach\nWe can use a linked list to achieve a partial simulation, here I have used a **doubly linked list to allow easy deletions**. \nFirst we sort the robots based on the positions and build our linked list.\nThen we move from the head of the linked list to the tail, processing the linked list to remove dying nodes. Whenever we find a "R L" pattern around our current pointer, we evaluate and remove the dead node due to the collision. That\'s all.\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Robot:\n def __init__(self, label, position, health, direction):\n self.label = label\n self.position = position\n self.health = health\n self.direction = direction\n self.prev = None\n self.next = None\n\nclass RobotList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def append(self, robot):\n if not self.head:\n self.head = self.tail = robot\n else:\n self.tail.next = robot\n robot.prev = self.tail\n self.tail = robot\n\n def remove(self, robot):\n if robot.prev:\n robot.prev.next = robot.next\n if robot.next:\n robot.next.prev = robot.prev\n if robot == self.head:\n self.head = robot.next\n if robot == self.tail:\n self.tail = robot.prev\n\n def collide(self, left, right):\n if left.health > right.health:\n left.health -= 1\n self.remove(right)\n right = right.next\n elif right.health > left.health:\n right.health -= 1\n self.remove(left)\n left = left.prev if left.prev else right\n else:\n self.remove(left)\n self.remove(right)\n left = left.prev if left.prev else right.next\n right = right.next if right.next else None\n\n return left, right\n\n def collide_all(self):\n curr = self.head\n while curr:\n if curr.prev and curr.prev.direction == \'R\' and curr.direction == \'L\':\n _, curr = self.collide(curr.prev, curr)\n elif curr.next and curr.direction == \'R\' and curr.next.direction == \'L\':\n curr, _ = self.collide(curr, curr.next)\n else:\n curr = curr.next\n\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n robots = [Robot(i + 1, pos, health, dir) for i, (pos, health, dir) in enumerate(zip(positions, healths, directions))]\n robots.sort(key=lambda robot: robot.position)\n\n robot_list = RobotList()\n for robot in robots:\n robot_list.append(robot)\n \n robot_list.collide_all()\n\n remaining = []\n curr = robot_list.head\n while curr:\n remaining.append(curr)\n curr = curr.next\n remaining.sort(key=lambda robot: robot.label)\n return [robot.health for robot in remaining]\n```
11
1
['Linked List', 'Stack', 'Greedy', 'Python3']
0
robot-collisions
Stack implementation based on the index of the Robot.
stack-implementation-based-on-the-index-irco1
Intuition\nTo solve this problem, we need to simulate the movement and interactions of robots based on their positions, healths, and directions. We can use a st
TACK_05
NORMAL
2024-07-13T09:07:55.730318+00:00
2024-07-13T09:07:55.730349+00:00
1,097
false
# Intuition\nTo solve this problem, we need to simulate the movement and interactions of robots based on their positions, healths, and directions. We can use a stack to keep track of robots that are moving right (\'R\') and handle collisions with robots moving left (\'L\') as we iterate through the sorted list of positions.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe store the position and index of the robots in order to get the health and direction based on the index of the respective robots. \nWe need to be carefull when there are 2 elements in the stack, instead of immediate addition we will push at the end only when the stack is empty. And check the conditions for directions if they collide then change their health.\n\n# Complexity\n- Time complexity:\nO (N*Log N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nO (N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions,\n vector<int>& healths, string direction) {\n\n vector<pair<int, int>> v;\n vector<int> ans;\n int np = positions.size();\n for (int i = 0; i < positions.size(); i++) {\n v.push_back(make_pair(positions[i], i));\n }\n sort(v.begin(), v.end());\n stack<int> st;\n st.push(v[0].second);\n for (int k = 1; k < v.size(); k++) {\n int i = v[k].second;\n if(!st.empty()){\n int temp = st.top();\n if (direction[i] == \'L\' && direction[temp] == \'R\') {\n if (healths[i] == healths[temp]) {\n st.pop();\n } else if (healths[i] > healths[temp]) {\n healths[i]--;\n st.pop();\n k--;\n } else if (healths[i] < healths[temp]) {\n healths[temp]--;\n }\n } else {\n st.push(i);\n }\n }\n else st.push(i);\n }\n while (!st.empty()) {\n ans.push_back(st.top());\n st.pop();\n }\n sort(ans.begin(), ans.end());\n for (int i = 0; i < ans.size(); i++) {\n ans[i] = healths[ans[i]];\n }\n return ans;\n }\n};\n```
11
0
['C++']
8
robot-collisions
Stack Implementation | Easy to understand
stack-implementation-easy-to-understand-tt41b
Intuition\nStart iteration from the leftmost position and encounter what\'s next.\n\n# Approach\n--> Create a vector of tuple to club the positions, healths and
Sparker_7242
NORMAL
2024-07-13T18:12:56.734041+00:00
2024-07-13T18:12:56.734063+00:00
96
false
# Intuition\nStart iteration from the leftmost position and encounter what\'s next.\n\n# Approach\n--> Create a vector of tuple to club the positions, healths and directions.\n--> Sort the vector to get the robots in order (left to right).\n\n--> Initialise a stack to keep the track of **health and positions** of the last robots who are yet to collide. NOTE that these robots will always have right directions and will collide with left moving robots if encountered during iteration.\n\n--> A map is used to keep track of positions and health remaining of the survivor robots as we have to return answer in order. *There are other appraches to do this as well.*\n\n--> Start the iteration.\n--> If a robot is moving right, push it in the stack.\n--> If a robot is moving left, compare it with top of stack elements until stack gets empty or this left moving robot is destroyed. **This logic will hold even if intially the stack was empty.** Think why?\n--> If this left moving robot survives whole the stack, **it will survive.** Think why? Set its health wrt position in map.\n--> Do not forget to decrease of the health of stronger robot by one on every collision.\n\n--> Finally after iteration, put robots\' healths left in the stack in the map as the are the survivors too.\n--> Iterate in positions vector. If map has that position survivor robot, push it in the answer vector. **This maintains the order.**\n\n# Complexity\n- Time complexity: O(nlogn)\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n = positions.size();\n vector<tuple<int,int,char>> v(n);\n for (int i = 0; i < n; i++){\n get<0>(v[i]) = positions[i];\n get<1>(v[i]) = healths[i];\n get<2>(v[i]) = directions[i];\n }\n sort(v.begin(),v.end());\n stack<pair<int,int>> s; // <health,position> vice versa will also work\n unordered_map<int,int> m; // <position,health>\n for (int i = 0; i < n; i++){\n int health = get<1>(v[i]), position = get<0>(v[i]);\n char direction = get<2>(v[i]);\n if (direction == \'R\'){\n s.push({health,position});\n } else {\n bool cnd = true; // to check if robot survived\n while (!s.empty()){\n if (health > s.top().first){\n health--;\n s.pop();\n } else if (health == s.top().first){\n s.pop();\n cnd = false; // robot destroyed\n break;\n } else {\n s.top().first--;\n cnd = false; // robot destroyed\n break;\n }\n }\n if (cnd)m[position] = health; // robot survived\n }\n }\n while (!s.empty()){ // putting survived robots\' health in map\n m[s.top().second] = s.top().first;\n s.pop();\n }\n vector<int> ans;\n for (int i = 0; i < n; i++){\n if (m[positions[i]]){ // if this positioned robot survived\n ans.push_back(m[positions[i]]);\n }\n };\n return ans;\n }\n};\n```\n\nDo not forget to upvote \uD83D\uDC4D if you found this useful.\n![image.png](https://assets.leetcode.com/users/images/0fdf2301-3e52-4efe-bc49-f16dfb526d20_1720894143.0946736.png)\n
9
0
['Stack', 'C++']
3
robot-collisions
Python | Simulation with Stack
python-simulation-with-stack-by-khosiyat-idd4
see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions:
Khosiyat
NORMAL
2024-07-13T07:38:52.791142+00:00
2024-07-13T07:38:52.791164+00:00
407
false
[see the Successfully Accepted Submission](https://leetcode.com/problems/robot-collisions/submissions/1319423677/?envType=daily-question&envId=2024-07-13)\n\n# Code\n```\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n # Combine positions, healths, and directions into a single list of tuples\n robots = sorted(zip(positions, healths, directions, range(len(positions))))\n \n stack = [] # Stack to keep track of robots moving to the right\n survivors = [] # List to keep track of surviving robots\n \n for pos, health, direction, idx in robots:\n if direction == \'R\':\n # If moving to the right, push onto the stack\n stack.append((pos, health, direction, idx))\n else: # direction == \'L\'\n while stack:\n r_pos, r_health, r_direction, r_idx = stack[-1]\n if r_direction == \'R\': # Check if top of the stack is moving right\n if r_health < health:\n # Remove right moving robot and decrease health of left moving robot\n stack.pop()\n health -= 1\n elif r_health > health:\n # Decrease health of right moving robot and stop\n stack[-1] = (r_pos, r_health - 1, r_direction, r_idx)\n health = 0\n break\n else: # r_health == health\n # Both robots destroy each other\n stack.pop()\n health = 0\n break\n else:\n break\n if health > 0:\n survivors.append((pos, health, direction, idx))\n \n # All remaining robots in the stack are survivors moving to the right\n survivors.extend(stack)\n \n # Sort survivors back to the original input order and extract their healths\n survivors.sort(key=lambda x: x[3])\n return [health for _, health, _, _ in survivors]\n\n```\n\n\n# Steps:\n\n## Sort the robots by their positions\nSince the collisions depend on the positions and movement directions, sorting the robots by their positions helps in handling collisions sequentially.\n\n## Simulate the movement and collisions:\n\n- Use a stack to keep track of robots moving to the right (\'R\').\n- As we encounter robots moving to the left (\'L\'), check for possible collisions with the robots in the stack.\n- Resolve collisions by comparing health values:\n - If the healths are equal, both robots are removed.\n - If the healths are different, the robot with lesser health is removed and the health of the surviving robot is decreased by 1.\n - Continue this until there are no more possible collisions for the current robot.\n\n## Collect the surviving robots and their healths in the original input order.\n\n# Explanation:\n\n## Combining and Sorting:\n\nWe combine positions, healths, directions, and their original indices into a list of tuples and sort this list by positions.\n\n## Handling Collisions:\n\n- We use a stack to keep track of robots moving to the right.\n- For each robot moving to the left, we check the stack (which contains robots moving to the right) for collisions.\n- Depending on the health values, we either remove robots or decrease the health of the surviving robot.\n\n## Final Collection:\n\n- After processing all robots, the stack contains surviving robots that were moving to the right.\n- We combine these with other surviving robots and sort them back to their original input order before extracting and returning their healths.\n\n\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
7
0
['Python3']
2
robot-collisions
Python 3 || 15 lines, duples, no zip ||
python-3-15-lines-duples-no-zip-by-spaul-l8bs
This code is pretty much the standard stack solution used by most on this problem, with the addition of two variations.\n\n1. We code the direction intohealths;
Spaulding_
NORMAL
2023-06-26T17:21:21.553249+00:00
2024-07-13T06:52:26.559218+00:00
341
false
This code is pretty much the standard stack solution used by most on this problem, with the addition of two variations.\n\n1. We code the direction into`healths`; `\'L\'`-> change to negative, `\'R\'`-> leave as positive.\n\n1. We use`positions`as the sort key.\n\nAs a result, we only need`idx`and`hth` as a two-tuple (a "duple") from `enumerate(healths)` for the stack. Thus, no zipping.\n```\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], \n healths: List[int], \n directions: str) -> List[int]:\n \n\n healths = map(mul,(-1 if ch == \'L\' \n else 1 for ch in directions), healths) # <-- (1)\n\n arr = sorted(enumerate(healths),\n key = lambda x: positions[x[0]]) # <-- (2)\n \n stack = deque([arr.pop(0)])\n \n for idx, hth in arr:\n if hth > 0: stack.append((idx,hth))\n\n else:\n while stack and stack[-1][1] > 0 and hth < 0:\n\n IDX, HTH = stack.pop()\n diff = HTH + hth\n\n if diff > 0: idx,hth = IDX,HTH-1 # \'R\' robot wins\n elif diff < 0: hth+= 1 # \'L\' robot wins\n else: break # robots tie\n\n else: stack.append((idx,hth)) # only appends if \n # there\'s a winner\n return [abs(hth) for _,hth in sorted(stack)]\n```\n[https://leetcode.com/problems/robot-collisions/submissions/980182168/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is *O*(*N*), in which *N* ~ `len(healths)`.
7
1
['Python3']
1
robot-collisions
[Java/Python 3] Check 'RL' after sorting by positions, w/ brief explanation and analysis.
javapython-3-check-rl-after-sorting-by-p-rima
Sort the indices of healths by positions;\n2. Traverse the sorted indices and check if the index on the top of the stack (survivors) corresponds to the directio
rock
NORMAL
2023-06-25T04:01:57.659455+00:00
2023-06-25T18:53:37.378783+00:00
1,162
false
1. Sort the indices of `healths` by `positions`;\n2. Traverse the sorted indices and check if the index on the top of the stack (`survivors`) corresponds to the direction `R` and current direction is `L`, then process according to the problem definition;\n3. return the health value still in the stack (`survivors`) sorted by their original indices.\n\n\n```java\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = healths.length;\n Integer[] sortedIndices = IntStream.range(0, n).boxed().sorted(Comparator.comparingInt(i -> positions[i])).toArray(Integer[]::new);\n Deque<Integer> survivors = new ArrayDeque<>();\n for (int i : sortedIndices) {\n while (!survivors.isEmpty() && survivors.peek() >= 0 && \n directions.charAt(survivors.peek()) == \'R\' && directions.charAt(i) == \'L\' &&\n healths[survivors.peek()] < healths[i]) {\n survivors.pop();\n healths[i] -= 1;\n }\n if (!survivors.isEmpty() && survivors.peek() >= 0 && \n directions.charAt(survivors.peek()) == \'R\' && directions.charAt(i) == \'L\') {\n if (healths[survivors.peek()] == healths[i]) {\n survivors.pop();\n }else {\n healths[survivors.peek()] -= 1;\n }\n }else {\n survivors.push(i);\n }\n }\n return survivors.stream().sorted().map(i -> healths[i]).collect(Collectors.toList());\n }\n```\n\n```python\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n n = len(healths)\n sorted_indices = sorted(range(n), key=lambda i: positions[i])\n survivors = []\n for i in sorted_indices:\n while survivors and directions[survivors[-1]] == \'R\' and directions[i] == \'L\' and healths[i] > healths[survivors[-1]]:\n healths[i] -= 1\n survivors.pop()\n if survivors and directions[survivors[-1]] == \'R\' and directions[i] == \'L\':\n if healths[i] == healths[survivors[-1]]:\n survivors.pop()\n else:\n healths[survivors[-1]] -= 1\n else: \n survivors.append(i) \n return [healths[i] for i in sorted(survivors)]\n```\n\n**Analysis:**\n\nTime: `O(nlogn)`, space: `O(n)`, where `n = healths.length`.
7
0
['Stack', 'Sorting', 'Java', 'Python3']
6
robot-collisions
Clean solution ✅|| Vector pair and stack implementation🔥^_^ || ©️cpp ✅
clean-solution-vector-pair-and-stack-imp-yw5w
Intuition\n Describe your first thoughts on how to solve this problem. \nThe only thought that came to my mind on seeing this problem is that i need to compare
parijatb_03
NORMAL
2024-07-13T12:39:09.520393+00:00
2024-07-13T12:39:09.520425+00:00
268
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n*The only thought that came to my mind on seeing this problem is that i need to compare the healths of only those conditions where the event of collision arises else we dont need to think of doing anything except for keep on storing the new robots values. Now we will get a collision only on 1 case ..... which is when the already present robot is headed \'R\' and coming new robot is headed \'L\' , no other case we will get a collision .Once we get this logic clear we can simple use a stack to keep on implementing this one logic till no 2 robots are left to compare.*\n# Approach\n<!-- Describe your approach to solving the problem. -->\n*I have used a vector v(n) which will store 2 things mainly \nno.1 : position of the robot\nno.2 : a group of values which will be the robot\'s index,health and direction*\n\n*now we sort this vector according to its index so we can work with the correct indexed robot.*\n\n*Once this done , we will use a stack which will again contain 2 things* \n**no.1 : position* *\n*no.2 : same as tht of vector v(n)\'s no.2*\n\n*So now we begin our loop to fill our stack with the first robot data\nWe will look for the condition where robot\'s direction is right ... this is important because if it is left we dont care cause it wont collide ever with another robot right ? so only when it is right we are checking that and now as we have just begun using the stack we will push this first robot inside the stack created \'st\'* . \n\n*So we will keep on iterating and going on pushing robots in stack as long as its directions = R cause they wont collide* \n\nOur only concern is when a new robot comes with the direction \'L\' \n\nNow when it happens , we will simply check for 3 situations \ni. if the new robot health == health of st.top() ie the last robot updated in the stack \nii. if new robot health is greater than the other \niii. if new robo health lesser \n\nfor i. we simply dont push the new robot into stack and just pop the last updated robot in the stack \n\nfor ii. we decrease the health of the new robot and continue ..... also note we do not directly add this robot to stack as it is important for it to compare with the rest robots that had already stored in the stack st , what if its health becomes lesser as it keeps on colliding .... so we dont add it but continue ..\n\nfor iii. we dont add the new robo data and simply decrease the last updated robo\'s health in the stack\n\nOnce we have completed iterating entire loop no more robots are left to compare and we simply push any remaining robos into the ans vector that we had used to add all the successful robos \n\nfinally we sort ans again according to positions and get the healths of the successful living robos \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTC : O(N\u2217Log(N))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSC : O(N)\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n = positions.size();\n vector<pair<int,vector<int>>>v(n);\n for(int i=0;i<n;i++){\n v[i]={positions[i],{i,healths[i],directions[i]}};\n }\n sort(v.begin(),v.end());\n stack<pair<int,vector<int>>>st;\n vector<pair<int,vector<int>>> ans;\n for(int i=0;i<n;i++){\n if(v[i].second[2]==\'R\'){\n st.push(v[i]);\n }else{\n bool insert=true;\n while(!st.empty()){\n pair<int,vector<int>> top=st.top();\n st.pop();\n if(top.second[1]==v[i].second[1]){\n insert=false;\n break;\n }else if(top.second[1]>v[i].second[1]){\n insert=false;\n top.second[1]--;\n st.push(top);\n break;\n }else{\n v[i].second[1]--;\n continue;\n }\n }\n if(insert){\n ans.push_back(v[i]);\n }\n }\n }\n while(!st.empty()){\n ans.push_back(st.top());\n st.pop();\n }\n for(int i=0;i<ans.size();i++){\n pair<int,vector<int>> temp = ans[i];\n ans[i].first=temp.second[0];\n ans[i].second[0]=temp.first;\n }\n sort(ans.begin(),ans.end());\n vector<int> res;\n for(int i=0;i<ans.size();i++){\n res.push_back(ans[i].second[1]);\n }\n return res;\n }\n};\n```\n![upvote_pic.webp](https://assets.leetcode.com/users/images/fc52405d-c780-438e-8e51-54de41ba44e7_1720873924.5361073.webp)\n
6
0
['C++']
2
robot-collisions
💯✅🔥🤐NO STACK && bruteforce has time complexity O(nlogn) and space complexity O(n)
no-stack-bruteforce-has-time-complexity-d56ha
Intuition\n Describe your first thoughts on how to solve this problem. \n\nNote:position value is not significant but positional order is significant for this q
sameonall
NORMAL
2024-07-13T06:56:59.241616+00:00
2024-07-13T20:40:59.671998+00:00
503
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n**Note**:position value is not significant but positional order is significant for this question as speed is same.Suggestion-Try to think urself!!\n**Note**:Concept of collision-segments when speed is same.\n**Collision-segments**-> means positional-segments where we have* R..RL..L* movements and independent collision happens in this segments and winners of this segments participate in collisons next time.\n**Note**:speed should be same nonzero or at rest in every collision-segments\n# Approach\n<!-- Describe your approach to solving the problem. -->\n // consider below is one of the collision-segment\n // 15 14 13 13 12 15 14 13\n // 15 14 13 12 0 15 14 13\n // 15 14 13 0 0 14 14 13\n // 15 14 0 0 0 13 14 13\n // 15 13 0 0 0 0 14 13\n // 15 0 0 0 0 0 13 13\n // 14 0 0 0 0 0 0 13\n // 13 0 0 0 0 0 0 0\n task1: sort health,directions by positions vector<pair<int,int>>h,d;\n task2: now iterate again and again till collision not possible (at max logn times iterations)and find collision segments ( R..RL..L) and call update(int l,int le,int r,vector<pair<int,int>>&h) to get winners.\n task3: store healths in vector<int>res in order as in positions vector and then store in vector ans all nonzeros health from vector<int>res;\n# Complexity\n- Time complexity:$$O(n*logn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nCollision function is called logn times as each time number of participants in every collision-segments reduced to 0 or 1.at worst size of collision-segment of two it will be logn times\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\nclass Solution {\n update(l, le, re, h) {\n let i = le, j = le + 1;\n while (i >= l && j <= re) {\n if (h[i][1] === 0) {\n i--;\n continue;\n }\n if (h[j][1] === 0) {\n j++;\n continue;\n }\n if (h[i][1] > h[j][1]) {\n h[i][1]--;\n h[j][1] = 0;\n j++;\n } else if (h[i][1] < h[j][1]) {\n h[j][1]--;\n h[i][1] = 0;\n i--;\n } else {\n h[i][1] = 0;\n h[j][1] = 0;\n i--;\n j++;\n }\n }\n }\n \n scan(h, d) {\n let i = 0;\n while (i < d.length) {\n let le = i - 1;\n let re = le;\n while (le + 1 < d.length && (h[le + 1][1] === 0 || d[le + 1][1] === \'R\')) {\n le++;\n }\n re = le;\n while (re + 1 < d.length && (h[re + 1][1] === 0 || d[re + 1][1] === \'L\')) {\n re++;\n }\n if (le === i - 1) {\n i = re + 1;\n continue;\n }\n if (re === le) {\n break;\n }\n this.update(i, le, re, h);\n i = re + 1;\n }\n }\n \n collision(h, d) {\n let right = d.length;\n let left = -1;\n for (let i = 0; i < d.length; i++) {\n if (h[i][1] > 0) {\n if (d[i][1] === \'L\') {\n left = i;\n } else if (right === d.length) {\n right = i;\n }\n }\n }\n return right < left;\n }\n \n survivedRobotsHealths(po, he, di) {\n let h = po.map((val, index) => [val, he[index]]);\n let d = po.map((val, index) => [val, di[index]]);\n \n h.sort((a, b) => a[0] - b[0]);\n d.sort((a, b) => a[0] - b[0]);\n \n while (this.collision(h, d)) {\n this.scan(h, d);\n }\n \n let res = new Array(po.length).fill(0);\n let pos = {};\n po.forEach((val, index) => pos[val] = index);\n \n h.forEach((pair) => {\n if (pair[1] > 0) {\n res[pos[pair[0]]] = pair[1];\n }\n });\n \n return res.filter(val => val > 0);\n }\n}\n\n// Example usage:\nlet po = [1, 3, 5, 7, 9];\nlet he = [2, 2, 2, 2, 2];\nlet di = "LLRLR";\n\nlet sol = new Solution();\nlet result = sol.survivedRobotsHealths(po, he, di);\nconsole.log(result); // Output: [2, 2, 2, 2, 2]\n\n```\n```python []\nclass Solution:\n def update(self, l, le, re, h):\n i, j = le, le + 1\n while i >= l and j <= re:\n if h[i][1] == 0:\n i -= 1\n continue\n if h[j][1] == 0:\n j += 1\n continue\n if h[i][1] > h[j][1]:\n h[i] = (h[i][0], h[i][1] - 1)\n h[j] = (h[j][0], 0)\n j += 1\n elif h[i][1] < h[j][1]:\n h[j] = (h[j][0], h[j][1] - 1)\n h[i] = (h[i][0], 0)\n i -= 1\n else:\n h[i] = (h[i][0], 0)\n h[j] = (h[j][0], 0)\n i -= 1\n j += 1\n \n def scan(self, h, d):\n i = 0\n while i < len(d):\n le = i - 1\n re = le\n while le + 1 < len(d) and (h[le + 1][1] == 0 or d[le + 1][1] == \'R\'):\n le += 1\n re = le\n while re + 1 < len(d) and (h[re + 1][1] == 0 or d[re + 1][1] == \'L\'):\n re += 1\n if le == i - 1:\n i = re + 1\n continue\n if re == le:\n break\n self.update(i, le, re, h)\n i = re + 1\n \n def collision(self, h, d):\n right, left = len(d), -1\n for i in range(len(d)):\n if h[i][1] > 0:\n if d[i][1] == \'L\':\n left = i\n elif right == len(d):\n right = i\n return right < left\n \n def survivedRobotsHealths(self, po, he, di):\n h = [(po[i], he[i]) for i in range(len(po))]\n d = [(po[i], di[i]) for i in range(len(po))]\n h.sort()\n d.sort()\n \n while self.collision(h, d):\n self.scan(h, d)\n \n res = [0] * len(po)\n pos = {po[i]: i for i in range(len(po))}\n for j in range(len(h)):\n res[pos[h[j][0]]] = h[j][1]\n \n ans = [f for f in res if f > 0]\n return ans\n\n```\n\n```Python3 []\nclass Solution:\n def update(self, l, le, re, h):\n i, j = le, le + 1\n while i >= l and j <= re:\n if h[i][1] == 0:\n i -= 1\n continue\n if h[j][1] == 0:\n j += 1\n continue\n if h[i][1] > h[j][1]:\n h[i][1] -= 1\n h[j][1] = 0\n j += 1\n elif h[i][1] < h[j][1]:\n h[j][1] -= 1\n h[i][1] = 0\n i -= 1\n else:\n h[i][1] = 0\n h[j][1] = 0\n i -= 1\n j += 1\n\n def scan(self, h, d):\n i = 0\n while i < len(d):\n le = i - 1\n re = le\n while le + 1 < len(d) and (h[le + 1][1] == 0 or d[le + 1][1] == \'R\'):\n le += 1\n re = le\n while re + 1 < len(d) and (h[re + 1][1] == 0 or d[re + 1][1] == \'L\'):\n re += 1\n if le == i - 1:\n i = re + 1\n continue\n if re == le:\n break\n self.update(i, le, re, h)\n i = re + 1\n\n def collision(self, h, d):\n right = len(d)\n left = -1\n for i in range(len(d)):\n if h[i][1] > 0:\n if d[i][1] == \'L\':\n left = i\n elif right == len(d):\n right = i\n return right < left\n\n def survived_robots_healths(self, po, he, di):\n size = len(po)\n h = [[0] * 2 for _ in range(size)]\n d = [[0] * 2 for _ in range(size)]\n\n for i in range(size):\n h[i][0] = po[i]\n h[i][1] = he[i]\n d[i][0] = po[i]\n d[i][1] = di[i]\n\n h.sort()\n d.sort()\n\n while self.collision(h, d):\n self.scan(h, d)\n\n pos = {}\n for i in range(size):\n pos[po[i]] = i\n\n res = []\n for j in range(size):\n if h[j][1] > 0:\n res.append(h[j][1])\n\n return res\n\n# Example usage:\npo = [1, 3, 5, 7, 9]\nhe = [2, 2, 2, 2, 2]\ndi = [\'L\', \'L\', \'R\', \'L\', \'R\']\n\nsol = Solution()\nresult = sol.survived_robots_healths(po, he, di)\nprint(result) # Output: [2, 2, 2, 2, 2]\n\n```\n\n```Ruby []\nclass Solution {\n update(l, le, re, h) {\n let i = le, j = le + 1;\n while (i >= l && j <= re) {\n if (h[i][1] === 0) {\n i--;\n continue;\n }\n if (h[j][1] === 0) {\n j++;\n continue;\n }\n if (h[i][1] > h[j][1]) {\n h[i][1]--;\n h[j][1] = 0;\n j++;\n } else if (h[i][1] < h[j][1]) {\n h[j][1]--;\n h[i][1] = 0;\n i--;\n } else {\n h[i][1] = 0;\n h[j][1] = 0;\n i--;\n j++;\n }\n }\n }\n \n scan(h, d) {\n let i = 0;\n while (i < d.length) {\n let le = i - 1;\n let re = le;\n while (le + 1 < d.length && (h[le + 1][1] === 0 || d[le + 1][1] === \'R\')) {\n le++;\n }\n re = le;\n while (re + 1 < d.length && (h[re + 1][1] === 0 || d[re + 1][1] === \'L\')) {\n re++;\n }\n if (le === i - 1) {\n i = re + 1;\n continue;\n }\n if (re === le) {\n break;\n }\n this.update(i, le, re, h);\n i = re + 1;\n }\n }\n \n collision(h, d) {\n let right = d.length;\n let left = -1;\n for (let i = 0; i < d.length; i++) {\n if (h[i][1] > 0) {\n if (d[i][1] === \'L\') {\n left = i;\n } else if (right === d.length) {\n right = i;\n }\n }\n }\n return right < left;\n }\n \n survivedRobotsHealths(po, he, di) {\n let h = po.map((val, index) => [val, he[index]]);\n let d = po.map((val, index) => [val, di[index]]);\n \n h.sort((a, b) => a[0] - b[0]);\n d.sort((a, b) => a[0] - b[0]);\n \n while (this.collision(h, d)) {\n this.scan(h, d);\n }\n \n let res = new Array(po.length).fill(0);\n let pos = {};\n po.forEach((val, index) => pos[val] = index);\n \n h.forEach((pair) => {\n if (pair[1] > 0) {\n res[pos[pair[0]]] = pair[1];\n }\n });\n \n return res.filter(val => val > 0);\n }\n}\n\n// Example usage:\nlet po = [1, 3, 5, 7, 9];\nlet he = [2, 2, 2, 2, 2];\nlet di = "LLRLR";\n\nlet sol = new Solution();\nlet result = sol.survivedRobotsHealths(po, he, di);\nconsole.log(result); // Output: [2, 2, 2, 2, 2]\n\n```\n\n\n```C++ []\nclass Solution {\npublic:\nvoid segmentUpdate(int l,int le,int re,vector<pair<int,int>>&h){\n int i=le,j=le+1;\n while(i>=l&&j<=re){\n if(h[i].second==0){i--;continue;}\n if(h[j].second==0){j++;continue;}\n if(h[i].second > h[j].second){\n h[i].second--;h[j++].second=0;\n }else if(h[i].second < h[j].second){\n h[j].second--;h[i--].second=0;\n }else{\n h[i].second=0;i--;\n h[j].second=0;j++;\n }\n }\n}\nvoid update(vector<pair<int,int>>&h,vector<pair<int,char>>&d){\n int i=0;\n while(i<d.size()){\n int le=i-1,re;\n while(le+1<d.size()&&(h[le+1].second==0||d[le+1].second==\'R\'))le++;\n re=le;\n while(re+1<d.size()&&(h[re+1].second==0||d[re+1].second==\'L\'))re++;\n if(le==i-1){i=re+1;continue;}\n if(re==le)break;\n segmentUpdate(i,le,re,h);\n i=re+1;\n }\n}\n\nbool collision(vector<pair<int,int>>&h,vector<pair<int,char>>&d){\n int right=d.size(),left=-1;\n for(int i=0;i<d.size();i++){\n if(h[i].second){\n if(d[i].second==\'L\')left=i;\n else if(right==d.size())right=i;\n }\n }\n return right<left;\n}\n vector<int> survivedRobotsHealths(vector<int>& po, vector<int>& he, string di) {\n \n vector<pair<int,int>>h;\n vector<pair<int,char>>d;\n for(int i=0;i<po.size();i++){\n h.push_back({po[i],he[i]});\n d.push_back({po[i],di[i]});\n }\n sort(h.begin(),h.end());\n sort(d.begin(),d.end());\n //O(n*logn)\n while(collision(h,d))update(h,d);\n\n vector<int>res(po.size());\n unordered_map<int,int>pos;\n for(int i=0;i<po.size();i++)pos[po[i]]=i;\n for(int j=0;j<h.size();j++){\n res[pos[h[j].first]]=h[j].second;\n }\n vector<int> ans;\n for(auto f:res)if(f)ans.push_back(f);\n return ans;\n }\n};\n```\n\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid update(int l, int le, int re, int h[][2]) {\n int i = le, j = le + 1;\n while (i >= l && j <= re) {\n if (h[i][1] == 0) {\n i--;\n continue;\n }\n if (h[j][1] == 0) {\n j++;\n continue;\n }\n if (h[i][1] > h[j][1]) {\n h[i][1]--;\n h[j][1] = 0;\n j++;\n } else if (h[i][1] < h[j][1]) {\n h[j][1]--;\n h[i][1] = 0;\n i--;\n } else {\n h[i][1] = 0;\n h[j][1] = 0;\n i--;\n j++;\n }\n }\n}\n\nvoid scan(int h[][2], char d[][2], int size) {\n int i = 0;\n while (i < size) {\n int le = i - 1, re;\n while (le + 1 < size && (h[le + 1][1] == 0 || d[le + 1][1] == \'R\')) le++;\n re = le;\n while (re + 1 < size && (h[re + 1][1] == 0 || d[re + 1][1] == \'L\')) re++;\n if (le == i - 1) {\n i = re + 1;\n continue;\n }\n if (re == le) break;\n update(i, le, re, h);\n i = re + 1;\n }\n}\n\nint collision(int h[][2], char d[][2], int size) {\n int right = size, left = -1;\n for (int i = 0; i < size; i++) {\n if (h[i][1] > 0) {\n if (d[i][1] == \'L\') left = i;\n else if (right == size) right = i;\n }\n }\n return right < left;\n}\n\nvoid survived_robots_healths(int po[], int he[], char di[], int size, int *result_size, int result[]) {\n int h[size][2];\n char d[size][2];\n \n for (int i = 0; i < size; i++) {\n h[i][0] = po[i];\n h[i][1] = he[i];\n d[i][0] = po[i];\n d[i][1] = di[i];\n }\n \n for (int i = 0; i < size; i++) {\n for (int j = i + 1; j < size; j++) {\n if (h[i][0] > h[j][0]) {\n int temp1 = h[i][0], temp2 = h[i][1];\n h[i][0] = h[j][0], h[i][1] = h[j][1];\n h[j][0] = temp1, h[j][1] = temp2;\n }\n if (d[i][0] > d[j][0]) {\n char temp1 = d[i][0], temp2 = d[i][1];\n d[i][0] = d[j][0], d[i][1] = d[j][1];\n d[j][0] = temp1, d[j][1] = temp2;\n }\n }\n }\n \n while (collision(h, d, size)) {\n scan(h, d, size);\n }\n \n int pos[size];\n for (int i = 0; i < size; i++) {\n pos[i] = -1;\n }\n for (int i = 0; i < size; i++) {\n for (int j = 0; j < size; j++) {\n if (po[i] == h[j][0]) {\n pos[i] = j;\n break;\n }\n }\n }\n \n int idx = 0;\n for (int j = 0; j < size; j++) {\n if (h[j][1] > 0) {\n result[idx++] = h[j][1];\n }\n }\n *result_size = idx;\n}\n\nint main() {\n int po[] = {1, 3, 5, 7, 9};\n int he[] = {2, 2, 2, 2, 2};\n char di[] = {\'L\', \'L\', \'R\', \'L\', \'R\'};\n int size = sizeof(po) / sizeof(po[0]);\n int result[size];\n int result_size;\n \n survived_robots_healths(po, he, di, size, &result_size, result);\n \n printf("[");\n for (int i = 0; i < result_size; i++) {\n printf("%d", result[i]);\n if (i < result_size - 1) {\n printf(", ");\n }\n }\n printf("]\\n");\n \n return 0;\n}\n\n```\n```
6
0
['Array', 'Hash Table', 'Stack', 'C', 'Sorting', 'Simulation', 'Python', 'C++', 'Ruby', 'JavaScript']
3
robot-collisions
Stack. Simple and clear solution
stack-simple-and-clear-solution-by-xxxxk-b37u
\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n stack = []\n for
xxxxkav
NORMAL
2024-07-13T01:04:20.668883+00:00
2024-07-13T01:05:39.350046+00:00
772
false
```\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n stack = []\n for i in sorted(range(len(positions)), key = lambda i: positions[i]):\n if directions[i] == \'R\':\n stack.append(i)\n else:\n while stack and healths[stack[-1]] < healths[i]:\n healths[i] -= 1\n healths[stack.pop()] = 0\n if stack:\n if healths[stack[-1]] == healths[i]:\n healths[stack.pop()] = 0\n else:\n healths[stack[-1]] -= 1\n healths[i] = 0\n return [h for h in healths if h] \n```
6
0
['Stack', 'Python3']
4
robot-collisions
✅Easy Solution ✅ Using Sorting & Stack ✅ C++ ✅Beginner Friendly🔥🔥🔥
easy-solution-using-sorting-stack-c-begi-mvvv
Approach:\n\n If a robot is moving to the left and the stack is empty, it means there is no robot to stop the current robot. Therefore, the current robot surviv
anti_quark
NORMAL
2023-06-25T05:04:22.005304+00:00
2023-06-25T05:27:41.337970+00:00
325
false
**Approach:**\n\n* If a robot is moving to the left and the stack is empty, it means there is no robot to stop the current robot. Therefore, the current robot survives.\n* If a robot is moving to the right, simply push it into the stack.\n* If a robot is moving to the left and the stack is not empty:\n* Compare the health of the current robot with the top robot in the stack.\n1. If the current robot has the same health as the top robot, both robots have their health reduced to 0 as they collide.\n2. If the current robot has lower health, set its health to 0 and push the previous robot back into the stack. Decrease the health of the previous robot by 1.\n3. If the current robot has higher health, set the health of the previous robot to 0. Decrease the health of the current robot by 1 and continue comparing with more previous robots in the stack if there are any.\n* After iterating through all the robots, the stack contains the surviving robots in the order they appeared in the input.\n* Pop the robots from the stack one by one and store their health values in a result array.\n* Reverse the result array to match the order of the robots in the input.\n* Return the result array, which contains the health of the surviving robots in the same order they were given.\nBy following this approach, we can identify the surviving robots and determine their health after the collisions have occurred.\n\n\n**Code:**\n\t\n\t\n\t\tclass Solution {\n\t\t\tpublic:\n\t\t\t\tvector<int> survivedRobotsHealths(vector<int>& p, vector<int>& h, string d) {\n\t\t\t\t\tvector<int> r=p;\n\t\t\t\t\tint n=p.size();\n\t\t\t\t\tvector<tuple<int,int,char>> v;\n\t\t\t\t\tfor(int i=0;i<n;i++) v.push_back({p[i],h[i],d[i]});\n\t\t\t\t\tsort(v.begin(),v.end());\n\n\t\t\t\t\tstack<pair<int,int>> st;\n\t\t\t\t\tint a,b; char c;\n\t\t\t\t\tvector<pair<int,int>> temp;\n\t\t\t\t\tfor(int i=0;i<n;i++){\n\t\t\t\t\t\ttie(a,b,c)=v[i];\n\t\t\t\t\t\tif(c==\'R\')\n\t\t\t\t\t\t\tst.push({a,b});\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(st.empty()) temp.push_back({a,b});\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\twhile(!st.empty()){\n\t\t\t\t\t\t\t\t\tif(st.top().second>b){\n\t\t\t\t\t\t\t\t\t\tst.top().second--;\n\t\t\t\t\t\t\t\t\t\tb=0;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if(st.top().second==b){\n\t\t\t\t\t\t\t\t\t\tst.pop();\n\t\t\t\t\t\t\t\t\t\tb=0;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\t\tb--;\n\t\t\t\t\t\t\t\t\t\tst.pop();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(b) temp.push_back({a,b});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\twhile(!st.empty()){\n\t\t\t\t\t\ttemp.push_back(st.top());\n\t\t\t\t\t\tst.pop();\n\t\t\t\t\t}\n\n\t\t\t\t\tmap<int,int> m;\n\t\t\t\t\tfor(auto i:temp) m[i.first]=i.second;\n\n\t\t\t\t\tvector<int> ans;\n\t\t\t\t\tfor(int i=0;i<n;i++){\n\t\t\t\t\t\tif(m[r[i]]) ans.push_back(m[r[i]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn ans;\n\t\t\t\t}\n\t\t\t};
6
0
['Stack', 'Sorting', 'C++']
1
robot-collisions
Java Clean Solution | Daily Challenges
java-clean-solution-daily-challenges-by-ddc6y
Complexity\n- Time complexity:O(n*K)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
Shree_Govind_Jee
NORMAL
2024-07-13T04:29:52.525436+00:00
2024-07-13T04:29:52.525458+00:00
786
false
# Complexity\n- Time complexity:$$O(n*K)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions,\n int[] healths, String directions) {\n List<Integer> list = new ArrayList<>();\n for (int i = 0; i < positions.length; i++) {\n list.add(i);\n }\n\n Collections.sort(list, (a, b) -> Integer.compare(\n positions[a], positions[b]));\n Stack<Integer> stck = new Stack<>();\n for (var l : list) {\n if (directions.charAt(l) == \'L\') {\n while (!stck.isEmpty()) {\n int temp = stck.peek();\n if (healths[l] == healths[temp]) {\n healths[l] = 0;\n healths[temp] = 0;\n stck.pop();\n break;\n } else if (healths[l] > healths[temp]) {\n healths[l]--;\n healths[temp] = 0;\n stck.pop();\n } else {\n healths[l] = 0;\n healths[temp]--;\n break;\n }\n }\n } else {\n stck.push(l);\n }\n }\n\n List<Integer> res = new ArrayList<>();\n for (var h : healths) {\n if (h != 0)\n res.add(h);\n }\n return res;\n }\n}\n```
5
0
['Array', 'Stack', 'Sorting', 'Simulation', 'Combinatorics', 'Java']
1
robot-collisions
Sorting + stack | very straight forward approach | With vid explantion
sorting-stack-very-straight-forward-appr-reuy
Watch in 2x to save your time\nhttps://youtu.be/htvW2qSuwVI\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n- We need to simulate
Atharav_s
NORMAL
2024-07-13T02:55:41.062572+00:00
2024-07-13T02:55:41.062603+00:00
1,120
false
Watch in 2x to save your time\nhttps://youtu.be/htvW2qSuwVI\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We need to simulate the movement and collisions of robots.\n- Sorting the robots by their positions can help efficiently handle collisions.\n- Using a stack to keep track of right-moving robots can optimize collision handling.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create a vector of pairs to store robot information: (position, (index, (health, direction))).\n- Sort the robots based on their positions.\n- Iterate through the sorted robots:\n1. If the robot is moving right:\n2. Push its index and direction onto the stack.\n3. Update its final health.\n4. If the robot is moving left:\n5. While there are right-moving robots on the stack and the current robot is to the left of the top right-moving robot:\n6. Compare the health of the current robot and the top right-moving robot.\n7. Update the healths of the involved robots based on collision rules.\n8. Remove the top right-moving robot from the stack if it\'s destroyed.\nIf the current robot survives, push it onto the stack and update its final health.\n- Create a result vector to store the final healths of surviving robots.\n- Iterate through the final health array and append non-negative health values to the result vector.\n- Return the result vector.\n\n# Complexity\n- Time complexity: O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n\n vector<pair<int,pair<int,pair<int,char>>>> robots;\n\n int n = positions.size();\n\n for(int i=0;i<n;i++){\n\n robots.push_back({positions[i],{i,{healths[i],directions[i]}}});\n \n }\n\n sort(robots.begin(),robots.end());\n\n stack<pair<int,char>> st;\n vector<int> finalHealth(n,-1);\n\n for(int i=0;i<n;i++){\n\n int position = robots[i].first;\n int index = robots[i].second.first;\n int health = robots[i].second.second.first;\n char direction = robots[i].second.second.second;\n\n if(direction == \'R\'){\n\n st.push({index,direction});\n finalHealth[index] = health;\n \n }else{\n\n while(!st.empty() && st.top().second == \'R\'){\n\n int rightIndex = st.top().first;\n int rightHealth = finalHealth[rightIndex];\n\n if(rightHealth > health){\n\n finalHealth[rightIndex]--;\n health = -1;\n break;\n \n }else if(rightHealth < health){\n\n finalHealth[rightIndex] = -1;\n health --;\n st.pop();\n \n }else{\n\n finalHealth[rightIndex] = -1;\n health = -1;\n st.pop();\n break;\n \n }\n \n }\n\n if(health > 0){\n finalHealth[index] = health;\n }\n \n }\n \n }\n\n vector<int> result;\n\n for(auto healthy : finalHealth){\n if(healthy > 0) result.push_back(healthy);\n }\n\n return result;\n \n }\n};\n```
5
0
['C++']
4
robot-collisions
stack || Brute force sol with comments
stack-brute-force-sol-with-comments-by-h-mi5s
Intuition\n##### Check the condition of collide , if there is collision remove robot with min health \n\n\n---\n\n\n\n# Approach\n\n###### First we arrange the
harsh_0412
NORMAL
2023-06-25T04:02:08.880463+00:00
2023-06-25T05:00:16.829599+00:00
1,728
false
# Intuition\n##### Check the condition of collide , if there is collision remove robot with min health \n\n\n---\n\n\n\n# Approach\n\n###### First we arrange the robots in ascending order of their pos , after that we start from left side and check the direction of cur robot , now check the condition of collision , if there is collision then removing robot with min health and storing left moving robots in ans whose survive till end , for right moving store in stack st \n\n- for collision\n **R --> <--L**\n- no collision \n**<--L R-->**\n**<--L <--L**\n**R--> R-->**\n\n---\n\n\n# Complexity\n- Time complexity:\nO(NlogN + N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n static bool comp( pair<int,int>&a,pair<int,int>&b){\n return a.first<b.first;\n }\n vector<int> survivedRobotsHealths(vector<int>& pos, vector<int>& h, string d) {\n vector<pair<int,int>>v;\n int n = pos.size();\n \n for( int i = 0; i< n; i++){\n v.push_back({pos[i], i}); //storing the position with index\n }\n sort(v.begin(),v.end(),comp); //sort acc to pos\n stack<int>st; // store the index of remaining robot whose surviving till now\n vector<int>ans;\n \n for( int i= 0; i < n; i++){\n \n int ind = v[i].second; // finding respective index of that pos \n \n if( d[ind] ==\'L\'){ // check the dir if it is left \n if(st.empty()) ans.push_back(ind); // if there is nothing to collide for a particle that moving in left direction so it never collide to anyone so its health never decrease , so push into our final ans \n else{\n while( !st.empty() && h[st.top()] < h[ind]){ // check if anyone going to right dir and with min health with current robot which moving in Left\n st.pop(); //removing right moving robot with min health \n h[ind]--; //health of cur robot decrease by one\n }\n if( st.empty())ans.push_back(ind); // if there no right moving robot remain so again push into our final ans \n else{\n if( h[st.top() ] == h[ind])st.pop(); // if left and right moving robot have same health then remove both robot \n else {\n h[st.top()]--; //if right moving element having more health than left ,then health of right moving decrease by one \n if( h[st.top()]== 0)st.pop(); // if( health of right moving become zero which at the top of stack them removing from stack )\n }\n }\n }\n }\n else {\n st.push(ind); // if cur robot is right moving so it don\'t collide with previous right moving robots so simply store the index of this one \n }\n }\n \n while( !st.empty()){\n ans.push_back(st.top()); // now storing tha index of remaining right moving robot whose survive till the end and present in stack\n st.pop();\n }\n sort( ans.begin(),ans.end()); // acc to question result store in intial given state \n \n for( int i =0; i< ans.size(); i++)ans[i] = h[ans[i]]; // now assigning health of robot with index ans[i] \n return ans;\n }\n};\n```\n\n\n---\n# Plz upvote !!!
5
0
['Array', 'Stack', 'Sorting', 'C++']
2
robot-collisions
✅C++ | For Beginners | Sorting | STACK | Brute Force
c-for-beginners-sorting-stack-brute-forc-sqqu
\n# Code\n\nclass Solution {\npublic:\n struct robot{\n int pos, heal, idx;\n char dir;\n };\n \n static bool mySort(robot r1, robot r
pkacb
NORMAL
2023-06-25T04:01:44.355251+00:00
2023-06-25T04:11:10.251889+00:00
182
false
\n# Code\n```\nclass Solution {\npublic:\n struct robot{\n int pos, heal, idx;\n char dir;\n };\n \n static bool mySort(robot r1, robot r2){\n return r1.pos < r2.pos;\n }\n static bool myComp(robot r1, robot r2){\n return r1.idx < r2.idx;\n }\n\n \n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n = positions.size();\n vector<robot> v(n);\n for(int i = 0; i < n; i++)\n {\n v[i].pos = positions[i];\n v[i].heal = healths[i];\n v[i].dir = directions[i];\n v[i].idx = i;\n }\n \n sort(v.begin(), v.end(), mySort);\n stack<robot> st;\n \n for(int i = 0; i < n; i++)\n {\n if(v[i].dir == \'R\')\n {\n st.push(v[i]);\n continue;\n }\n \n while(!st.empty())\n {\n robot prev = st.top();\n if(prev.dir == \'L\')\n break;\n st.pop();\n if(prev.heal < v[i].heal)\n v[i].heal--;\n else if(prev.heal > v[i].heal)\n {\n prev.heal--;\n st.push(prev);\n v[i].heal = 0;\n break;\n }\n else\n {\n v[i].heal = 0;\n break;\n }\n }\n if(v[i].heal > 0)\n st.push(v[i]);\n\n \n }\n \n \n vector<robot> temp;\n while(!st.empty())\n temp.push_back(st.top()), st.pop();\n \n sort(temp.begin(), temp.end(), myComp);\n \n vector<int> ans;\n for(int i = 0; i < temp.size(); i++)\n ans.push_back(temp[i].heal);\n \n return ans;\n }\n};\n```
5
0
['Stack', 'Sorting', 'C++']
1
robot-collisions
Optimized Collision Handling for Neighbouring Robots, 100% beats Simple Solution
optimized-collision-handling-for-neighbo-niiy
Beats\n\n\n# Intuition\nTwo neighbour robots will always collide if their directions are different, We can see a pattern here that we have to start with left mo
sxnchayyyy
NORMAL
2024-07-13T07:24:36.694229+00:00
2024-07-13T07:24:36.694251+00:00
226
false
# Beats\n![Screenshot 2024-07-13 123523.png](https://assets.leetcode.com/users/images/e017a382-691e-442a-87ee-4654bcbc05b9_1720855160.837885.png)\n\n# Intuition\nTwo neighbour robots will always collide if their directions are different, We can see a pattern here that we have to start with left most position in sorted order and check for all the collisions and make changes according to the results of that particular collision.\n\n# Approach\n1) The first thing we have to do is to sort the positions such that we dont lose the direction of movement and the health of the robot, so what we will do is make a vector of tuples and each tuple will consist of position of the robot, health of the robot and the direction it is moving in.\n\n2) We have to see where the collision is occuring between two neighbouring robots, We have seen that happen for quite a few time now yeah? We will use a Stack that will primarily contain the direction of the robots with the position sorted in an increasing order, if the current direction is different from the direction of the robot on top of the stack a collision is bound to occur.\n\n3) We will handle the case where the current robot has a health greater than the robot at the top of the stack, when the healths are equal and when the robot at the top of the stack has more health.\n\n4) Since we have to return the healths in the order we were given, we will keep the indies of both the robots with us, if one robot get defeated we will immediately update the health of the robot in the result array using the original position.\n\n5) For the robots who were not defeated we will update their healths after doing all the operations, We have updated all the healths in our stack, All we have to do is just pop the elements of stack and update our result array based on the final healths.\n\n6) Since we have marked the healths of defeated robots as zero and the problem has asked us to remove their health, all we have to do is remove all the 0s from the result array and return the final array!\n\n# Complexity\n- Time complexity:\nO(N log (N)) Because of the sorting\n\n- Space complexity:\nO(N) We have used a few linear data structures like a vector, a stack and a vector of tuple but the tuple was of length 3 or 4 so that is linear only.\n\n# Code\n```\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define nline \'\\n\'\n#define sp \' \'\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\n\nstatic int fastIO = []()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n return 0;\n}();\n\nclass Solution\n{\npublic:\n vector<int> survivedRobotsHealths(vector<int> &positions, vector<int> &healths, string directions)\n {\n int n = positions.size();\n vector<tuple<int, int, char, int>> Robots(n);\n\n for (int i = 0; i < n; i++)\n {\n Robots[i] = make_tuple(positions[i], healths[i], directions[i], i);\n }\n\n sort(all(Robots));\n\n stack<tuple<char, int, int>> stk;\n vector<int> result(n, -1);\n\n for (int i = 0; i < n; i++)\n {\n char direction = get<2>(Robots[i]);\n int health = get<1>(Robots[i]);\n int originalIndex = get<3>(Robots[i]);\n\n while (!stk.empty() && get<0>(stk.top()) == \'R\' && direction == \'L\')\n {\n if (get<1>(stk.top()) == health)\n {\n result[get<2>(stk.top())] = 0;\n result[originalIndex] = 0;\n stk.pop();\n health = 0;\n break;\n }\n else if (get<1>(stk.top()) > health)\n {\n get<1>(stk.top()) -= 1;\n result[originalIndex] = 0;\n health = 0;\n break;\n }\n else\n {\n health -= 1;\n result[get<2>(stk.top())] = 0;\n stk.pop();\n }\n }\n\n if (health > 0)\n {\n stk.push({direction, health, originalIndex});\n }\n }\n\n while (!stk.empty())\n {\n tuple<char, int, int> top = stk.top();\n stk.pop();\n result[get<2>(top)] = get<1>(top);\n }\n\n result.erase(remove(result.begin(), result.end(), 0), result.end());\n\n return result;\n }\n};\n```\n# Upvote ?\n![upvote meme.jpg](https://assets.leetcode.com/users/images/cacd2aa1-a162-4da6-93b2-39654a2c2c17_1720855200.286236.jpeg)\n
4
0
['C++']
4
robot-collisions
Beats 98% , pehle istemal kare fir vishwash kare 👌
beats-98-pehle-istemal-kare-fir-vishwash-kgn8
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
adarshydv
NORMAL
2024-07-13T04:03:53.475746+00:00
2024-07-13T04:03:53.475775+00:00
557
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions,\n vector<int>& healths, string directions) {\n int n = positions.size();\n vector<int> indices(n), result;\n stack<int> stack;\n\n for (int index = 0; index < n; ++index) {\n indices[index] = index;\n }\n\n sort(indices.begin(), indices.end(),\n [&](int lhs, int rhs) { return positions[lhs] < positions[rhs]; });\n\n for (int currentIndex : indices) {\n // Add right-moving robots to the stack\n if (directions[currentIndex] == \'R\') {\n stack.push(currentIndex);\n } else {\n while (!stack.empty() && healths[currentIndex] > 0) {\n // Pop the top robot from the stack for collision check\n int topIndex = stack.top();\n stack.pop();\n\n // Top robot survives, current robot is destroyed\n if (healths[topIndex] > healths[currentIndex]) {\n healths[topIndex] -= 1;\n healths[currentIndex] = 0;\n stack.push(topIndex);\n } else if (healths[topIndex] < healths[currentIndex]) {\n // Current robot survives, top robot is destroyed\n healths[currentIndex] -= 1;\n healths[topIndex] = 0;\n } else {\n // Both robots are destroyed\n healths[currentIndex] = 0;\n healths[topIndex] = 0;\n }\n }\n }\n }\n\n // Collect surviving robots\n for (int index = 0; index < n; ++index) {\n if (healths[index] > 0) {\n result.push_back(healths[index]);\n }\n }\n return result;\n }\n};\n```
4
1
['C++']
6
robot-collisions
NO stack; Is this CLEAN code?
no-stack-is-this-clean-code-by-navid-jtm9
Describe your first thoughts on how to solve this problem. \n\n# Intuition\n\nWe put all robots in their positions. Then start from the left (lowest position).
navid
NORMAL
2023-06-25T08:53:09.686338+00:00
2023-06-25T09:30:38.882976+00:00
657
false
![robo-fight.jpg](https://assets.leetcode.com/users/images/9e66d9c9-0625-4cdf-b957-8d1561a26b34_1687681164.2591827.jpeg)<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Intuition\n\nWe put all robots in their positions. Then start from the left (lowest position). We keep moving forward (to the right or higher position), until we can find a fightable pair of robots. But what are fightable robots?\n\n# Can you eat popcorn?\n\nIf we could find a robot that goes to the left (moves backward), it means that we could successfully find the fightable pair. Is that correct?\n\nNope! if the previous robot is also going to the left, or there\'s no previous robot, then we have to keep moving forward and check the next robot.\n\nBut if the previous robot goes to the right, we start eating popcorn and watching the fight.\n\n\n# Approach\nWe use TreeMap (it\'s like HashMap, but the keys are sorted).\nKeys will be the position, and the value will be the Robot object.\n\nWe have a variable called `positionGoingLeft` which is used to find the position of the robot that goes to the left.\nYou can\'t imagine what `positionGoingRight` is.\n\n# Complexity\n\n- Time complexity:\nSince the keys in `treeMap` are sorted, it will take `O(n log n)` to build the `treeMap`.\nFor each key on the `treeMap` (which is the position for the robots), we check the previous and next one which is `O(log n)`. \nSo the time complexity will be `O(n log n)`\n\n\n- Space complexity:\n`O(n)` because we store n objects in the `treeMap`\n\n# Very Important Question\n\nCan you make the code cleaner than this (please comment) or does this deserve an upvote?\n\n# Code\n```\nclass Robot {\n int index;\n int health;\n boolean goingLeft;\n\n public Robot(int i, int health, char direction) {\n index = i;\n this.health = health;\n this.goingLeft = direction == \'L\';\n }\n}\n\nTreeMap<Integer, Robot> treeMap = new TreeMap<>();\nInteger positionGoingLeft = 0;\nInteger positionGoingRight = 0;\n\npublic List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n createTreeMap(positions, healths, directions);\n findFighters();\n return getResult();\n}\n\n void createTreeMap(int[] positions, int[] healths, String directions) {\n for (int i = 0; i < positions.length; i++) {\n Robot robot = new Robot(i + 1, healths[i], directions.charAt(i));\n treeMap.put(positions[i], robot);\n }\n }\n\n private void findFighters() {\n while (fightableRobotsExist()) {\n fight();\n }\n }\n\n private boolean fightableRobotsExist() {\n while (foundRobotGoingLeft()) {\n if (previousRobotGoesRight()) {\n return true;\n }\n positionGoingLeft++;\n }\n return false;\n }\n\n private boolean foundRobotGoingLeft() {\n positionGoingLeft = treeMap.ceilingKey(positionGoingLeft);\n while (positionGoingLeft != null) {\n Robot nextRobot = treeMap.get(positionGoingLeft);\n if (nextRobot.goingLeft) {\n return true;\n }\n positionGoingLeft = treeMap.higherKey(positionGoingLeft);\n }\n return false;\n }\n\n private boolean previousRobotGoesRight() {\n positionGoingRight = treeMap.lowerKey(positionGoingLeft);\n if (positionGoingRight == null) {\n return false;\n }\n Robot robotGoingRight = treeMap.get(positionGoingRight);\n return !robotGoingRight.goingLeft;\n }\n\n private void fight() {\n Robot robotGoingLeft = treeMap.get(positionGoingLeft);\n Robot robotGoingRight = treeMap.get(positionGoingRight);\n if (robotGoingRight.health == robotGoingLeft.health) {\n treeMap.remove(positionGoingLeft);\n treeMap.remove(positionGoingRight);\n } else if (robotGoingRight.health < robotGoingLeft.health) {\n treeMap.remove(positionGoingRight);\n robotGoingLeft.health--;\n } else {\n treeMap.remove(positionGoingLeft);\n robotGoingRight.health--;\n }\n }\n\n\n private List<Integer> getResult() {\n PriorityQueue<Robot> robotPriorityQueue = getPriorityQueueSortedByIndex();\n return getHealths(robotPriorityQueue);\n }\n\n private PriorityQueue<Robot> getPriorityQueueSortedByIndex() {\n PriorityQueue<Robot> priorityQueueSortedByOriginalIndex = new PriorityQueue<>\n (Comparator.comparingInt(a -> a.index));\n for (Map.Entry<Integer, Robot> entry : treeMap.entrySet()) {\n priorityQueueSortedByOriginalIndex.add(entry.getValue());\n }\n return priorityQueueSortedByOriginalIndex;\n }\n \n private List<Integer> getHealths(PriorityQueue<Robot> robotPriorityQueue) {\n List<Integer> results = new ArrayList<>();\n while (!robotPriorityQueue.isEmpty()) {\n Robot r = robotPriorityQueue.remove();\n results.add(r.health);\n }\n return results;\n }\n\n```
4
0
['Tree', 'Binary Search Tree', 'Sorting', 'Java']
1
robot-collisions
C++ || sorting || stack || simple solution
c-sorting-stack-simple-solution-by-its_n-vp1z
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& pos, vector<int>& h, string d) {\n \n \n vecto
its_navneet
NORMAL
2023-06-25T04:04:57.145218+00:00
2023-06-25T08:11:33.338473+00:00
1,197
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& pos, vector<int>& h, string d) {\n \n \n vector<pair<int,int>>vp ;\n int n=pos.size() ;\n for(int i=0;i<n;i++) {\n \n vp.push_back({pos[i],i}) ;\n }\n \n sort(vp.begin(),vp.end()) ;\n \n stack<int>st ;\n \n \n for(int i=0;i<n;i++) {\n int ind=vp[i].second ;\n char dir=d[ind] ;\n \n if(dir==\'L\') {\n \n if(st.empty()) {\n st.push(ind) ; \n }\n else {\n \n if(d[st.top()]==\'R\' && h[st.top()] ==h[ind]) {\n h[st.top()]=0 ;\n st.pop() ;\n h[ind]=0 ;\n \n }\n else{ \n \n while(!st.empty() && d[st.top()]==\'R\' && h[st.top()] < h[ind] ){\n h[st.top()]=0 ;\n st.pop();\n h[ind]--;\n }\n // left robot moving in right direction and health is greater than curr robot\n if(!st.empty() && d[st.top()]==\'R\' && h[st.top()] > h[ind]) {\n h[st.top()]--; \n h[ind]=0 ;\n }\n // left robot moving in right direction and health is equal to curr robot\n else if(!st.empty() && d[st.top()]==\'R\' && h[st.top()] == h[ind]) {\n h[st.top()]=0; \n h[ind]=0 ;\n st.pop();\n }\n else{\n st.push(ind) ;\n }\n }\n \n }\n } \n // moving in right direction, collison is not possible with behind this robot\n else{\n st.push(ind) ; \n }\n }\n \n vector<int>ans;\n \n for(int x:h) {\n if(x >0) ans.push_back(x) ; \n }\n \n return ans;\n \n }\n};\n```
4
0
['C++']
2
robot-collisions
🔥LITTLE BIT COMPLEX CODE in C++🔥||🔥stack🔥
little-bit-complex-code-in-cstack-by-gan-2ldt
if this code helps you, please upvote that\'s helps to me.\n# Code\n\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, v
ganeshkumawat8740
NORMAL
2023-06-25T04:03:18.567461+00:00
2023-06-25T04:15:06.437183+00:00
377
false
# if this code helps you, please upvote that\'s helps to me.\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<vector<int>> tmp;\n for(int i = 0; i < positions.size(); i++){\n tmp.push_back({positions[i],healths[i],directions[i],i});\n }\n sort(tmp.begin(),tmp.end());\n vector<int> vv(positions.size());\n for(int i = 0; i < positions.size(); i++){\n positions[i] = tmp[i][0];\n healths[i] = tmp[i][1];\n directions[i] = tmp[i][2];\n vv[i] = tmp[i][3];\n }\n vector<int> ans(directions.length(),0);\n vector<vector<int>> v;\n int i = 0, n = directions.length(),k=1;\n while(i<n && directions[i]==\'L\'){\n v.push_back({0,healths[i],vv[i]});\n i++;\n }\n while(i<n){\n while(i<n&&directions[i]==\'R\'){\n v.push_back({1,healths[i],vv[i]});\n i++;\n }\n if(i<n && directions[i]==\'L\'){\n k = 1;\n while(!v.empty() && v.back()[0] == 1){\n if(v.back()[1]<healths[i]){\n healths[i]--;\n v.pop_back();\n }else if(v.back()[1]==healths[i]){\n v.pop_back();\n k=0;\n i++;\n break;\n }else{\n k=0;\n v.back()[1]--;\n i++;\n break;\n }\n }\n if(k && healths[i]>0){\n v.push_back({0,healths[i],vv[i]});\n i++;\n }\n }\n \n }\n if(v.empty())return {};\n for(auto &i: v)ans[i[2]] = i[1];\n vector<int> xxxx;\n for(auto &i: ans){\n if(i)xxxx.push_back(i);\n }\n return xxxx;\n }\n};\n```
4
1
['Array', 'Stack', 'C++']
1
robot-collisions
Simple Java Code ☠️
simple-java-code-by-abhinandannaik1717-qblj
\n\n# Code\n\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.l
abhinandannaik1717
NORMAL
2024-07-13T14:04:20.587356+00:00
2024-07-13T14:04:20.587390+00:00
178
false
\n\n# Code\n```\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n int l=0,r=0;\n ArrayList<Integer> ans = new ArrayList<Integer>();\n for(int i=0;i<n;i++){\n if(directions.charAt(i)==\'R\'){\n l++;\n }\n else{\n r++;\n }\n }\n if(l==0 || r==0){\n for(int i=0;i<n;i++){\n ans.add(healths[i]);\n }\n return ans;\n }\n int[][] le = new int[l][3];\n int[][] ri = new int[r][3]; \n l=0;r=0;\n for(int i=0;i<n;i++){\n if(directions.charAt(i)==\'R\'){\n le[l][0]=positions[i];\n le[l][1]=healths[i];\n le[l][2]=i;\n l++;\n }\n else{\n ri[r][0]=positions[i];\n ri[r][1]=healths[i];\n ri[r][2]=i;\n r++;\n }\n }\n Arrays.sort(le,(a, b)->Integer.compare(a[0], b[0]));\n Arrays.sort(ri,(a, b)->Integer.compare(a[0], b[0]));\n int i=le.length-1,j=0;\n for(;i>=0;i--){\n for(j=0;j<ri.length;j++){\n if(le[i][0]>ri[j][0] || ri[j][1]==0){\n continue;\n }\n if(le[i][1]>ri[j][1]){\n le[i][1]--;\n ri[j][1]=0;\n }\n else if(le[i][1]<ri[j][1]){\n le[i][1]=0;\n ri[j][1]--;\n break;\n }\n else{\n le[i][1]=0;\n ri[j][1]=0;\n break;\n }\n }\n }\n int[][] res = new int[l+r][2];\n j=0;\n for(i=0;i<ri.length;i++){\n res[j][0]=ri[i][1];\n res[j][1]=ri[i][2];\n j++;\n }\n for(i=0;i<le.length;i++){\n res[j][0]=le[i][1];\n res[j][1]=le[i][2];\n j++;\n }\n Arrays.sort(res,(a, b)->Integer.compare(a[1], b[1]));\n for(i=0;i<res.length;i++){\n if(res[i][0]!=0){\n ans.add(res[i][0]);\n }\n }\n return ans;\n }\n}\n```\n\n\n\n### Overview\nYou need to determine the health of robots that survive collisions. Robots have initial positions, healths, and movement directions. When two robots collide, one or both may be removed based on their health. The goal is to return the health of the surviving robots in their original input order.\n\n### Code Breakdown\n\n1. **Initialization:**\n ```java\n int n = positions.length;\n int l = 0, r = 0;\n ArrayList<Integer> ans = new ArrayList<Integer>();\n ```\n\n - `n` is the number of robots.\n - `l` and `r` are counters for robots moving left (\'L\') and right (\'R\'), respectively.\n - `ans` is the list that will store the health of surviving robots.\n\n2. **Counting Robots by Direction:**\n ```java\n for (int i = 0; i < n; i++) {\n if (directions.charAt(i) == \'R\') {\n l++;\n } else {\n r++;\n }\n }\n ```\n\n - Loop through the `directions` string to count how many robots are moving left (`r`) and how many are moving right (`l`).\n\n3. **Checking if All Robots Move in the Same Direction:**\n ```java\n if (l == 0 || r == 0) {\n for (int i = 0; i < n; i++) {\n ans.add(healths[i]);\n }\n return ans;\n }\n ```\n\n - If all robots move in the same direction (`l == 0` or `r == 0`), there will be no collisions. Add all health values to `ans` and return it.\n\n4. **Separating Robots by Direction:**\n ```java\n int[][] le = new int[l][3];\n int[][] ri = new int[r][3];\n l = 0;\n r = 0;\n\n for (int i = 0; i < n; i++) {\n if (directions.charAt(i) == \'R\') {\n le[l][0] = positions[i];\n le[l][1] = healths[i];\n le[l][2] = i;\n l++;\n } else {\n ri[r][0] = positions[i];\n ri[r][1] = healths[i];\n ri[r][2] = i;\n r++;\n }\n }\n ```\n\n - Separate robots into `le` (left-moving) and `ri` (right-moving) arrays.\n - Each array stores the robot\'s position, health, and original index.\n\n5. **Sorting Robots by Position:**\n ```java\n Arrays.sort(le, (a, b) -> Integer.compare(a[0], b[0]));\n Arrays.sort(ri, (a, b) -> Integer.compare(a[0], b[0]));\n ```\n\n - Sort `le` and `ri` arrays by position to prepare for collision processing.\n\n6. **Processing Collisions:**\n ```java\n int i = le.length - 1, j = 0;\n\n for (; i >= 0; i--) {\n for (j = 0; j < ri.length; j++) {\n if (le[i][0] > ri[j][0] || ri[j][1] == 0) {\n continue;\n }\n if (le[i][1] > ri[j][1]) {\n le[i][1]--;\n ri[j][1] = 0;\n } else if (le[i][1] < ri[j][1]) {\n le[i][1] = 0;\n ri[j][1]--;\n break;\n } else {\n le[i][1] = 0;\n ri[j][1] = 0;\n break;\n }\n }\n }\n ```\n\n - Start from the last right-moving robot (`le`) and the first left-moving robot (`ri`).\n - Compare positions and healths to determine the result of collisions.\n - Adjust health values or mark robots as removed (`health = 0`).\n\n7. **Collecting Survivors:**\n ```java\n int[][] res = new int[l + r][2];\n j = 0;\n\n for (i = 0; i < ri.length; i++) {\n res[j][0] = ri[i][1];\n res[j][1] = ri[i][2];\n j++;\n }\n for (i = 0; i < le.length; i++) {\n res[j][0] = le[i][1];\n res[j][1] = le[i][2];\n j++;\n }\n ```\n\n - Collect the health and original indices of surviving robots into `res`.\n\n8. **Sorting Survivors by Original Order:**\n ```java\n Arrays.sort(res, (a, b) -> Integer.compare(a[1], b[1]));\n\n for (i = 0; i < res.length; i++) {\n if (res[i][0] != 0) {\n ans.add(res[i][0]);\n }\n }\n ```\n\n - Sort `res` by original indices to maintain the input order.\n - Add the health of surviving robots to `ans` if they are still non-zero.\n\n9. **Return Result:**\n ```java\n return ans;\n ```\n\n - Return the list `ans` containing the health of the surviving robots in their original order.\n\n\n\n\n\n### Example\n\nGiven:\n- `positions = [3, 7, 2, 5]`\n- `healths = [4, 6, 8, 3]`\n- `directions = "RRLL"`\n\n#### Initial Setup\n\n1. **Initialize Variables:**\n - `n = 4` (number of robots)\n - `l = 2` (number of left-moving robots)\n - `r = 2` (number of right-moving robots)\n - `ans` will store the final health of surviving robots.\n\n2. **Separate Robots by Direction:**\n - Robots moving left (`L`):\n - `ri` (right-moving): `[[3, 4, 0], [7, 6, 1]]`\n - Robots moving right (`R`):\n - `le` (left-moving): `[[2, 8, 2], [5, 3, 3]]`\n\n#### Processing Collisions\n\n3. **Sort Robots by Position:**\n - Sorted `le` (left-moving):\n - `[[2, 8, 2], [5, 3, 3]]`\n - Sorted `ri` (right-moving):\n - `[[3, 4, 0], [7, 6, 1]]`\n\n4. **Collision Resolution:**\n\n - Start with the last robot in `le` and first in `ri`:\n - Compare positions: `2 (le)` < `3 (ri)`\n\n - Robots do not collide directly, so no changes in health.\n\n - Move to the next robot:\n - Compare positions: `5 (le)` > `3 (ri)`\n - Health comparison:\n - Health of `le` (8) > Health of `ri` (4)\n - Decrease health of `le` to 7 (since it lost in this collision).\n - `ri` health remains unchanged.\n\n - Continue with next robot:\n - Compare positions: `5 (le)` < `7 (ri)`\n - Health comparison:\n - Health of `le` (7) < Health of `ri` (6)\n - Decrease health of `ri` to 5 (since it lost in this collision).\n - `le` health remains unchanged.\n\n - Final state:\n - `le` (left-moving): `[[2, 7, 2], [5, 3, 3]]`\n - `ri` (right-moving): `[[3, 4, 0], [7, 5, 1]]`\n\n#### Collecting Survivors\n\n5. **Combine and Sort Survivors:**\n - Combine `le` and `ri` into `res` based on their indices.\n\n - Sorted `res` by original indices:\n - `[[4, 0], [5, 1], [7, 2], [3, 3]]`\n\n6. **Extract Final Healths:**\n - From `res`, collect health values where health is non-zero.\n\n - Final `ans`: `[4, 5, 7, 3]`\n\n#### Result\n\n- The final health of surviving robots, in the order they were originally given:\n - Robot 1: Health 4\n - Robot 2: Health 5\n - Robot 3: Health 7\n - Robot 4: Health 3\n\n\n\n### Complexity Analysis\n\n- **Time Complexity:** `O(n log n)`\n - Sorting the robots by position takes `O(n log n)`.\n - Processing collisions takes `O(n^2)` in the worst case, but due to the sorted nature and mutual exclusion during collisions, it\'s effectively `O(n log n)`.\n\n- **Space Complexity:** `O(n)`\n - The arrays and lists used to track the robots\' positions, healths, and indices require `O(n)` space.\n\n
3
0
['Array', 'Sorting', 'Simulation', 'Java']
0
robot-collisions
Hassle-free method..
hassle-free-method-by-nehasinghal032415-0t5s
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
NehaSinghal032415
NORMAL
2024-07-13T12:26:41.417521+00:00
2024-07-13T12:26:41.417553+00:00
87
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(2N) --->Where N is total number of robots....\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(2N) --->Where N is total number of robots....\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int len=directions.length();\n Integer array[]=new Integer[len];\n //list which stores the result.....\n List<Integer> list=new ArrayList<>();\n Stack<Integer> st=new Stack<>();\n for(int i=0;i<len;i++){\n array[i]=i;\n }\n //sorting positions with respect to index...\n Arrays.sort(array,new Comparator<Integer>(){\n public int compare(Integer a,Integer b){\n return positions[a]-positions[b];\n }\n });\n\n for(int index : array){\n if(directions.charAt(index)==\'R\'){\n st.push(index);\n }\n else{\n boolean alive=true;\n while(!st.isEmpty()){\n int p=st.peek();\n //case 1...\n if(directions.charAt(p)==\'L\'){\n alive=true;\n break;\n }\n //case 2....\n else if(healths[index]<healths[p]){\n alive=false;\n healths[index]=0;\n healths[p]-=1;\n break;\n }\n //case 3...\n else if(healths[index]>healths[p]){\n alive=true;\n healths[index]-=1;\n healths[st.peek()]=0;\n st.pop();\n }\n //case 4....\n else if(healths[index]==healths[st.peek()]){\n alive =false;\n healths[index]=healths[p]=0;\n st.pop();\n break;\n }\n }\n if(alive){\n st.push(index);\n }\n }\n }\n for(int i=0;i<len;i++){\n if(healths[i]!=0){\n list.add(healths[i]);\n }\n }\n return list;\n }\n}\n```
3
0
['Array', 'String', 'Stack', 'Sorting', 'Java']
1
robot-collisions
Using stack
using-stack-by-akshita_12-2oda
Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve this problem, we need to simulate the collisions between robots moving in oppo
akshita_12
NORMAL
2024-07-13T10:57:34.289486+00:00
2024-07-13T10:57:34.289530+00:00
30
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem, we need to simulate the collisions between robots moving in opposite directions. By sorting the robots based on their positions, we can manage their interactions using a stack to keep track of robots moving to the right. This allows us to handle collisions with robots moving to the left in a structured manner.\n```\n\nCOLLISION happens when :\nrobo1 robo2\n R L\n ---> <---\n\n\nNO COLLISION when :\nrobo1 robo2\n L R\n <--- --->\n```\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStep 1 : Struct Definition and Initialization:\nWe use an id variable because we have to return the healths array in the same order.\n```\n struct Robot{\n int id;\n int pos;\n int h;\n char dir;\n };\n```\nInitialize an array of these structs using the input vectors.\n```\n vector<Robot> arr(n);\n for(int i=0; i<n; i++){\n arr[i].id = i;\n arr[i].pos = positions[i];\n arr[i].h = healths[i];\n arr[i].dir = directions[i];\n }\n```\n\nStep 2: Sorting: Sort the robots based on their positions to process their movements in the correct order.\n```\n static bool comp(const Robot& robo1, const Robot& robo2) {\n return robo1.pos < robo2.pos;\n }\n```\n\nStep 3: Stack for Collision Management: We can use a stack to manage robots moving to the right (\'R\'). When encountering a robot moving to the left (\'L\'), check for collisions with robots on the stack.\n```\nrobo1 robo2 robo3 robo4\n R R L L\n ---> ---> <--- <---\n ind\n\n| | if it is a \'R\' push it with id\n| | if it is a \'L\' do the required\n| {robo2, R} | collisions health updation\n| {robo1, R} |\n|__________________|\n stack\n```\n\nStep 4: Collision Logic: For each collision, compare the health of the robots. The robot with lower health is removed, and the health of the surviving robot is decremented. If both have the same health, both are removed.\n\nStep 5: Collect Surviving Robots\' Health: After processing all robots, collect the health values of the surviving robots and return them.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn) due to sorting, O(n) for traversal and we\'re using a while loop for collision management so overall complexity in the worst case = O(n2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n struct Robot{\n int id;\n int pos;\n int h;\n int dir;\n };\n static bool comp(const Robot& robo1, const Robot& robo2) {\n return robo1.pos < robo2.pos;\n }\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n = positions.size();\n vector<Robot> arr(n);\n for(int i=0; i<n; i++){\n arr[i].id = i;\n arr[i].pos = positions[i];\n arr[i].h = healths[i];\n arr[i].dir = directions[i];\n }\n\n sort(arr.begin(), arr.end(), comp);\n \n\n\n stack<pair<int, int>> st;\n for(int i=0; i<n; i++){\n\n if(arr[i].dir == \'R\') st.push({arr[i].id, \'R\'});\n\n else if(arr[i].dir == \'L\'){\n while(!st.empty() && st.top().second==\'R\'){\n\n int prevId = st.top().first;\n int curId = arr[i].id;\n int prevh = healths[prevId];\n int curh = arr[i].h;\n\n if(prevh > curh){\n healths[prevId]--;\n healths[curId] = 0;\n arr[i].h=0;\n break;\n }\n else if(prevh < curh){\n st.pop();\n healths[prevId] = 0;\n healths[curId]--;\n arr[i].h--;\n }\n else{\n st.pop();\n healths[prevId] = 0;\n healths[curId] = 0;\n arr[i].h=0;\n break;\n }\n }\n }\n }\n\n\n vector<int> ans;\n for(int i=0; i<n; i++)\n if(healths[i] != 0) ans.push_back(healths[i]);\n return ans;\n }\n};\n\n\n \n```
3
0
['C++']
0
robot-collisions
Easiest explanation on leetcode(completely brute force && Totally explained)
easiest-explanation-on-leetcodecompletel-2n4y
Intuition\n1.so the question robots collide when the faces of robot are toward each other means (-> <-) \n2.so we have to keep track of theh faces and keep note
Ajay-Adhikari
NORMAL
2024-07-13T04:59:21.765028+00:00
2024-07-13T04:59:21.765063+00:00
375
false
# Intuition\n1.so the question robots collide when the faces of robot are toward each other means (-> <-) \n2.so we have to keep track of theh faces and keep note that we have to return our result as in the order of input is given \n3. we have to take care when robot is left facing then chechk the previous robot face .\n4. chances of collde is only one when the face is left and previous robot is right faced.\n5. TO remove the robot just use stack as it is easy to erase robot from line.\n6. Also keep track if score of robot(left faced ) is greater then previous robot which is right faced then remove the previous all robot having right faced that stand contigously and also reduce the score of robot when removing previous robot \n7. ex: assume arrows as a robot with their score\n7. <-(10),<-9,<-8,->,->(21) , ->(22) ,->(21),<-(47)\n8. here 47 scored robot with left pop out all the robot having right faced having less score and 47will reduced by 3and becomes 44 \n9. <-(10),<-9,<-8,->,->(21) , <-(44) \n10. edge case if previous robot is of same score \n11. edge case if previous robot having more score then remove that (->(44) robot just for example)\n\n\nBAS ITNI CHEEJE HI DEKHNI H\n\n\n# Approach\n1.Use stack and follow the above steps and yes make ordered map that represent line in sorted manner of robot with their score and health see code \n\n2. also make stack which contains all thing health , directions and position because position will help at last when we have to return our answer in input order . see code \n3. Now run a for loop to iterate map or in simple term to run in a line and keep track which robot is coming and which direction it will face \n4. if it is left face then chechk that previous robot is of right then start poping but careful keep track of score also .\n5. just see code and you will understand\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n=positions.size();\n map<int , pair<int , char>> mp;\n for(int i=0;i<n;i++)\n {\n mp[positions[i]].first=healths[i];\n mp[positions[i]].second=directions[i];\n }\n stack<pair<int , pair<int , char>>> st;\n for(auto it:mp)\n {\n if(!st.empty() && it.second.second==\'L\')\n {\n\n if(st.top().second.second==\'R\')\n {\n if(it.second.first<st.top().second.first)\n {\n st.top().second.first-=1;\n continue;\n }\n else if(st.top().second.first<it.second.first)\n {\n while(!st.empty() && it.second.first>st.top().second.first &&st.top().second.second==\'R\' )\n {\n it.second.first-=1;\n st.pop();\n }\n if(!st.empty() && it.second.first==st.top().second.first && st.top().second.second==\'R\')\n {\n st.pop();\n continue;\n }\n if(!st.empty() && it.second.first<st.top().second.first && st.top().second.second==\'R\' )\n {\n st.top().second.first-=1;\n continue;\n }\n \n }\n else\n {\n st.pop();\n continue;\n }\n } \n }\n st.push(it);\n }\n vector<int> res;\n unordered_map<int , int> mp1;\n while(!st.empty())\n {\n mp1[st.top().first]=st.top().second.first;\n st.pop();\n }\n for(int i=0;i<n;i++)\n {\n if(mp1.find(positions[i])!=mp1.end())\n {\n res.push_back(mp1[positions[i]]);\n }\n }\n\n \n return res;\n \n \n }\n};\n```
3
0
['C++']
6
robot-collisions
🌟💫Best Easy understandable Python3 solution 🌟🌟❤️‍🔥❤️‍🔥🔥🔥Explained by line...!!
best-easy-understandable-python3-solutio-1b5r
Intuition\n Describe your first thoughts on how to solve this problem. \nThe main idea is to simulate the robot collisions based on their positions and directio
A206k
NORMAL
2024-07-13T04:11:09.070246+00:00
2024-07-13T04:11:09.070267+00:00
204
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe main idea is to simulate the robot collisions based on their positions and directions. By using a stack, we can efficiently handle the robots moving to the right and the left, and resolve their interactions accordingly.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Sort Robots by Position**: We sort the robots based on their positions to ensure we handle collisions in the correct order.\n2. **Stack for Right-moving Robots**: Use a stack to keep track of the indices of robots moving to the right.\n3. **Collision Handling**: For each robot moving to the left:\n - Check for collisions with the robots in the stack (those moving to the right).\n - If the current robot has higher health, reduce its health by 1 and destroy the robot on the stack.\n - If both robots have equal health, destroy both.\n - If the current robot has lower health, destroy it and reduce the health of the robot on the stack.\n4. **Return Surviving Robots**: After processing all collisions, return the healths of the surviving robots.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(nlogn) due to the sorting step. The collision handling is done in linear time \n\uD835\uDC42(\uD835\uDC5B), so the overall complexity is dominated by the sorting step.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n) due to the extra space used by the stack and the list of robot indices.\n# Explanation of the code:\n\n1. Sorting Robots by Position: The robots are sorted by their positions to handle collisions in order of their spatial arrangement.\n\n2. Handling Robots Moving to the Right: Robots moving to the right are pushed onto a stack.\n3. Handling Robots Moving to the Left: Robots moving to the left collide with those on the stack:\n\n --->If the current robot\'s health is greater, it continues after reducing its health and destroying the robot on the stack.\n\n --->If the current robot\'s health is equal to the robot on the stack, both are destroyed.\n\n ---->If the current robot\'s health is less, it is destroyed after reducing the health of the robot on the stack.\n4. Returning Surviving Robots: The healths of robots that are not destroyed (health > 0) are returned.\n# Code\n```\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n stack = []\n # Sort the indices of robots based on their positions\n for i in sorted(range(len(positions)), key=lambda i: positions[i]):\n # If the robot is moving to the right, add its index to the stack\n if directions[i] == \'R\':\n stack.append(i)\n else:\n # Process collisions with robots in the stack\n while stack and healths[stack[-1]] < healths[i]:\n # The current robot loses 1 health point\n healths[i] -= 1\n # The robot in the stack is destroyed\n healths[stack.pop()] = 0\n if stack:\n if healths[stack[-1]] == healths[i]:\n # Both robots are destroyed if their healths are equal\n healths[stack.pop()] = 0\n else:\n # The robot in the stack loses 1 health point\n healths[stack[-1]] -= 1\n # The current robot is destroyed\n healths[i] = 0\n # Return the healths of robots that survived\n return [h for h in healths if h]\n \n```
3
0
['Stack', 'Sorting', 'Simulation', 'Python3']
1
robot-collisions
Swift | Stack and Simulation
swift-stack-and-simulation-by-pagafan7as-j12a
Code\n\nclass Solution {\n func survivedRobotsHealths(_ positions: [Int], _ healths: [Int], _ directions: String) -> [Int] {\n var stack = [Int]()\n
pagafan7as
NORMAL
2024-07-13T01:38:44.428807+00:00
2024-07-13T05:07:42.618142+00:00
52
false
# Code\n```\nclass Solution {\n func survivedRobotsHealths(_ positions: [Int], _ healths: [Int], _ directions: String) -> [Int] {\n var stack = [Int]()\n let directions = Array(directions)\n var healths = healths\n\n // Sort robots by increasing position.\n var robots = positions.indices.sorted { positions[$0] < positions[$1] }\n\n // Place each robot on the stack and see if it collides against any\n // of the robots already on the stack.\n for robot in robots {\n stack.append(robot)\n\n // If the top 2 robots on the stack are moving towards each other, resolve their collision.\n while stack.suffix(2).map { directions[$0] } == ["R", "L"] {\n let lastRobots = [stack.removeLast(), stack.removeLast()]\n\n // Compute the new healths of the 2 robots after the collision, and if a\n // robot survives, re-add it to the stack.\n let minHealth = lastRobots.map { healths[$0] }.min()!\n for robot in lastRobots {\n healths[robot] = healths[robot] > minHealth ? healths[robot] - 1 : 0\n if healths[robot] > 0 { stack.append(robot) }\n }\n }\n }\n\n return healths.filter { $0 > 0 }\n }\n}\n```
3
0
['Swift']
2
robot-collisions
[Go] Stack
go-stack-by-joeblack5451-p8qn
Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\nfunc survivedRobotsHealths(positions []int, healths []int, directions string)
joeblack5451
NORMAL
2024-07-13T00:54:50.943436+00:00
2024-07-13T00:54:50.943468+00:00
184
false
# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nfunc survivedRobotsHealths(positions []int, healths []int, directions string) []int {\n robots := make(map[int][]int)\n for i, position := range positions {\n direction := 1\n if directions[i] == \'L\' { direction = -1 }\n robots[position] = []int{healths[i], direction, i}\n }\n\n sortedPositions := append([]int{}, positions...)\n sort.Ints(sortedPositions)\n stack := [][]int{}\n for _, position := range sortedPositions {\n stack = append(stack, robots[position])\n i := len(stack) - 1\n for i - 1 >= 0 && stack[i][1] == -1 && stack[i-1][1] == 1 {\n right := stack[i-1]\n left := stack[i]\n survive := []int{}\n stack = stack[:i-1]\n if left[0] > right[0] {\n survive = left\n } else if left[0] < right[0] {\n survive = right\n } else {\n i-=2\n continue\n }\n survive[0]--\n stack = append(stack, survive)\n i--\n }\n }\n\n sort.Slice(stack, func(i, j int) bool {\n\t\treturn stack[i][2] < stack[j][2]\n\t})\n\n result := []int{}\n for _, robot := range stack {\n result = append(result, robot[0])\n }\n return result\n}\n\n```
3
0
['Stack', 'Go']
0
robot-collisions
Intuitive Solution, Faster than 100%
intuitive-solution-faster-than-100-by-ni-w5i8
Intuition\n Describe your first thoughts on how to solve this problem. \nAfter reading the problem, I thought it was very similar to the Aestroid Collision Prob
nikhilpujar23
NORMAL
2023-06-25T04:34:46.606637+00:00
2023-06-25T04:34:46.606662+00:00
331
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAfter reading the problem, I thought it was very similar to the Aestroid Collision Problem.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Steps:**\n1. Convert the question into Aestroid Collision. In that question, the order of the aestroids was from left to right. We can achieve that in this question too by simply creating a new vector v which has (position,health,direction). Then we sort this v according to position.\n2. The only changes made to the Aestroid Collision solution is how to decrease the health of the robot after a collision. There are two cases when we have to do so:\na. if the current robot is moving to the left and its value is greater than the robot on top of the stack. Decrease the health of the left moving robot by 1 and pop the robot from the top of the stack.If stack becomes empty, push the cur robot onto the stack.\nb. if current robot was moving to the left and we encounter another robot moving to the right on top of the tack, but the robot on top of the stack has a grerater health. In this case, decrease health of the element on top of the stack and dont push the current robot onto the stack.\n3.Now the last step is to arrange the elements in the same order of their positions in the orignal array. This can be done using a map.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n 2 iterations of the input vector so O(n) \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n) for the additional vector, stack and map.\n# Code\n```\nclass Solution {\npublic:\n static bool comp(vector<int>&a,vector<int>&b){\n return a[0]<b[0];\n }\n vector<int> survivedRobotsHealths(vector<int>& pos, vector<int>& heal, string dir) {\n int n=dir.size();\n \n vector<vector<int>>v(n);\n for(int i=0;i<n;i++){\n v[i]={pos[i],heal[i],dir[i]==\'R\'};\n }\n // dir R means 1\n sort(v.begin(),v.end(),comp);\n stack<vector<int>>st;\n for(auto it:v){\n if(it[2]==1 || st.empty()){\n st.push(it);\n }else{\n while(!st.empty() && st.top()[2]==1 && st.top()[1]<it[1]){st.pop();it[1]--;}\n \n if(!st.empty() && st.top()[2]==1 && st.top()[1]==it[1]){st.pop();}\n \n else if(st.empty() || st.top()[2]==0){st.push(it);}\n else if(!st.empty()){st.top()[1]--;}\n \n }\n }\n vector<int>ans(n,-1);\n map<int,int>m;\n \n for(int i=0;i<pos.size();i++){\n m[pos[i]]=i;\n }\n while(!st.empty()){\n ans[m[st.top()[0]]]=st.top()[1];\n st.pop();\n }\n vector<int>final;\n for(auto it:ans){\n if(it!=-1)final.push_back(it);\n } \n return final;\n \n }\n};\n```
3
0
['Stack', 'Greedy', 'Monotonic Stack', 'C++']
1
robot-collisions
java solution using stack and sorting
java-solution-using-stack-and-sorting-by-uu1w
\nclass Solution {\n class Pair{\n int p;\n int h;\n char d;\n int idx;\n Pair(int p,int h,char d,int i){\n thi
akash0228
NORMAL
2023-06-25T04:07:42.879792+00:00
2023-06-25T04:07:42.879814+00:00
346
false
```\nclass Solution {\n class Pair{\n int p;\n int h;\n char d;\n int idx;\n Pair(int p,int h,char d,int i){\n this.p=p;\n this.h=h;\n this.d=d;\n this.idx=i;\n }\n }\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n=positions.length;\n List<Pair> list=new ArrayList<>();\n \n for(int i=0;i<n;i++){\n list.add(new Pair(positions[i],healths[i],directions.charAt(i),i));\n }\n \n Collections.sort(list,(a,b)->a.p-b.p);\n \n List<int[]> ans=new ArrayList<>();\n Stack<int[]> q=new Stack<>();\n \n for(int i=0;i<n;i++){\n Pair curr=list.get(i);\n if(curr.d==\'R\'){\n q.add(new int[]{curr.h,curr.idx});\n continue;\n }\n else{\n boolean flag=false;\n int health=curr.h;\n \n while(!q.isEmpty() && health!=0){\n int top[]=q.pop();\n int last=top[0];\n int idx=top[1];\n \n if(last<health){\n health-=1;\n }else if(last==health){\n health=0;\n break;\n }\n else{\n last-=1;\n health=0;\n q.add(new int[]{last,idx});\n \n }\n }\n \n if(health!=0)\n ans.add(new int[]{health,curr.idx});\n }\n }\n \n while(!q.isEmpty()){\n ans.add(q.pop());\n }\n \n Collections.sort(ans,(a,b)->a[1]-b[1]);\n \n List<Integer> result=new ArrayList<>();\n \n for(int i=0;i<ans.size();i++){\n result.add(ans.get(i)[0]);\n }\n \n return result;\n }\n}\n```
3
0
['Stack', 'Sorting', 'Java']
1
robot-collisions
Easy C++ solution || Stack
easy-c-solution-stack-by-ankitkr23-7cox
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vecto
ankitkr23
NORMAL
2023-06-25T04:03:26.342828+00:00
2023-06-25T04:06:36.042680+00:00
207
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<pair<int, int>>v;\n int n=positions.size();\n for(int i=0; i<n; i++){\n v.push_back({positions[i], i});\n }\n sort(v.begin(), v.end());\n stack<pair<int, int>> st;\n st.push(v[0]);\n for(int i=1; i<v.size(); i++){\n int flag=1;\n int curpos=v[i].first;\n int ind=v[i].second;\n while(st.size()!=0 && directions[st.top().second]==\'R\' && directions[ind]==\'L\' && flag==1){\n pair<int, int> p=st.top();\n int pos=p.first;\n if(healths[p.second]==healths[ind]){\n st.pop();\n flag=0;\n }\n else if(healths[p.second]>healths[ind]){\n flag=0;\n healths[p.second]-=1;\n }\n else if(healths[ind]>healths[p.second]){\n st.pop();\n healths[ind]-=1;\n }\n }\n if(flag==1)st.push({curpos, ind});\n }\n map<pair<int, int>, int>mp;\n while(st.size()!=0){\n mp[st.top()]++;\n st.pop();\n }\n vector<int> ans;\n for(int i=0; i<n; i++){\n if(mp.count({positions[i], i})>0){\n ans.push_back(healths[i]);\n }\n }\n return ans;\n }\n};\n```
3
0
['C++']
1
robot-collisions
Java (nlogn) Solution using Deque
java-nlogn-solution-using-deque-by-shash-d96c
Approach:\n- Create an 2d list with all valued combined and also maintain the index in original array\n- Sort the list based on position\n- Start from index 0,
shashankbhat
NORMAL
2023-06-25T04:02:48.303378+00:00
2023-06-25T04:08:29.734968+00:00
167
false
# Approach:\n- Create an 2d list with all valued combined and also maintain the index in original array\n- Sort the list based on position\n- Start from index 0, and check for each robot.\n - For first robot, insert into deque\n - For other robots, if direction is left, check in loop for last elements in deque for any collisions. If collision is detected then if current robot health is greater, remove last robot from deque and decrease current robot health and vice versa\n - Finally sort the remaining robots in deque based on index in original array\n\n# Code\n```\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n ArrayList<ArrayList<Integer>> combined = new ArrayList<>();\n \n int n = positions.length;\n for(int i=0; i<n; i++) {\n ArrayList<Integer> temp = new ArrayList<>();\n temp.add(positions[i]);\n temp.add(healths[i]);\n temp.add(directions.charAt(i) == \'R\' ? 1 : -1);\n temp.add(i);\n combined.add(temp);\n }\n \n Collections.sort(combined, new Comparator<ArrayList<Integer>>() {\n public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {\n return o1.get(0).compareTo(o2.get(0));\n }\n });\n \n List<Integer> result = new ArrayList<>();\n int i=0;\n int j=0;\n Deque<ArrayList<Integer>> deque = new ArrayDeque<>();\n\n while(j < n) {\n if(j == 0) {\n deque.addLast(combined.get(j));\n } else {\n ArrayList<Integer> current = combined.get(j);\n int currHealth = current.get(1);\n if(current.get(2) == -1) {\n while(!deque.isEmpty() && deque.peekLast().get(2) == 1) {\n ArrayList<Integer> prev1 = deque.peekLast();\n if(deque.peekLast().get(1) < currHealth) {\n currHealth--;\n deque.removeLast();\n } else if(deque.peekLast().get(1) > currHealth) {\n ArrayList<Integer> prev = deque.pollLast();\n prev.set(1, prev.get(1) - 1);\n currHealth = 0;\n deque.addLast(prev);\n break;\n } else {\n deque.removeLast();\n currHealth = 0;\n break;\n }\n }\n\n if(currHealth > 0) {\n current.set(1, currHealth);\n deque.addLast(current);\n }\n } else {\n deque.addLast(current);\n }\n }\n j++;\n }\n \n ArrayList<ArrayList<Integer>> temp = new ArrayList<>();\n for(ArrayList<Integer> arr : deque)\n temp.add(arr);\n \n Collections.sort(temp, new Comparator<ArrayList<Integer>>() {\n public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {\n return o1.get(3).compareTo(o2.get(3));\n }\n });\n \n for(ArrayList<Integer> arr : temp) {\n result.add(arr.get(1));\n }\n \n return result;\n }\n}\n```
3
0
['Array', 'Java']
1
robot-collisions
Priority Queue || Intuitive Soln || Easy Explanation || C++
priority-queue-intuitive-soln-easy-expla-98jz
Intuition\nWe divide all the robots into two types namely -\n\n1. Robots Going Left (save them all in a set)\n2. Robots going right( put them all in a priority
prasoonrajpoot
NORMAL
2023-06-25T04:01:36.978202+00:00
2023-06-25T04:11:24.526705+00:00
331
false
# Intuition\nWe divide all the robots into two types namely -\n\n1. Robots Going Left (save them all in a set)\n2. Robots going right( put them all in a priority queue)\n\n# Approach\nAs we can see both of them as ordered containers means sorted in some manner\n\nnow when comparing these two structure simultaneously we have this kind of structure.\n\nL LL. L. L\n\n R R R R\n\nnow as we can see the last R will not collide with anybody, but how would we know this in code ??\uD83E\uDDD1\u200D\uD83D\uDCBB\n\nFor that we will take the rightmost element( top of priority Queue) get its x coordinate, and binary search upon the L set, or the elements going left, \n\nThrough binary search or specifically lower bound we will always get the robot which is right or at the same position to the position we are at in priority queue. \n\nThen after that it\'s a matter of simple comparison.\n\nWe eighter Pop from the queue or we erase from the set depending on the values\n\n\nPlease Upvote if you liked my approach, and do let me know if in comments if you require further explainations.\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<pair<int,int>> answer;\n priority_queue<pair<int, pair<int,int> >> r;\n set<pair<int, pair<int,int> >> l;\n \n \n for(int i = 0; i < directions.size(); i++){\n if(directions[i] == \'L\'){\n l.insert({positions[i], {healths[i], i}});\n }else{\n r.push({positions[i], {healths[i], i}});\n }\n }\n \n \n while(r.size()){\n int pos = r.top().first, h = r.top().second.first, idx = r.top().second.second;\n r.pop();\n \n auto ptr = l.lower_bound({pos, {0, 0}});\n \n if(ptr == l.end()){\n answer.push_back({idx, h});\n continue;\n }\n \n int x = ptr->second.first;\n int id = ptr->second.second;\n \n if(h > x){\n l.erase(ptr);\n r.push({pos, {h -1, idx}});\n continue;\n }else if( x > h){\n l.erase(ptr);\n l.insert({pos, {x- 1, id} });\n continue;\n }else{\n l.erase(ptr);\n }\n }\n \n \n \n for(auto i : l){\n answer.push_back({i.second.second, i.second.first});\n }\n sort(answer.begin(), answer.end());\n \n \n vector<int> temp;\n for(auto i : answer){\n temp.push_back(i.second);\n }\n return temp;\n }\n};\n```
3
0
['C++']
1
robot-collisions
🔥Stack-Based Solution: Sort, keeping track of index (C++). Beats: 70% ✅ Runtime 60% ✅ memory🔥
stack-based-solution-sort-keeping-track-hu75f
\n\n# Intuition\nThe problem requires finding the remaining robot healts after collitions. The main key here is that a collision can occur only if right followe
Sithaarth_Maheshwaran
NORMAL
2024-07-14T14:09:10.878200+00:00
2024-07-14T15:28:18.967186+00:00
8
false
![Screenshot 2024-07-14 192732.png](https://assets.leetcode.com/users/images/b8e6986e-679a-4d2a-9278-74fb318bb34e_1720966804.1031845.png)\n\n# Intuition\nThe problem requires finding the remaining robot healts after collitions. The main key here is that a collision can occur only if right followed by left moving robots. We can maintain a stack to handle the collitions and remaining robots. \n\n# Approach\n1. **Sort the Robots by Position:** First, sort the robots based on their positions. This allows us to process the robots in the order they would encounter each other on the line.\n\n2. **Use a Stack to Track Collisions:** Use a stack to manage the robots and handle collisions. When a right-moving robot meets a left-moving robot, they may collide. Depending on their health, one or both robots may be removed from the line. Remember, a left moving robot can collide with more than one right moving robot as long as it has higher health. So updating the stack requires looping through past robots while traversing.\n\n3. **Update Health After Collision:** If two robots collide, the robot with lower health is removed, and the other robot\'s health decreases by one. If both have the same health, both are removed.\n\n4. **Store the Results:** After processing all robots, collect the health of the surviving robots remained in the stack in the order they were given in the input.\n\n# Complexity\n- Time complexity: $$O(nlogn)$$ \n\n\n- Space complexity: $$O(n)$$\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<pair<int,int>> robots; //stores each robot\'s position and initial index\n stack<pair<pair<int,char>,int>> stk; //stores each robot\'s health,direction and initial index\n int n = positions.size();\n for(int i = 0;i<n;i++) robots.push_back({positions[i],i});\n sort(robots.begin(),robots.end());\n vector<int> initialPosition(n,0);\n //initially push the robot in 1st position\n stk.push({{healths[robots[0].second],directions[robots[0].second]},robots[0].second});\n int i ;\n //loop from the 2nd position\n for(i = 1;i<n;i++){\n pair<int,int> r = robots[i]; //current robot\n if(!stk.empty() && stk.top().first.second==\'R\' && directions[r.second] == \'L\'){\n char d = directions[r.second];\n int h = healths[r.second];\n bool f = true;\n //loop until robot on top of stack exceeds current robot in health\n while(!stk.empty() && stk.top().first.second == \'R\'){\n int t = stk.top().first.first;\n int ind = stk.top().second;\n stk.pop();\n if(t == h){\n f = false;\n break;\n }\n if(t < h){\n //decrease the health of current robot\n h--;\n }\n else{\n f = false;\n //push the top robot back into the stack\n stk.push({{t-1,\'R\'},ind});\n break;\n }\n }\n //push the updated health of current robot if not destroyed\n if(f) stk.push({{h,d},r.second});\n\n }\n else stk.push({{healths[r.second],directions[r.second]},r.second});\n }\n //place the remained robots in a position vector\n while(!stk.empty()){\n initialPosition[stk.top().second] = stk.top().first.first;\n stk.pop();\n }\n vector<int> res;\n //store the ordered robots in final result\n for(auto& r : initialPosition){\n if(r) res.push_back(r);\n }\n \n return res;\n }\n};\n```\n**Note:** One thing to note in my solution is that I used two result vectors to get the remaining healths...Thats quite inefficient. Let me know in the comments if you got any better approach...\n\n**UPVOTE WOULD BE VERY MUCH APPRICIATED \uD83D\uDE01 THANKS FOR YOUR TIME**\n\n\n
2
0
['Stack', 'Sorting', 'C++']
1
robot-collisions
SUPER EASY 💪🔥✨
super-easy-by-codewithsparsh-68l8
Intuition\nTo solve this problem, we need to simulate the movements and collisions of robots on a line. The key is to handle the collisions efficiently, ensurin
CodeWithSparsh
NORMAL
2024-07-14T05:08:28.309623+00:00
2024-07-14T05:08:28.309651+00:00
8
false
# Intuition\nTo solve this problem, we need to simulate the movements and collisions of robots on a line. The key is to handle the collisions efficiently, ensuring that we update the health of robots correctly and determine the survivors after all possible collisions have occurred.\n\n# Approach\n1. **Representation**: Represent each robot as a tuple containing its position, health, direction, and original index.\n2. **Sorting**: Sort the robots by their positions to simulate their movements correctly.\n3. **Stack for Collisions**: Use a stack to process the collisions. Push robots moving to the right onto the stack. When encountering a robot moving left, process any potential collisions with the robots in the stack.\n4. **Collision Handling**: \n - If the health of the left-moving robot is greater, reduce its health and remove the right-moving robot from the stack.\n - If the health of the right-moving robot is greater, reduce its health and continue with the next robot.\n - If both robots have the same health, remove both from the stack.\n5. **Collect Survivors**: After processing all robots, the remaining robots in the stack are the survivors.\n6. **Result**: Return the health of the surviving robots in the order they were given in the input.\n\n# Complexity\n- **Time complexity**: \\(O(n \\log n)\\) for sorting the robots by position, and \\(O(n)\\) for processing the collisions, giving a total of \\(O(n \\log n)\\).\n- **Space complexity**: \\(O(n)\\) for storing the robots and using the stack.\n\n# Code\n```java\nclass Solution {\n public List<Integer> survivedRobotsHealths(List<Integer> positions, List<Integer> healths, String directions) {\n int n = positions.size();\n List<Integer> survivors = new ArrayList<>();\n List<Integer> survivorIndexes = new ArrayList<>();\n \n // Create a list of tuples (position, health, direction, index)\n List<List<Object>> robots = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n robots.add(Arrays.asList(positions.get(i), healths.get(i), directions.charAt(i), i));\n }\n \n // Sort the robots by their positions\n robots.sort((a, b) -> Integer.compare((int) a.get(0), (int) b.get(0)));\n \n // Use a stack to process the collisions\n Stack<List<Object>> stack = new Stack<>();\n \n for (var robot : robots) {\n if (robot.get(2).equals(\'R\')) {\n stack.push(robot); // push the robot moving right to the stack\n } else {\n // Process collisions\n while (!stack.isEmpty() && stack.peek().get(2).equals(\'R\') && (int) stack.peek().get(1) < (int) robot.get(1)) {\n var collidedRobot = stack.pop();\n robot.set(1, (int) robot.get(1) - 1); // reduce health of current left-moving robot\n }\n if (!stack.isEmpty() && stack.peek().get(2).equals(\'R\')) {\n if (stack.peek().get(1).equals(robot.get(1))) {\n stack.pop(); // both robots are destroyed\n } else {\n stack.peek().set(1, (int) stack.peek().get(1) - 1); // reduce health of the right-moving robot\n }\n } else {\n survivors.add((int) robot.get(1)); // current robot survived\n survivorIndexes.add((int) robot.get(3)); // keep the original index\n }\n }\n }\n \n // Add remaining right-moving robots to survivors\n for (var robot : stack) {\n survivors.add((int) robot.get(1));\n survivorIndexes.add((int) robot.get(3));\n }\n \n // Sort the survivors by their original indexes\n List<Integer> result = new ArrayList<>(Collections.nCopies(n, 0));\n for (int i = 0; i < survivors.size(); i++) {\n result.set(survivorIndexes.get(i), survivors.get(i));\n }\n \n return result.stream().filter(health -> health != 0).collect(Collectors.toList());\n }\n}\n```\n\nThis code efficiently handles the movements and collisions of robots and returns the health of the surviving robots in the correct order.
2
1
['Dart']
0
robot-collisions
Python Solution Beats 28% 🥶🥶🥶🔥🔥
python-solution-beats-28-by-snah0902-aewq
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
snah0902
NORMAL
2024-07-14T01:23:06.451858+00:00
2024-07-14T01:23:06.451886+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n rightRobots = []\n leftRobots = []\n robotInformations = list(zip(enumerate(positions), healths, directions))\n robotInformations.sort(key=lambda x: x[0][1])\n for (originalIndex, position), health, direction in robotInformations:\n if direction == \'R\':\n rightRobots.append((health, originalIndex))\n else:\n didLeftRobotBreak = False\n while len(rightRobots) > 0:\n rightRobotHealth, rightOriginalIndex = rightRobots[-1]\n if rightRobotHealth == health:\n rightRobots.pop()\n didLeftRobotBreak = True\n break\n elif rightRobotHealth < health:\n rightRobots.pop()\n health -= 1\n else:\n rightRobots[-1] = rightRobotHealth - 1, rightOriginalIndex\n break\n if len(rightRobots) == 0 and not didLeftRobotBreak:\n leftRobots.append((health, originalIndex))\n mergedLeftAndRights = leftRobots + rightRobots\n mergedLeftAndRights.sort(key= lambda x: x[1])\n return list(map(lambda x: x[0], mergedLeftAndRights))\n```
2
0
['Python3']
1
robot-collisions
Python3 || 2 class solution || O(n log n)
python3-2-class-solution-on-log-n-by-fol-0mku
Approach\nCreate class Robot for storing robots with their characteristics. Use array robots_init to store initial positions of robots for answer. Use stack: if
followvinya
NORMAL
2024-07-13T20:28:27.827723+00:00
2024-07-13T20:29:58.336759+00:00
15
false
# Approach\nCreate class Robot for storing robots with their characteristics. Use array robots_init to store initial positions of robots for answer. Use stack: if current element is bigger than previous -> pop previous and continue checking in while cycle until previous element will be of same direction or stack ends; elif current is smaller than previous -> then just ignore it; else(equal) -> pop previous, ignore current. Update health parameter of each robot. In the end return healths of all robots in initial array(bc they are stored with initial positions there) if they are >0 (exist).\n\n# Complexity\n- Time complexity: O(n log n) because of sorting\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Robot:\n def __init__(self, position, health, direction):\n self.position = position\n self.health = health\n self.direction = direction\n\n\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n st = [] #for collisions checking\n robots_init = [] #initial list of robots to return it in the end \n for i in range(len(positions)):\n robots_init.append(Robot(positions[i], healths[i], directions[i]))\n robots = sorted(robots_init, key=lambda elem: elem.position)\n #we have list of Robot objects, sorted by position\n \n for elem in robots:\n if len(st) == 0 or elem.direction == \'R\':\n st.append(elem)\n else:\n while st and st[-1].direction == \'R\':\n if elem.health > st[-1].health:\n st[-1].health = 0\n st.pop()\n elem.health -= 1\n elif elem.health < st[-1].health:\n st[-1].health -= 1\n elem.health = 0\n break\n else:\n elem.health = 0\n st[-1].health = 0\n st.pop()\n break\n else:\n st.append(elem)\n\n return [elem.health for elem in robots_init if elem.health > 0]\n\n\n\n```
2
0
['Python3']
0
robot-collisions
🔥🔥Beats 95.80% 🔥🔥| Easy to understand C++ solution ✅✅ | Stack + Simulation ✅✅
beats-9580-easy-to-understand-c-solution-z7gj
\n\n---\n\n# Intuition\nThe problem requires simulating the movement and collision of robots moving in opposite directions on a line. The key insight is to effi
its_kartike
NORMAL
2024-07-13T19:44:56.163656+00:00
2024-07-13T19:44:56.163680+00:00
5
false
![image.png](https://assets.leetcode.com/users/images/89269bee-5130-4b5c-a50d-4cc4213133bb_1720898892.6253111.png)\n\n---\n\n# Intuition\nThe problem requires simulating the movement and collision of robots moving in opposite directions on a line. The key insight is to efficiently handle the collision of robots and determine the remaining health of the robots after all collisions are resolved.\n\n# Approach\n1. **Combine and Sort**: Combine the positions, healths, and directions into a single vector and sort it based on positions. This allows us to process robots in the order of their positions.\n2. **Use a Stack**: Use a stack to keep track of robots moving to the right (`\'R\'`). As we iterate through the sorted robots:\n - If a robot is moving to the right, push it onto the stack.\n - If a robot is moving to the left, check for collisions with robots on the stack (which are moving to the right). Resolve the collisions by comparing healths and updating/removing robots accordingly.\n3. **Track Remaining Health**: Use an unordered map to store the health of the remaining robots.\n4. **Construct Result**: After processing all robots, construct the result based on the initial order of the positions.\n\n# Complexity\n- **Time complexity**: \\(O(n*log(n)\\) due to sorting, where \\(n\\) is the number of robots.\n- **Space complexity**: \\(O(n)\\) for storing robots in the vector, stack, and unordered map.\n\n---\n# Code\n```cpp\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n\n int n = positions.size();\n if (n == 1) return healths;\n\n vector<pair<int, pair<int, char>>> vec;\n for (int i = 0; i < n; i++) {\n vec.push_back({positions[i], {healths[i], directions[i]}});\n }\n sort(vec.begin(), vec.end());\n\n stack<pair<int, pair<int, char>>> st;\n unordered_map<int, int> remainingHealth;\n for (int i = 0; i < n; i++) {\n int pos = vec[i].first;\n int heal = vec[i].second.first;\n char dir = vec[i].second.second;\n\n if (dir == \'R\') {\n st.push(vec[i]);\n } else {\n while (!st.empty() && st.top().second.second == \'R\') {\n auto [pos2, hp_dir2] = st.top();\n int heal2 = hp_dir2.first;\n st.pop();\n\n if (heal2 > heal) {\n st.push({pos2, {heal2 - 1, \'R\'}});\n heal = 0; // this robot is destroyed\n break;\n } else if (heal2 < heal) {\n heal--;\n } else {\n heal = 0; // both robots are destroyed\n break;\n }\n }\n if (heal > 0) {\n remainingHealth[pos] = heal;\n }\n }\n }\n\n while (!st.empty()) {\n auto [pos, hp_dir] = st.top();\n st.pop();\n remainingHealth[pos] = hp_dir.first;\n }\n\n vector<int> result;\n for (int i = 0; i < n; i++) {\n if (remainingHealth.find(positions[i]) != remainingHealth.end()) {\n result.push_back(remainingHealth[positions[i]]);\n }\n }\n\n return result;\n }\n};\n```\n
2
0
['Array', 'Stack', 'Sorting', 'Simulation', 'C++']
0
robot-collisions
Easy to understand || C++ || O(n log n) || Stack, Vector, Map
easy-to-understand-c-on-log-n-stack-vect-w7ig
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Manral_0203
NORMAL
2024-07-13T19:11:18.681460+00:00
2024-07-13T19:11:18.681482+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions,\n vector<int>& healths, string directions) {\n\n stack<int> st1;\n map<int, int> mp, mp2;\n map<int, int> mp1;\n unordered_map<int, int> um, um1;\n\n if (directions.find(\'L\') == -1 || directions.find(\'R\') == -1 ||\n directions.size() == 1) {\n return healths;\n }\n\n for (int i = 0; i < positions.size(); i++) {\n mp1[positions[i]] = healths[i];\n um[positions[i]] = i;\n um1[i] = healths[i];\n if (directions[i] == \'R\') {\n mp[positions[i]] = 1;\n } else {\n mp[positions[i]] = -1;\n }\n }\n vector<vector<int>> st;\n for (map<int, int>::iterator itr = mp1.begin(); itr != mp1.end();\n itr++) {\n map<int, int>::iterator itr1 = mp.find(itr->first);\n unordered_map<int, int>::iterator itr2 = um.find(itr->first);\n // cout<<itr->second<<" "<<itr->first<<endl;\n // cout<<itr2->second<<" "<<itr2->first<<endl;\n if (itr1->second == -1) {\n if (st.empty()) {\n st.push_back({itr2->second, itr->second});\n st1.push(-itr->second);\n } else if (st1.top() < 0) {\n // st.push(-itr->second);\n st.push_back({itr2->second, itr->second});\n st1.push(-itr->second);\n } else if (abs(st1.top()) == itr->second) {\n st.pop_back();\n st1.pop();\n } else if (abs(st1.top()) > itr->second) {\n int a = abs(st1.top()) - 1;\n vector<int> v = st.back();\n st1.pop();\n st.pop_back();\n st1.push(a);\n st.push_back({v[0], a});\n // st1.push(itr->second);\n\n } else {\n int a = 0, b = 0;\n vector<int> v;\n while (!st1.empty() && itr->second > (st1.top()) &&\n st1.top() > 0) {\n v = st.back();\n itr->second--;\n cout<<v[0]<<"\\t"<<v[1]<<endl;\n st.pop_back();\n st1.pop();\n // a++;\n // if(st.top()<0){\n // b=1;\n // break;\n // }\n }\n if (st1.empty() || st1.top()<0) {\n // st1.pop();\n st1.push(-itr->second );\n // st1.push(itr->second);\n st.push_back({itr2->second, itr->second - a});\n\n }else if(itr->second==st1.top()){\n st1.pop();\n st.pop_back();\n }\n else if(st1.top()>itr->second){\n int a = st1.top() - 1;\n v = st.back();\n st.pop_back();\n st1.pop();\n st.push_back({v[0],a});\n st1.push(a);\n }\n // else if( st1.top()>itr->second) {\n // int a = itr->second - 1;\n // // st.pop();\n // st1.push(-a);\n // // st1.push(itr->second);\n // st.push_back({itr2->second, a});\n // }\n else {\n \n int a = itr->second - 1;\n // st.pop();\n st1.push(a);\n // st1.push(itr->second);\n st.push_back({v[0], a});\n }\n cout << "khh";\n cout << itr2->second << " " << itr->second << endl;\n }\n } else {\n st1.push(itr->second);\n st.push_back({itr2->second, itr->second});\n cout << itr2->second << " " << itr->second << endl;\n\n // st.push(itr->second);\n }\n }\n\n // cout << st.size() << "\\t" << st1.size();\n vector<int> re, ce;\n // vector<vector<int>> v;\n // while (!st.empty()) {\n // unordered_map<int, int>::iterator itr1 = um.find(st1.top());\n // unordered_map<int, int>::iterator itr = um.find(itr1->);\n // v.push_back({itr->second, st.top()});\n // cout << itr->second << "\\t" << st.top() << endl;\n // // cout<<st1.top()<<endl;\n // st1.pop();\n // // cout<<st.top()<<endl;\n // st.pop();\n // }\n for (auto& i : st) {\n cout << i[0] << "\\t" << i[1] << endl;\n // re.push_back(abs(i[1]));\n }\n sort(st.begin(), st.end());\n for (auto& i : st) {\n cout << i[0] << endl;\n re.push_back(abs(i[1]));\n }\n return re;\n }\n};\n```
2
0
['Array', 'Stack', 'Sorting', 'C++']
0
robot-collisions
A C Solution
a-c-solution-by-well_seasoned_vegetable-01re
Code\n\nstruct data {\n int position;\n int health;\n char direction;\n int idx;\n};\n\nint cmp(const void* a, const void* b) {\n return ((struct
well_seasoned_vegetable
NORMAL
2024-07-13T15:40:30.816911+00:00
2024-07-14T12:22:04.530312+00:00
28
false
# Code\n```\nstruct data {\n int position;\n int health;\n char direction;\n int idx;\n};\n\nint cmp(const void* a, const void* b) {\n return ((struct data*)a)->position - ((struct data*)b)->position;\n}\n\nint* survivedRobotsHealths(int* positions, int positionsSize, int* healths, int healthsSize, char * directions, int* returnSize){\n *returnSize = 0;\n struct data* stack = malloc(positionsSize * sizeof(struct data));\n struct data* arr = malloc(positionsSize * sizeof(struct data));\n for(int i = 0; i < positionsSize; i++) {\n arr[i].position = positions[i];\n arr[i].health = healths[i];\n arr[i].direction = directions[i];\n arr[i].idx = i;\n }\n\n int idx = -1;\n qsort(arr, positionsSize, sizeof(struct data), cmp);\n\n for(int i = 0; i < positionsSize; i++) {\n if(arr[i].direction == \'R\') stack[++idx] = arr[i];\n else {\n while(idx >= 0) {\n if(arr[i].health > stack[idx].health) {\n healths[arr[i].idx] = --arr[i].health;\n stack[idx--].health = healths[stack[idx].idx] = 0;\n }\n else{\n if(arr[i].health == stack[idx].health) stack[idx--].health = healths[stack[idx].idx] = 0;\n else healths[stack[idx].idx] = --stack[idx].health;\n healths[arr[i].idx] = arr[i].health = 0;\n break;\n }\n }\n }\n }\n int* ret = malloc(positionsSize * sizeof(int));\n for(int i = 0; i < positionsSize; i++) {\n if(healths[i]) ret[(*returnSize)++] = healths[i];\n }\n\n return ret;\n}\n```
2
0
['C']
0
robot-collisions
IN DEPTH SOUTION || JAVA || Stack.
in-depth-soution-java-stack-by-abhishekk-ap37
Thanks @mikey.\n# Guys UPVOTE IF U LIKED THE EXPLANATION.\n\n# Breakdown:\n\n1. Input and Initialization:\n - positions: An integer array storing the initial
Abhishekkant135
NORMAL
2024-07-13T15:03:17.423331+00:00
2024-07-13T15:03:17.423370+00:00
82
false
Thanks @mikey.\n# Guys UPVOTE IF U LIKED THE EXPLANATION.\n\n# **Breakdown:**\n\n1. **Input and Initialization:**\n - `positions`: An integer array storing the initial positions of the robots (circular arena).\n - `healths`: An integer array storing the initial health of each robot.\n - `directions`: A String representing the direction each robot faces ("L" - left, "R" - right).\n - `n`: Stores the number of robots (length of the arrays).\n - `indices`: An Integer array created to hold robot indices (used for sorting).\n - `stack`: A stack to store indices of robots facing right ("R").\n - `result`: An empty list to store the remaining health of surviving robots.\n\n2. **Sorting by Positions:**\n - The `indices` array is filled with robot indices (0 to n-1).\n - The `indices` array is sorted based on the robot positions in the `positions` array using `Arrays.sort`. This ensures processing robots in the order they encounter each other.\n\n3. **Processing Robots:**\n - The code iterates through the robots in the sorted order using the `indices` array.\n\n - **Robot Facing Right ("R"):**\n - If the current robot faces right ("R"), its index is pushed onto the `stack`. This indicates it will attack robots to its left.\n\n - **Robot Facing Left ("L"):**\n - If the current robot faces left ("L"), it attacks robots that are currently on the `stack` (facing right).\n - The loop continues as long as the `stack` is not empty and the current robot has health (`healths[currentIndex] > 0`).\n - The robot at the top of the `stack` (`topIndex`) is compared with the current robot.\n - **Current Robot Stronger:**\n - If the current robot has more health (`healths[currentIndex] > healths[topIndex]`), it reduces the health of the robot on the stack (`healths[topIndex] -= 1`) and sets its own health to 0 (defeated). The `topIndex` is then pushed back onto the stack to maintain processing order.\n - **Equal Health:**\n - If both robots have the same health (`healths[topIndex] == healths[currentIndex]`), both are defeated, and their healths are set to 0.\n - **Current Robot Weaker:**\n - If the current robot has less health (`healths[topIndex] > healths[currentIndex]`), it is defeated, and its health is set to 0. The health of the robot on the stack remains unchanged.\n - After processing the robots on the stack, the loop continues to the next robot facing left.\n\n4. **Extracting Surviving Robot Healths:**\n - After iterating through all robots, the code loops through the `healths` array again.\n - For each robot, if its health is still positive (`healths[i] > 0`), it means the robot survived the battles. The remaining health is added to the `result` list.\n\n5. **Returning Results:**\n - The function returns the `result` list containing the remaining health of all surviving robots.\n\n# **Overall:**\n\nThis code simulates robot battles in a circular arena, considering their facing directions and health, and returns the health remaining for the robots that survive the encounters.\n\n# Code\n```\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n Integer[] indices = new Integer[n];\n for (int i = 0; i < n; i++) {\n indices[i] = i;\n }\n Stack<Integer> stack = new Stack<>();\n Arrays.sort(indices, (i, j) -> Integer.compare(positions[i], positions[j]));\n List<Integer> result = new ArrayList<>();\n for (int currentIndex : indices) {\n if (directions.charAt(currentIndex) == \'R\') {\n stack.push(currentIndex);\n } else {\n while (!stack.isEmpty() && healths[currentIndex] > 0) {\n int topIndex = stack.pop();\n\n if (healths[topIndex] > healths[currentIndex]) {\n healths[topIndex] -= 1;\n healths[currentIndex] = 0;\n stack.push(topIndex);\n } else if (healths[topIndex] < healths[currentIndex]) {\n healths[currentIndex] -= 1;\n healths[topIndex] = 0;\n } else {\n healths[currentIndex] = 0;\n healths[topIndex] = 0;\n }\n }\n }\n }\n for (int i = 0; i < n; i++) {\n if (healths[i] > 0) {\n result.add(healths[i]);\n }\n }\n return result;\n }\n}\n```
2
0
['Array', 'Stack', 'Java']
0
robot-collisions
Solution using Stack
solution-using-stack-by-salman_md-2m1m
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
salman_md_
NORMAL
2024-07-13T11:24:01.232186+00:00
2024-07-13T11:24:01.232217+00:00
128
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity : O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions,\n vector<int>& healths, string directions) {\n int n = positions.size();\n vector<int> actual_index(n);\n iota(begin(actual_index), end(actual_index), 0);\n auto lambda = [&](int& i, int& j) {\n return positions[i] < positions[j];\n };\n sort(actual_index.begin(), actual_index.end(), lambda);\n vector<int> result;\n stack<int> st;\n for (int currIdx : actual_index) {\n if (directions[currIdx] == \'R\') {\n st.push(currIdx);\n } else {\n while (!st.empty() && healths[currIdx] > 0) {\n int top_idx = st.top();\n st.pop();\n if (healths[top_idx] > healths[currIdx]) {\n healths[top_idx] -= 1;\n healths[currIdx] = 0;\n st.push(top_idx);\n } else if (healths[top_idx] < healths[currIdx]) {\n healths[currIdx] -= 1;\n healths[top_idx] = 0;\n } else {\n healths[currIdx] = 0;\n healths[top_idx] = 0;\n }\n }\n }\n }\n for (int i = 0; i < n; i++) {\n if (healths[i] > 0) {\n result.push_back(healths[i]);\n }\n }\n return result;\n }\n};\n```
2
0
['C++']
1
robot-collisions
[✅🧠 FULLY EASY EXPLAINED STACK O(N log N) Approach C++]
fully-easy-explained-stack-on-log-n-appr-p97u
This question is all about just observation. Observation: The only possible collision is when there is a sequence of directions as: "RL" as the first robot is m
o1154
NORMAL
2024-07-13T09:42:34.134302+00:00
2024-07-13T09:42:34.134343+00:00
90
false
This question is all about just observation. Observation: The only possible collision is when there is a sequence of directions as: "RL" as the first robot is moving towards right and second is moving towards left **(GIVEN THAT THEY ARE SORTED ACCORDING TO THEIR POSITIONS LIKE FOR THE \'R\' IF THE POSITION IS SOME X THEN THE POSITION FOR L IF \'Y\' THEN X < Y HOLDS TRUE bcoz consider for a while IF THE SEQUENCE GIVEN WAS "RL" BUT THE POSITION OF R WAS 10 AND THAT OF L WAS 1 SO ULTIMATELY THE SEQUENCE WAS LR WHICH MEANS THAT THEY WON\'T COLLIDE)**. So now we just had to check for only three things that is if (after sorting as per positions) the previous robot was moving towards right and current is moving towards left then whose health is greater (specified in question). Now the next thing to consider is till when the current robot survive like if there was a stream of robots going right and current robot wanted to go left the let\'s say a case "RRRL" and health [3,2,3,4] like consider that current robot is \'L\' so it wants to go left and all on the left of it wants to come right then firstly our robot will kill the previous robot with 3 health and our robot health becomes 3 and the previous robot dies then comes the next robot with 2 health, our health is 3 we kill that robot and our health becomes 2 now next robot has health 3 so it\'s health is greater than our health and our gets killed by next robot and health of that robot reduces to 2 and survives. (DO A DRY RUN YOU WILL DEFINITELY UNDERSTAND).\nLast thing that is reaquired is that we need to return the sequence like the previous sequence you might already see that i have already made a custom node with position,health,direction and index of every robot. and firstly i am sorting wrt the position (clarified above) and at last i have sorted based on their initial index (stored in node) which will eventually give us correct sequence.\n[DO A DRYRUN ALSO]\n[\u2705 PLS UPVOTE IF YOU LIKED THE EXPLANATION]\n```\nclass node{\npublic:\n int position;\n int health; \n char direction;\n int index;\n node(int _position, int _health, char _direction, int _index){\n position = _position;\n health = _health;\n direction = _direction;\n index = _index;\n }\n};\n\nbool comparator(node* node1, node* node2){\n return node1->position < node2->position;\n}\n\nbool comparator2(node* node1, node* node2){\n return node1->index < node2->index;\n}\n\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<node*>vv;\n int n = positions.size();\n for(int i = 0; i < n; i++){\n node* curr = new node(positions[i], healths[i], directions[i], i);\n vv.push_back(curr);\n }\n sort(vv.begin(), vv.end(), comparator);\n stack<node*>st;\n for(auto &i: vv){\n if(st.empty()){\n st.push(i);\n } else {\n if(st.top()->direction == \'R\' && i->direction == \'L\'){\n bool consider = false;\n while(st.size() && st.top()->direction == \'R\' && i->direction == \'L\'){\n if(st.top()->health == i->health){\n st.pop();\n consider = false;\n break;\n }else if(st.top()->health > i->health){\n node* tempNode = new node(st.top()->position, st.top()->health - 1, st.top()->direction, st.top()->index);\n st.pop();\n st.push(tempNode);\n consider = false;\n break;\n } else if(st.top()->health < i->health){\n node* tempNode = new node(i->position, i->health - 1, i->direction, i->index);\n i = tempNode;\n st.pop();\n consider = true;\n }\n }\n if(consider){\n st.push(i);\n }\n } else {\n st.push(i);\n }\n }\n }\n \n vector<node*>temp;\n while(st.size()){\n temp.push_back(st.top());\n st.pop();\n }\n sort(temp.begin(), temp.end(), comparator2);\n vector<int>ans;\n for(auto i: temp){\n ans.push_back(i->health);\n }\n return ans;\n }\n};\n```
2
0
['Stack', 'Greedy', 'C', 'Sorting', 'JavaScript']
2
robot-collisions
Easiest Stack Solution -- SORT -- Commented
easiest-stack-solution-sort-commented-by-n6uq
Intuition\n Describe your first thoughts on how to solve this problem. \nStep 1 : Sort according to positions in asceding irder\nStep 2 : Use stack to store sta
Skaezr73
NORMAL
2024-07-13T08:37:51.369845+00:00
2024-07-13T09:33:23.241389+00:00
119
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n<b>Step 1 :</b> Sort according to positions in asceding irder\n<b>Step 2 :</b> Use stack to store state of each robot\n<b>Step 3 :</b> If ***current*** robot has direction to **"RIGHT"** just push it \n<b>Step 4 :</b> Else use the following 3 cases\n```\nwhile (!st.empty() && st.top().dir == \'R\') {\n if (arr[i].health > st.top().health) {\n arr[i].health--;\n st.pop();\n } else if (arr[i].health == st.top().health) {\n fg = 1; // don\'t push latest robot\n st.pop();\n break;\n } else {\n st.top().health--;\n fg = 1;\n break;\n }\n }\n```\n\n<b>Step 5 :</b> flag here is used when we will not add current robot to stack\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(log(n))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n# Code\n```\nclass Solution {\npublic:\n struct robot {\n int pos;\n int health;\n char dir;\n };\n\n static bool comp(struct robot &a, struct robot &b) {\n return a.pos < b.pos;\n }\n\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<struct robot> arr;\n unordered_map<int, int> mp; // store position vs index\n int n = positions.size();\n\n for (int i = 0; i < n; i++) {\n struct robot it;\n it.pos = positions[i];\n it.health = healths[i];\n it.dir = directions[i]; \n arr.push_back(it);\n mp[it.pos] = i;\n }\n\n sort(arr.begin(), arr.end(), comp);\n\n stack<struct robot> st;\n\n for (int i = 0; i < n; i++) {\n if (st.empty()) {\n st.push(arr[i]);\n } else {\n if (arr[i].dir == \'R\') {\n st.push(arr[i]);\n } else {\n int fg = 0;\n while (!st.empty() && st.top().dir == \'R\') {\n if (arr[i].health > st.top().health) {\n arr[i].health--;\n st.pop();\n } else if (arr[i].health == st.top().health) {\n fg = 1; // don\'t push latest robot\n st.pop();\n break;\n } else {\n st.top().health--;\n fg = 1;\n break;\n }\n }\n if (fg == 0) {\n st.push(arr[i]);\n }\n }\n }\n }\n\n vector<int> ans(n, 0);\n\n while (!st.empty()) {\n ans[mp[st.top().pos]] = st.top().health;\n st.pop();\n }\n\n vector<int> finali;\n for (auto e : ans) {\n if (e > 0) finali.push_back(e);\n }\n\n return finali;\n }\n};\n\n```
2
0
['C++']
0
robot-collisions
Python Solution
python-solution-by-mouad_haikal-adab
\n\n# Code\n\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n robots = so
Mouad_Haikal
NORMAL
2024-07-13T08:26:09.973940+00:00
2024-07-13T08:26:09.973993+00:00
137
false
\n\n# Code\n```\nclass Solution:\n def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:\n robots = sorted(list(zip(positions, directions, healths)))\n stack = []\n\n for bot in robots:\n c = False\n pos, dire, hp = bot\n while dire == \'L\' and stack and stack[-1][1] == \'R\':\n pos2, dire2, hp2 = stack.pop()\n if hp < hp2:\n dire = \'R\'\n hp = hp2-1\n pos = pos2\n elif hp > hp2:\n hp -= 1\n else:\n c = True\n break\n if c: continue\n stack.append((pos, dire, hp))\n\n d = {pos: hp for pos, _, hp in stack}\n out = []\n for pos in positions:\n if pos in d: out.append(d[pos])\n return out\n```
2
0
['Stack', 'Sorting', 'Simulation', 'Python', 'Python3']
1
robot-collisions
[C++] --> Stack | Explained | Kind of easy understand!
c-stack-explained-kind-of-easy-understan-iymi
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
zhanghx04
NORMAL
2024-07-13T07:25:20.232787+00:00
2024-07-13T07:25:20.232841+00:00
18
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define L 1\n#define R 0\n\nclass Solution {\npublic:\n struct Robot {\n int health;\n int pos;\n int direction; // 0 toright, 1 toleft, so if there is a collision, left - right should be -1\n };\n\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<Robot> game;\n unordered_map<int, int> alive; // position : health\n\n int n = positions.size();\n\n // Combine robot\'s all information and sort it by its position\n for (int i = 0; i < n; ++i) {\n game.push_back(Robot(healths[i], positions[i], directions[i] == \'L\'));\n }\n\n sort(game.begin(), game.end(), [] (const Robot &a, const Robot &b) { return a.pos < b.pos; });\n\n stack<Robot> stk;\n\n for (auto &robot : game) {\n // Stack store the robot that go to R direction\n if (robot.direction == R) {\n stk.push(robot);\n continue;\n } \n\n // Here is the robot that goes L direction\n // No robot goes right, so this robot is safe\n if (stk.empty()) {\n alive[robot.pos] = robot.health;\n continue;\n } \n\n // Collision!!!\n while (!stk.empty()) {\n Robot curr = stk.top();\n stk.pop();\n\n // Both died\n if (curr.health == robot.health) {\n robot.health = 0;\n break;\n }\n\n // Current L direction robot is stronger, health -1 and challenge the next enemy\n if (curr.health < robot.health) {\n robot.health--;\n continue;\n }\n\n // Current Ldirection robot is weak, died, the enemy\'s health -1 and go back to stack\n if (curr.health > robot.health) {\n curr.health--;\n robot.health = 0;\n stk.push(curr);\n break;\n }\n }\n\n // If current robot won all of the R direction enemy and still alive.\n if (robot.health > 0) {\n alive[robot.pos] = robot.health;\n }\n \n }\n\n // Remain Robots in stack are alive\n while (!stk.empty()) {\n alive[stk.top().pos] = stk.top().health;\n stk.pop();\n }\n\n // Based on robots\' original input order to write the alives\' health\n vector<int> result;\n for (int pos : positions) {\n if (alive.count(pos)) {\n result.push_back(alive[pos]);\n }\n }\n\n return result;\n }\n};\n```
2
0
['Stack', 'C++']
0
robot-collisions
Easy Solution Using stack and sorting in c++
easy-solution-using-stack-and-sorting-in-fbrh
\n# Code\n\nclass Solution\n{\npublic:\n vector<int> survivedRobotsHealths(vector<int> &positions, vector<int> &health, string directions)\n {\n in
rohit_1610
NORMAL
2024-07-13T04:38:44.399366+00:00
2024-07-13T04:38:44.399403+00:00
18
false
\n# Code\n```\nclass Solution\n{\npublic:\n vector<int> survivedRobotsHealths(vector<int> &positions, vector<int> &health, string directions)\n {\n int n = directions.size();\n vector<int> ans;\n vector<pair<int, int>> vp;\n for (int i = 0; i < n; i++)\n {\n int x = positions[i];\n vp.push_back({i, x});\n }\n sort(vp.begin(), vp.end(), [&](pair<int, int> a, pair<int, int> b)\n { return a.second < b.second; });\n stack<int> st;\n for (int i = 0; i < n; i++)\n {\n int ind = vp[i].first;\n char ch = directions[ind];\n if (ch == \'L\')\n {\n bool f = false;\n while (!st.empty() && directions[st.top()] == \'R\')\n {\n int x = health[ind], y = health[st.top()];\n if (x == y)\n {\n\n health[ind] = 0;\n health[st.top()] = 0;\n st.pop();\n f = true;\n break;\n }\n else if (x > y)\n {\n\n health[st.top()] = 0;\n st.pop();\n health[ind]--;\n }\n else\n {\n f = true;\n health[st.top()]--;\n health[ind] = 0;\n break;\n }\n }\n if (!f)\n {\n st.push(ind);\n }\n }\n else\n {\n st.push(ind);\n }\n }\n for (auto it : health)\n {\n if (it > 0)\n {\n ans.push_back(it);\n }\n }\n return ans;\n }\n};\n```
2
0
['C++']
0
robot-collisions
Simple Stack Approach and Simulation. Beats All
simple-stack-approach-and-simulation-bea-g6e9
Intuition\n Describe your first thoughts on how to solve this problem. \nThe key insight is that robots moving in the same direction will never collide. Therefo
officialank671
NORMAL
2024-07-13T04:32:41.086335+00:00
2024-07-13T04:32:41.086364+00:00
331
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n*The key insight is that robots moving in the same direction will never collide. Therefore, we only need to worry about collisions between robots moving in opposite directions. We can use a stack to efficiently track robots moving right (\'R\'). When encountering a left-moving robot (\'L\'), we simulate collisions with the right-moving robots on the stack until either the left-moving robot is destroyed or there are no more valid collisions.*\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Sorting for Simulation:** Sort the robots based on their positions to simulate their movement from left to right. Store the sorted indices for later reference.\n2. **Stack for Right-Moving Robots:** Use a stack to keep track of the indices of robots moving to the right.\n3. **Simulating Movement and Collisions:**\n - Iterate through the sorted indices.\n - If a robot is moving right, push its index onto the stack.\n - If a robot is moving left:\n - Pop right-moving robots from the stack while their health is less than or equal to the current left-moving robot\'s health.\n - If both robots have equal health in a collision, remove both.\n - If the left-moving robot survives a collision, decrement its health.\n - If the stack is not empty after processing collisions and the top right-moving robot has more health, decrement its health.\n4. **Collecting Survivors:** Iterate through the healths array and collect the health values of surviving robots (those with health greater than zero).\n\n# Submission\n \n![Screenshot 2024-07-13 100103.png](https://assets.leetcode.com/users/images/90a45112-502e-40d0-b499-25ae1b603a68_1720845127.6968844.png)\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nlog(n))$$ *due to the initial sorting of robot positions. The rest of the algorithm processes each robot (and potentially its collisions) once, resulting in an overall linear time complexity after sorting.*\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ *to store the sorted indices and potentially all robots in the stack (worst case when all robots move right).*\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n ios_base::sync_with_stdio(false);\n vector<int> result;\n vector<int> indices(positions.size()); // index array is better than making pair<int,int>\n iota(indices.begin(), indices.end(), 0); // initializing 0 to n\n sort(indices.begin(),indices.end(), // sorting index array so, we don\'t loose the original order \n [&positions](int indexA,int indexB){ // custom Comparator\n return positions[indexA]<positions[indexB]; // on the basis of positions\n }\n );\n stack<int> st;\n for(int index : indices){\n if(directions.at(index)==\'R\') st.push(index); // we store only right because we moving 0 to n\n else {\n if(st.empty()) continue; // no collisons \n while(!st.empty() && healths.at(st.top())<=healths.at(index)){ \n // till we have no more collisions \n if(healths.at(st.top())==healths.at(index)){\n healths.at(index)=-1; // set negative value\n healths.at(st.top())=-1;\n st.pop();\n break; // once equal both robot[index] && robot[st.top()] will be removed from line \n }\n else{\n healths.at(st.top())=-1;\n st.pop();\n healths.at(index)--;\n }\n }\n // make sure for check health[index] > 0 \n if(!st.empty() && healths.at(index)>0 && healths.at(st.top())> healths[index]){\n healths.at(st.top())--;\n healths.at(index)=-1;\n }\n }\n }\n for(int health : healths)\n if(health > 0) result.push_back(health); // survivors\n return result;\n }\n};\n```\n```Java []\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n List<Integer> result = new ArrayList<Integer>();\n List<Integer> indices = new ArrayList<>();\n for (int i = 0; i < positions.length; i++)\n indices.add(i);\n Comparator<Integer> cmp = (a, b) -> {\n return positions[a] - positions[b];\n };\n indices.sort(cmp);\n Stack<Integer> st = new Stack<>();\n for (int index : indices) {\n if (directions.charAt(index) == \'R\') {\n st.add(index);\n } else {\n if (st.isEmpty()) continue;\n while (!st.isEmpty() && healths[st.peek()] <= healths[index] && healths[index] > 0) {\n if (healths[st.peek()] == healths[index]) {\n healths[index] = -1;\n healths[st.peek()] = -1;\n st.pop();\n break;\n } else {\n healths[st.peek()] = -1;\n st.pop();\n healths[index]--;\n }\n }\n if (!st.isEmpty() && healths[index] > 0 && healths[st.peek()] > healths[index]) {\n healths[st.peek()]--;\n healths[index] = -1;\n }\n }\n }\n for (int health : healths) {\n if (health > 0) result.add(health);\n }\n return result;\n }\n}\n```\n
2
0
['Array', 'Stack', 'Sorting', 'Simulation', 'C++']
3
robot-collisions
Kotlin simulation (Sort + Stack)
kotlin-simulation-sort-stack-by-james438-jb1n
\ndata class Robot (var position: Int, var health: Int, var direction: Char, val index: Int) {}\n\nenum class DIRECTION(val value: Char) {\n LEFT(\'L\'),\n
james4388
NORMAL
2024-07-13T04:14:33.003437+00:00
2024-07-13T04:14:33.003472+00:00
53
false
```\ndata class Robot (var position: Int, var health: Int, var direction: Char, val index: Int) {}\n\nenum class DIRECTION(val value: Char) {\n LEFT(\'L\'),\n RIGHT(\'R\')\n}\n\nclass Solution {\n fun survivedRobotsHealths(positions: IntArray, healths: IntArray, directions: String): List<Int> {\n var robots = positions.withIndex().map { (index, position) -> Robot(position, healths[index], directions[index], index) }.toMutableList()\n robots.sortBy { it.position }\n var rightRobots = mutableListOf<Robot>()\n\n for (robot in robots) {\n if (robot.direction == DIRECTION.RIGHT.value) {\n rightRobots.add(robot)\n } else { // Left robot\n while (rightRobots.isNotEmpty() && robot.health > 0) {\n val rightRobot = rightRobots.removeLast()\n if (rightRobot.health > robot.health) {\n rightRobot.health -= 1\n robot.health = 0\n rightRobots.add(rightRobot)\n } else if (rightRobot.health < robot.health) {\n robot.health -= 1\n rightRobot.health = 0\n } else {\n robot.health = 0\n rightRobot.health = 0\n }\n }\n }\n }\n robots.sortBy { it.index }\n \n return robots.filter { it.health > 0 }.map { it.health }\n }\n}\n```
2
0
['Stack', 'Sorting', 'Simulation', 'Kotlin']
0
robot-collisions
Java | Detailed approach using Stack and Sorting.
java-detailed-approach-using-stack-and-s-dmmr
Intuition\nA collision can occur between any two consecutive robots only and out of which the one with less health gets removed or both gets removed if their he
mr_pawan
NORMAL
2024-07-13T03:02:05.280145+00:00
2024-07-13T11:56:24.200064+00:00
114
false
# Intuition\nA collision can occur between any two consecutive robots only and out of which the one with less health gets removed or both gets removed if their health is the same.\nIt immediately makes me think of a **Stack** as we just need to check with the previous robot and if it\'s moving in the opposite direction.\n\n# Approach\nFirst we need to sort the robots according to their position because only then we can make a decision about collision.\nI have stored all the robot information in the Robot class, with it\'s original index position because in the end we need to return the survived robots in the original order if they survived.\nThen just keep on adding the robot in the stack till the time a robot with opposite direction which can collide comes and then we decide continuously with the previous robots in the stack till the time there is no possible collision.\nAlso there can be only 4 cases when 2 robots encounter each other.\n1. Previous robot is moving in Left and next one is also moving in Left direction\n2. Previous robot is moving in Right and next robot is also moving in right direction.\n3. Previous robot is moving in left and next robot is moving in right direction.\n4. Previous robot is moving in right and next robot is moving in left direction.\n\nObserve that a collision can occur only in case number 4. So we just need to handle that.\nIn case of collisions\nWhen the previous robot health is greater then the current robot is to be removed and the previous robot health gets reduced by 1, also we break out of the loop as the current robot can not make any more collisions as the robots before the previous robot are moving in a direction of no collision.\nWhen the current robot health is greater then the previous robot is to be removed and we need to continue checking with the other previous robots.\nWhen both of their health is same then both of them needs to be removed and then we break out of the loop as the robots before the previous robot are moving in a direction of no collision.\n\nOnce we have traversed through all the robots we just take out all the survived robots from stack and get them sorted using their original indexes and return them in a list.\n\nDO UPVOTE if you Liked the solution \uD83D\uDE04\u270C\uD83C\uDFFB\uD83D\uDE4C\uD83C\uDFFB\n\n# Complexity\n- Time complexity:\n**O(NlogN)** \n\n- Space complexity:\n**O(N)**\n\n# Code\n```\nclass Solution {\n\n class Robot {\n int index;\n char direction;\n int health;\n int position;\n\n public Robot(int index, char direction, int health, int position) {\n this.index = index;\n this.direction = direction;\n this.health = health;\n this.position = position;\n }\n\n public int getHealth() {\n return this.health;\n }\n }\n\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n Robot[] robots = new Robot[positions.length];\n\n for (int i = 0; i < positions.length; i++) {\n Robot robot = new Robot(i, directions.charAt(i), healths[i], positions[i]);\n robots[i] = robot;\n }\n\n Arrays.sort(robots, (a, b) -> {\n return a.position - b.position;\n });\n\n Stack<Robot> stack = new Stack<>();\n\n for (Robot robot : robots) {\n if (stack.isEmpty()) {\n stack.push(robot);\n } else if (willCollide(stack.peek(), robot)) {\n while (!stack.isEmpty() && willCollide(stack.peek(), robot)) {\n Robot prevRobot = stack.pop();\n if (prevRobot.health > robot.health) {\n prevRobot.health--;\n stack.push(prevRobot);\n robot.health = 0;\n break;\n } else if (robot.health > prevRobot.health) {\n robot.health--;\n prevRobot.health = 0;\n } else {\n prevRobot.health = 0;\n robot.health = 0;\n break;\n }\n }\n\n if (robot.health > 0) {\n stack.push(robot);\n }\n } else {\n stack.push(robot);\n }\n }\n\n List<Robot> survivedRobots = new ArrayList<>();\n while (!stack.isEmpty()) {\n survivedRobots.add(stack.pop());\n }\n\n survivedRobots.sort((a, b) -> {\n return a.index - b.index;\n });\n\n return survivedRobots.stream().map(Robot::getHealth).toList();\n }\n\n public boolean willCollide(Robot robot1, Robot robot2) {\n return robot1.direction == \'R\' && robot2.direction == \'L\';\n }\n}\n```
2
0
['Stack', 'Sorting', 'Java']
1
robot-collisions
Simulation using gnu pbds ordered statistics tree (ordered set)
simulation-using-gnu-pbds-ordered-statis-xoxw
Intuition\nWe can use simulation to solve this problem since there can be no more than $2n$ collisions. How do we know which two robots will collide? Let\'s cat
envyaims
NORMAL
2024-07-13T02:05:20.065607+00:00
2024-07-13T02:05:20.065625+00:00
76
false
# Intuition\nWe can use simulation to solve this problem since there can be no more than $2n$ collisions. How do we know which two robots will collide? Let\'s categorize each robot as moving left and moving right and sort by position. Consider robot $i$ moving right. Then, there is a possibility of colliding with robot $j$ moving left such that it robot $j$ has the smallest $p_j$ such that $p_j > p_i$. Of course, if $p_j > p_{i+1}$, then the next robot moving right will attack the $j$\'th robot first, so we process that robot first. Let $k$ be the minimum integer such that $p_k > p_{i+1}$. We can try to attack robots moving left in the interval $[j,k-1]$.\n\nThen, if this robot is defeated by any robot moving the opposite direction in the interval, then there is a possibly the robot which defeats our robot will attack more robots $j < i$. We can simulate the attacks of that robot as well.\n\n# Approach\n\nWe can simulate the above using gnu pbds ordered statistics tree, since we are able to index the set and treat it practically as a vector with efficient erasing.\n\n# Complexity\n- Time complexity\nO(n log n) probably\n- Space complexity:\nO(n)\n\n# Code\n```\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/detail/standard_policies.hpp>\nusing namespace __gnu_pbds;\nclass Solution {\npublic:\n template<typename T>\n using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\n vector<int> survivedRobotsHealths(vector<int>& p, vector<int>& h, string dir) {\n int n = p.size();\n ordered_set<array<int, 3>> left, right;\n for(int i = 0; i < n; i++){\n if(dir[i] == \'L\'){\n right.insert({p[i], h[i], i});\n }\n else{\n left.insert({p[i], h[i], i});\n }\n }\n for(int i = 0; i < left.size();){\n array<int, 3> cur_robot = *left.find_by_order(i);\n auto it = right.lower_bound({cur_robot[0], -69420, -69420});\n if(it != right.end() && i + 1 < left.size() && (*it)[0] > (*left.find_by_order(i+1))[0]){\n it = right.end();\n }\n while(it != right.end() && cur_robot[1] > (*it)[1]){\n // while we can smack the right robot\n right.erase(it);\n it = right.lower_bound({cur_robot[0], -69420, -69420});\n cur_robot[1]--;\n if(it != right.end() && i + 1 < left.size() && (*it)[0] > (*left.find_by_order(i+1))[0]){\n it = right.end();\n }\n }\n if(it != right.end()){\n left.erase(left.find_by_order(i));\n if(cur_robot[1] == (*it)[1]){\n // both die\n right.erase(it);\n i = max(0, i - 1);\n }\n else{\n // the right robot kept going\n array<int, 3> r_robot = *it;\n r_robot[1]--;\n i--;\n while(i >= 0 && (*left.find_by_order(i))[1] < r_robot[1]){\n left.erase(left.find_by_order(i));\n i--;\n r_robot[1]--;\n }\n if(i == -1){\n // right robot prevails\n right.erase(it);\n right.insert(r_robot);\n }\n else{\n array<int, 3> l_robot = (*left.find_by_order(i));\n left.erase(l_robot);\n right.erase(it);\n if(l_robot[1] != r_robot[1]){\n // we kill the right robot\n l_robot[1]--;\n left.insert(l_robot);\n assert(i == left.order_of_key(l_robot));\n }\n i--;\n }\n i = max(i, 0);\n }\n }\n else{\n // go to next left robot\n left.erase(left.find_by_order(i));\n left.insert(cur_robot);\n i++;\n }\n }\n vector<pair<int, int>> ans;\n for(int i = 0; i < left.size(); i++){\n ans.push_back({(*left.find_by_order(i))[2], (*left.find_by_order(i))[1]});\n }\n for(int i = 0; i < right.size(); i++){\n ans.push_back({(*right.find_by_order(i))[2], (*right.find_by_order(i))[1]});\n }\n sort(ans.begin(), ans.end());\n vector<int> real_ans;\n for(auto i: ans) real_ans.push_back(i.second);\n return real_ans;\n }\n};\n```
2
0
['Simulation', 'Ordered Set', 'C++']
0
robot-collisions
"Robot Battle Simulation: Calculating Remaining Health" 100% 100% PHP
robot-battle-simulation-calculating-rema-nj9u
Intuition\nSimulate the robot battles while tracking their positions and health.\n\n# Approach\nSort the robot indices by position, process them in order while
jeniapppqqq
NORMAL
2023-10-06T11:54:51.048435+00:00
2023-10-06T11:54:51.048462+00:00
47
false
# Intuition\nSimulate the robot battles while tracking their positions and health.\n\n# Approach\nSort the robot indices by position, process them in order while simulating battles between left-moving and right-moving robots, and return the remaining health.\n\n# Complexity\n- Time complexity: O(n*log(n))\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\n /**\n * @param Integer[] $positions\n * @param Integer[] $healths\n * @param String $directions\n * @return Integer[]\n */\n public function survivedRobotsHealths($positions, $healths, $directions) {\n // Create an array to store robot indices and sort them based on positions\n $sort = [];\n for ($i = 0; $i < count($positions); ++$i) {\n $sort[$i] = $i;\n }\n usort($sort, function($a, $b) use ($positions) {\n return $positions[$a] - $positions[$b];\n });\n\n // Initialize two arrays to store robot data\n $next = []; // Array to keep track of robots moving to the right\n $data = []; // Array to store final data\n\n // Iterate through robots in sorted order of positions\n foreach ($sort as $i) {\n if ($directions[$i] == \'R\') {\n // If robot is moving right, add it to the \'next\' array\n array_push($next, [$i, $healths[$i]]);\n } else {\n $cur = $healths[$i];\n // If robot is moving left, simulate its movement and adjust health\n while (!empty($next) && $next[count($next) - 1][1] < $cur) {\n $cur -= 1;\n array_pop($next);\n }\n if (empty($next)) {\n // If there are no robots moving right, add the left-moving robot to \'data\'\n array_push($data, [$i, $cur]);\n } else {\n // If there are robots moving right, adjust their health and add to \'next\'\n $tmp = array_pop($next);\n if ($tmp[1] > $cur) {\n $tmp[1] -= 1;\n array_push($next, $tmp);\n }\n }\n }\n }\n\n // Add the remaining robots moving to the right to \'data\'\n foreach ($next as $r) {\n array_push($data, $r);\n }\n\n // Sort \'data\' based on robot indices and extract the health values\n usort($data, function($a, $b) {\n return $a[0] - $b[0];\n });\n\n // Extract and return the remaining health values\n $res = [];\n foreach ($data as $i) {\n array_push($res, $i[1]);\n }\n return $res;\n }\n}\n\n```
2
0
['Array', 'Stack', 'Greedy', 'PHP', 'Sorting', 'Simulation']
0
robot-collisions
Easy Code || Stack + Sorting Based Approach || Easy to Understand
easy-code-stack-sorting-based-approach-e-2r9t
Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solution {\n static bool cmp(pair<int,int> &p1 , pair<int,int> &p2){
krishna_6431
NORMAL
2023-06-26T19:47:08.412505+00:00
2023-06-26T19:47:08.412525+00:00
108
false
# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\n static bool cmp(pair<int,int> &p1 , pair<int,int> &p2){\n return p1.second < p2.second;\n }\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n = positions.size();\n vector<pair<int,pair<int,pair<int,int>>>>vp;\n for(int i = 0 ; i < positions.size() ; i++){\n vp.push_back({positions[i],{healths[i],{directions[i],i}}});\n }\n sort(vp.begin(),vp.end());\n stack<pair<int,pair<int,int>>>stk;\n stk.push({vp[0].second.first,{vp[0].second.second.first,vp[0].second.second.second}});\n int j = 1;\n while(j < n){\n int health = vp[j].second.first;\n int dir = vp[j].second.second.first;\n if(!stk.empty() and stk.top().second.first == \'R\' and dir == \'L\'){\n if(!stk.empty() and stk.top().first < health){\n vp[j].second.first = vp[j].second.first - 1;\n stk.pop();\n if(j == n-1){\n if(stk.empty()){\n stk.push({vp[j].second.first,{dir,vp[j].second.second.second}});\n break;\n }\n }\n continue;\n }\n else if(!stk.empty() and stk.top().first == health){\n stk.pop();\n }\n else{\n stk.top().first--;\n }\n }\n else{\n stk.push({health,{dir,vp[j].second.second.second}});\n }\n j++;\n }\n vector<pair<int,int>>ans;\n while(!stk.empty()){\n ans.push_back({stk.top().first,stk.top().second.second});\n stk.pop();\n }\n sort(ans.begin(),ans.end(),cmp);\n vector<int>res;\n for(auto x : ans){\n res.push_back(x.first);\n }\n return res;\n }\n};\n```
2
0
['Stack', 'Sorting', 'C++']
0
robot-collisions
Cleanest Implementation [C++]
cleanest-implementation-c-by-jaintle-xugj
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n prior
jaintle
NORMAL
2023-06-25T21:12:45.253367+00:00
2023-06-25T22:10:51.819770+00:00
193
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> ans;\n vector<int> sol;\n vector<pair<pair<int,int>,char>> v;\n unordered_map<int,int> m;\n for(int i=0; i<positions.size(); i++){\n m[positions[i]]=i;\n v.push_back({{positions[i],healths[i]},directions[i]});\n }\n sort(v.begin(),v.end());\n stack<pair<int,int>> st;\n for(int i = 0; i<v.size(); i++){\n if(v[i].second==\'R\'){\n st.push({v[i].first.first,v[i].first.second});\n }\n else{\n int l = v[i].first.second;\n while(!st.empty()){\n auto temp = st.top();\n st.pop();\n if(l>temp.second){\n l-=1;\n }\n else{\n temp.second-=1;\n if(temp.second!=l-1)st.push(temp);\n l=0;\n break;\n }\n }\n if(l!=0)ans.push({m[v[i].first.first],l});\n }\n }\n while(!st.empty()){\n ans.push({m[st.top().first],st.top().second});\n st.pop();\n }\n while(!ans.empty()){\n auto t = ans.top();\n ans.pop();\n sol.push_back(t.second);\n }\n return sol;\n }\n};\n```\n\n```\n\n int int if if if set set OOO for for for EEEEE \n int int if if set set O O for E \n int int if if if set set O O for EEE \n int int if set set O O for E \n int int if set OOO for EEEEE \n```
2
0
['Hash Table', 'Stack', 'Heap (Priority Queue)', 'C++']
2
robot-collisions
Done using Stack + Sort in C++
done-using-stack-sort-in-c-by-srijan1543-x6wz
Intuition\nSince the problem requires us to keep track of all of the collisions so that we can get the final health array, we have to sort the positions of the
Srijan1543
NORMAL
2023-06-25T13:17:25.148338+00:00
2023-06-25T13:17:25.148368+00:00
59
false
# Intuition\nSince the problem requires us to keep track of all of the collisions so that we can get the final health array, we have to sort the positions of the robot and add the robot to a stack either by scanning from left to right (or) from right to left. Just before adding the robot in the stack , check for collision case where the direction is opposite and update the health array for each collisions. We generally use stack when there is frequent updates to be made. \n\n# Approach\nCreate a new array to keep track of the original index of the sorted postion array. In the following approach the data array has both position and original index, so we can still get the original index after sorting the data array. Now just create a stack to keep track of the previous robots. Here we are scanning from left to right so the collision case is when previous robot is moving right and current robot is moving left. We don\'t consider previous robot moving left and current moving to right since there is no collision between current and previous and the stack only stores the updated robots seen uptil now so previous moving to left won\'t lead to a collision case. We update the health array for each collision and we can finally scan the health array to get the non-zero values alone (this way we can get our final answer array to be in the same order as the health array)\n\n# Complexity\n- Time complexity:\nO(nlogn) due to sorting\n\n- Space complexity:\nO(n) since the data array requires O(n) space, and the space stack can contain at most n elements\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n vector<pair<int,int>> data;\n for(int i=0;i<positions.size();i++)\n {\n data.push_back({positions[i],i});\n }\n sort(data.begin(),data.end());\n stack<int> space;\n for(int i=0;i<data.size();i++)\n {\n int pos=data[i].first, index=data[i].second;\n if(!space.empty())\n {\n while(true && !space.empty())\n {\n int prev=space.top();\n if(directions[prev]==\'R\' && directions[index]==\'L\' && healths[index]!=0)\n {\n if(healths[index]==healths[prev]) \n {\n healths[index]=0;\n healths[prev]=0;\n space.pop();\n break;\n }\n else if(healths[index]>healths[prev])\n {\n space.pop();\n healths[index]--;\n healths[prev]=0;\n }\n else\n {\n healths[prev]--;\n healths[index]=0;\n if(healths[prev]==0) space.pop();\n break;\n }\n }\n else\n {\n break;\n }\n }\n\n if(healths[index]!=0) space.push(index);\n }\n else \n {\n space.push(index);\n }\n }\n vector<int> arr;\n for(int i=0;i<healths.size();i++)\n {\n if(healths[i]) arr.push_back(healths[i]);\n }\n return arr;\n }\n};\n```
2
0
['C++']
2
robot-collisions
🏆 Easiest & Simplest C++ 🔥Stack Only ✅ NO CLASS ❌
easiest-simplest-c-stack-only-no-class-b-ozym
ATLASSIAN 2023 INTERN Question\n# Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nSimple Just keep adding all robots goin
ayyusharma
NORMAL
2023-06-25T12:09:15.518793+00:00
2023-06-25T12:09:15.518817+00:00
226
false
**ATLASSIAN 2023 INTERN** Question\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSimple Just keep adding all robots going to R and when Robots goes to L, Just see if the health of robot at top having health less then equal to or higher then health at top. if equal simply set both healths to 0. else if the one having lesser health make it 0 and decrease other one by 1. Make sure to use While loop till health at top of stack index is not greater then current.\n\nYou Know what calculation is Just having bit calculation but toughest part is to recall healths in same order as given.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& pos, vector<int>& h, string d) {\n\n vector<pair<int,int>>v ;\n int n=pos.size() ;\n for(int i=0;i<n;i++) {\n \n v.push_back({pos[i],i}) ;\n }\n \n sort(v.begin(),v.end()) ;\n \n stack<int>st ;\n \n \n for(int i=0;i<n;i++) {\n int ind=v[i].second ;\n char dir=d[ind] ;\n \n if(dir==\'L\') \n {\n \n if(st.empty()) {\n st.push(ind) ; \n }\n else {\n \n if(d[st.top()]==\'R\' && h[st.top()] ==h[ind]) // when same health\n {\n h[st.top()]=0 ;\n st.pop() ;\n h[ind]=0 ;\n \n }\n else{ \n \n while(!st.empty() && d[st.top()]==\'R\' && h[st.top()] < h[ind] )\n {\n h[st.top()]=0 ;\n st.pop();\n h[ind]--;\n }\n // left robot moving in right direction and health is greater than curr robot\n if(!st.empty() && d[st.top()]==\'R\' && h[st.top()] > h[ind]) {\n h[st.top()]--; \n h[ind]=0 ;\n }\n // left robot moving in right direction and health is equal to curr robot\n else if(!st.empty() && d[st.top()]==\'R\' && h[st.top()] == h[ind]) {\n h[st.top()]=0; \n h[ind]=0 ;\n st.pop();\n }\n else{\n st.push(ind) ;\n }\n }\n \n }\n } \n // moving in right direction, collison is not possible with behind this robot\n else{\n st.push(ind) ; \n }\n }\n \n vector<int>ans;\n \n for(int x:h) {\n if(x >0) ans.push_back(x) ; \n }\n \n return ans;\n \n }\n};\n```
2
0
['Stack', 'Sorting', 'C++']
2
robot-collisions
[Javascript] Stack
javascript-stack-by-anna-hcj-npjl
Solution: Stack\n\nNote: The positions don\'t affect which robots will collide with each other, this stays the same no matter what. Robots adjacent to each othe
anna-hcj
NORMAL
2023-06-25T09:56:56.737082+00:00
2023-06-25T09:56:56.737107+00:00
133
false
**Solution: Stack**\n\nNote: The positions don\'t affect which robots will collide with each other, this stays the same no matter what. Robots adjacent to each other going right and left will always collide.\nIn the stack, keep track of robots we have processed so far that have still survived.\n\nIf the current robot is going left,\n* We need to eliminate all right-going robots with smaller health at the top of the stack, while decreasing the health of the current robot. \n* If the robot at the top of the stack is right-going and the health is greater, then remove the current robot and decrease the health of the robot at the top of the stack.\n* If the robot at the top of the stack is right-going and the health is the same, remove both.\n\nIf the current robot is going right, then just push it onto the stack to be dealt with later.\n\n`n = number of robots`\nTime Complexity: `O(n log(n))` \nSpace Complexity: `O(n)` \n```\nvar survivedRobotsHealths = function(positions, healths, directions) {\n let n = positions.length, stack = [], robots = [];\n for (let i = 0; i < n; i++) {\n robots.push({position: positions[i], health: healths[i], direction: directions[i], originalIndex: i})\n }\n robots.sort((a, b) => a.position - b.position); \n for (let i = 0; i < n; i++) {\n if (robots[i].direction === \'L\') {\n // remove right-going robots with smaller health from the top of the stack while decreasing the current robot\'s health\n while (stack.length && robots[stack[stack.length - 1]].direction === \'R\' && robots[stack[stack.length - 1]].health < robots[i].health) {\n stack.pop();\n robots[i].health--;\n }\n if (stack.length === 0 || robots[stack[stack.length - 1]].direction === \'L\') stack.push(i); // no more collisions, add current robot to stack\n else if (stack.length > 0 && robots[stack[stack.length - 1]].health === robots[i].health) stack.pop(); // health is same, remove both\n else if (stack.length > 0 && robots[stack[stack.length - 1]].health > robots[i].health) robots[stack[stack.length - 1]].health--; // right-going robot has greater health, remove current robot and decrease right-going robot\'s health\n } else {\n stack.push(i);\n }\n }\n return stack.sort((a, b) => robots[a].originalIndex - robots[b].originalIndex).map((i) => robots[i].health);\n};\n```
2
0
['JavaScript']
0
robot-collisions
Beautifully Explained CPP code, [Stack, Sorting]
beautifully-explained-cpp-code-stack-sor-jos7
Intuition\n Describe your first thoughts on how to solve this problem. \nAs we can see the problem we can see that there are few things that need to be concerne
DeathRidr007
NORMAL
2023-06-25T06:26:37.513541+00:00
2023-06-25T06:26:37.513574+00:00
180
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs we can see the problem we can see that there are few things that need to be concerned,\n1. The only way the robots will collide is robot from left side is moving towards right and the right side robot will move towrds left.\n2. If there is any collision then we have to go through 3 scenarios.\n - Health of both of the robots are equal\n In which we will remove both robots\n - Health of left side robot is greater than right side robot\n In which we have to ignore the right side robot,and decrement the health of left side robot by 1.\n - Health of right side robot is greater than left side robot.\n In which the left side robot will be removed, and after decrementing the health of right side robot, it will be moving in its direction.\n3. If there isn\'t any kind of collisions then its good to go.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst of all for simplicity of the problem we are going to sort the array according to their positions. and we are going to keep record of positions, health, index in positions, directions as below\n```\nElement = {position, {direction, {health, index in position}}}\n\n```\n\nHere, we are going to use here stack because of following reasons,\n- If we are going to remove the left side robot then we have to check for the condition in which right side robot can collide with previous robot of current left side robot. So, to keep track of that we have to use stack. \n(case : RRL)\n\n```\nnow while(!st.empty()) check that whether there is any possible collide with rightRobot or not,\nand if there is any collision then try to avoid that using below conditions.\n\nFor here we are going to have 3 coditions for collisions:\n1. if st.top().health == rightRobot.health\n st.pop() \n dont add the rightRobot\n2. if st.top().health > rightRobot.health\n decrement the health of left robot by 1\n and ignore the rightRobot as its destroyed\n3. if st.top().health < rightRobot.health\n firstly decerment rightRobot.health by 1\n And go to while loop again\n\n```\n\nNow after going through all the elements, we have to return the robots which have survived through collisions, So, we will copy their index and health from stack.\n\nSo, now we will sort them to get in the order of index. and then we will copy them into result vector.\n# Complexity\n- Time complexity: $$O(nlogn)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& health, string directions) {\n vector<pair<int, pair<char, pair<int, int>>>> arr;\n int n = positions.size();\n \n for(int i=0;i<n;i++){\n arr.push_back({positions[i], {directions[i],{health[i], i}}});\n }\n \n sort(arr.begin(), arr.end());\n \n stack<pair<int, pair<char, pair<int, int>>>> st;\n \n for(int i=0;i<n;i++){\n if(st.empty()) st.push(arr[i]);\n else{\n if(arr[i].second.first == \'L\'){\n bool take = true;\n while(!st.empty() && (st.top().second.first == \'R\' && arr[i].second.first == \'L\')){\n int health = st.top().second.second.first;\n if(health == arr[i].second.second.first){\n st.pop();\n take = false;\n break;\n }\n else{\n if(health > arr[i].second.second.first){\n st.top().second.second.first--;\n take = false;\n break;\n }else{\n arr[i].second.second.first--;\n st.pop();\n }\n }\n }\n if(take) st.push(arr[i]);\n }else{\n st.push(arr[i]);\n }\n }\n }\n \n vector<pair<int, int>> tmp;\n vector<int> res;\n \n while(!st.empty()){\n tmp.push_back({st.top().second.second.second, st.top().second.second.first});\n st.pop();\n }\n \n sort(tmp.begin(), tmp.end());\n \n for(auto it: tmp){\n res.push_back(it.second);\n }\n \n return res;\n }\n};\n```\n\nPlease upvote if you find it helpful & Best of Luck for your future : )
2
0
['Stack', 'Sorting', 'C++']
0
robot-collisions
[Java] Use Stack to Simulate, Clean Code
java-use-stack-to-simulate-clean-code-by-37fj
\nimport java.util.*;\n\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n =
xiangcan
NORMAL
2023-06-25T04:02:49.864671+00:00
2023-06-25T04:03:08.740283+00:00
590
false
```\nimport java.util.*;\n\nclass Solution {\n public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {\n int n = positions.length;\n int[] finalHealths = new int[n];\n Arrays.fill(finalHealths, -1);\n\n List<int[]> robots = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n robots.add(new int[]{positions[i], healths[i], i});\n }\n \n Collections.sort(robots, (a, b) -> a[0] - b[0]);\n\n Deque<int[]> left = new ArrayDeque<>();\n Deque<int[]> right = new ArrayDeque<>();\n\n for (int[] robot : robots) {\n if (directions.charAt(robot[2]) == \'R\') {\n right.push(robot);\n } else {\n while (!right.isEmpty()) {\n int[] rightRobot = right.peek();\n if (rightRobot[1] > robot[1]) {\n rightRobot[1]--;\n robot[1] = 0;\n break;\n } else if (rightRobot[1] < robot[1]) {\n rightRobot[1] = 0;\n robot[1]--;\n right.pop();\n } else {\n rightRobot[1] = 0;\n robot[1] = 0;\n right.pop();\n break;\n }\n }\n if (robot[1] > 0) {\n left.push(robot);\n }\n }\n }\n\n while (!right.isEmpty()) {\n int[] robot = right.pop();\n finalHealths[robot[2]] = robot[1];\n }\n\n while (!left.isEmpty()) {\n int[] robot = left.pop();\n finalHealths[robot[2]] = robot[1];\n }\n \n List<Integer> healthList = new ArrayList<>();\n for (int health : finalHealths) {\n if (health > 0) {\n healthList.add(health);\n }\n }\n \n return healthList;\n }\n}\n```
2
0
['Simulation', 'Java']
1
robot-collisions
Easiest Code | Sorting and Stack | Just do a simulation | C++ | Short Code
easiest-code-sorting-and-stack-just-do-a-swgq
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n
anmolbtw
NORMAL
2023-06-25T04:02:12.660810+00:00
2023-06-25T04:02:12.660839+00:00
125
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n=positions.size();\n vector<pair<int,pair<int,pair<int,char>>>> nums(n); //pos,ind,heal,dir\n for(int i=0;i<n;i++){\n nums[i]={positions[i],{i,{healths[i],directions[i]}}};\n }\n sort(nums.begin(),nums.end());\n stack<pair<int,pair<int,char>>> st; //ind,heal,dir\n vector<int> ans(n,-1);\n for(auto it:nums){\n int ind=it.second.first;\n int heal=it.second.second.first;\n char dir=it.second.second.second;\n if(dir==\'R\'){\n st.push({ind,{heal,dir}});\n }\n else{\n while(!st.empty() and st.top().second.second!=\'L\'){\n if(st.top().second.first>heal){\n st.top().second.first--;\n heal=0;\n break;\n }\n else if(st.top().second.first<heal){\n st.pop();\n heal--;\n }\n else{\n heal=0;\n st.pop();\n break;\n }\n }\n if(heal>0) st.push({ind,{heal,dir}});\n }\n }\n while(!st.empty()){\n ans[st.top().first]=st.top().second.first;\n st.pop();\n }\n vector<int> fin;\n for(auto it:ans){\n if(it!=-1) fin.push_back(it);\n }\n return fin;\n }\n};\n```
2
0
['C++']
0
robot-collisions
C#
c-by-adchoudhary-4fmq
Code
adchoudhary
NORMAL
2025-03-01T07:23:40.317225+00:00
2025-03-01T07:23:40.317225+00:00
3
false
# Code ```csharp [] public class Solution { public List<int> SurvivedRobotsHealths(int[] positions, int[] healths, string directions) { int n = positions.Length; List<int> result = new List<int>(); Stack<int> stack = new Stack<int>(); int[] indices = new int[n]; for (int index = 0; index < n; ++index) { indices[index] = index; } Array.Sort(indices, (lhs, rhs) => positions[lhs].CompareTo(positions[rhs])); foreach (int currentIndex in indices) { // Add right-moving robots to the stack if (directions[currentIndex] == 'R') { stack.Push(currentIndex); } else { while (stack.Count > 0 && healths[currentIndex] > 0) { // Pop the top robot from the stack for collision check int topIndex = stack.Pop(); // Top robot survives, current robot is destroyed if (healths[topIndex] > healths[currentIndex]) { healths[topIndex] -= 1; healths[currentIndex] = 0; stack.Push(topIndex); } else if (healths[topIndex] < healths[currentIndex]) { // Current robot survives, top robot is destroyed healths[currentIndex] -= 1; healths[topIndex] = 0; } else { // Both robots are destroyed healths[currentIndex] = 0; healths[topIndex] = 0; } } } } // Collect surviving robots for (int index = 0; index < n; ++index) { if (healths[index] > 0) { result.Add(healths[index]); } } return result; } } ```
1
0
['C#']
0
robot-collisions
easy optimized code faster
easy-optimized-code-faster-by-srivarsha1-17ng
IntuitionApproachComplexity Time complexity: Space complexity: Code
Srivarsha1901
NORMAL
2024-12-31T09:55:01.972615+00:00
2024-12-31T09:55:01.972615+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def survivedRobotsHealths(self, positions, healths, directions): robots = list(zip(positions, healths, directions, range(len(positions)))) robots.sort() stack = [] survivors = {} for pos, health, dir, index in robots: if dir == 'R': stack.append((health, index)) else: while stack: right_health, right_index = stack[-1] if right_health > health: stack[-1] = (right_health - 1, right_index) health = -1 break elif right_health < health: health -= 1 stack.pop() else: stack.pop() health = -1 break if health > 0: survivors[index] = health for health, index in stack: survivors[index] = health return [survivors[i] for i in range(len(positions)) if i in survivors] ```
1
0
['Python']
0
robot-collisions
python using stack and sort
python-using-stack-and-sort-by-tianwen08-ft8a
IntuitionTo solve this problem, I initially thought of simulating the movement of each robot based on their given direction while keeping track of their health.
tianwen0815
NORMAL
2024-12-28T23:55:27.609646+00:00
2024-12-28T23:55:27.609646+00:00
22
false
# Intuition To solve this problem, I initially thought of simulating the movement of each robot based on their given direction while keeping track of their health. It quickly becomes evident that robots moving towards each other can collide, and handling these collisions efficiently is crucial. # Approach - **Sort Robots by Position:** Start by sorting robots based on their positions. This allows us to process potential collisions in a sequential and logical order. - **Use a Stack for Tracking:** Employ a stack to keep track of robots that are still in motion. Robots moving right ('R') are pushed onto the stack. For a robot moving left ('L'), we check the stack for potential collisions with robots moving right. - **Handle Collisions:** When a left-moving robot encounters a right-moving robot from the stack: - Compare their health. The robot with lesser health is removed. If health is the same, both are removed. - Adjust health if one robot remains after the collision. - **Final Processing:** After all collisions are processed, the stack will contain the robots that survived, and their positions and health can be finalized. # Complexity - **Time Complexity:** The solution involves sorting the robots and then iterating through them, which typically would result in a time complexity of $O(n \log n)$, where $n$ is the number of robots. - **Space Complexity:** We use a stack to track the robots, and the maximum size of this stack would be $O(n)$, as in the worst case, we might need to hold all robots in the stack before any collisions occur. # Code ```python3 [] class Solution: def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]: pos2robot = {pos: idx + 1 for idx, pos in enumerate(positions)} stack = [] for position, health, direction in sorted(zip(positions, healths, directions)): while stack and stack[-1][2] == "R" and direction == "L": if stack[-1][1] == health: stack.pop() break elif stack[-1][1] > health: stack[-1][1] -= 1 break else: stack.pop() health -= 1 else: stack.append([position, health, direction]) pos_health = sorted([(pos2robot[position], health) for position, health, _ in stack]) return [health for _, health in pos_health] ```
1
0
['Python3']
0
robot-collisions
Beginner friendly ✅✅ Simple stack🔥Most simple solution🔥🔥
beginner-friendly-simple-stackmost-simpl-nk7r
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
gorilla_sriv
NORMAL
2024-10-17T19:22:42.408173+00:00
2024-10-17T19:22:42.408195+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\nvector<int> survivedRobotsHealths(vector<int>& pos, vector<int>& h, string dir) {\n stack<int> s;\n map<int, int> m;\n\n // Map position to index\n for (int i = 0; i < pos.size(); i++) {\n m[pos[i]] = i;\n }\n\n // Process each robot based on their position\n for (auto it = m.begin(); it != m.end(); ++it) {\n if (s.empty()) {\n s.push(it->second); // Push the first robot\n } \n else if (dir[s.top()] == \'R\' && dir[it->second] == \'L\') {\n // Handle collision\n while (!s.empty() && dir[s.top()] == \'R\' && dir[it->second] == \'L\') {\n if (h[s.top()] < h[it->second]) {\n // Top robot dies\n s.pop();\n h[it->second]--; // Decrease health of current robot\n } \n else if (h[s.top()] == h[it->second]) {\n // Both robots destroy each other\n s.pop(); // Remove top robot\n h[it->second] = 0; // Current robot also dies\n break;\n } \n else {\n // Current robot dies\n h[it->second] = 0;\n h[s.top()]--; // Decrease health of the top robot\n break;\n }\n }\n // Only push the current robot if it survived the collisions\n if (h[it->second] > 0) {\n s.push(it->second);\n }\n } \n else {\n s.push(it->second); // No collision, just push\n }\n }\n\n // Collect surviving robots\' healths\n vector<int> ans;\n while (!s.empty()) {\n if (h[s.top()] != 0) {\n ans.push_back(s.top()); // Push the index of surviving robots\n }\n s.pop();\n }\n\n // Sort by original position\n sort(ans.begin(), ans.end());\n \n // Replace indices with health values\n for (int i = 0; i < ans.size(); i++) {\n ans[i] = h[ans[i]];\n }\n\n return ans;\n}\n};\n```
1
0
['C++']
0
robot-collisions
Solution for robot-collisions
solution-for-robot-collisions-by-daniel_-d19x
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Daniel_Westheimer
NORMAL
2024-08-10T22:32:40.520986+00:00
2024-08-10T22:32:40.521012+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n * log n);\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n);\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Robot {\npublic:\n int position;\n int health;\n char direction;\n int orgPos;\n};\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n int n = positions.size();\n vector<Robot>robots(n);\n vector<int>res(n),finalRes;\n stack<Robot>s;\n for(int i = 0; i < n; i++){\n robots[i].position = positions[i];\n robots[i].health = healths[i];\n robots[i].direction = directions[i];\n robots[i].orgPos = i;\n }\n sort(robots.begin(),robots.end(),[](const Robot& a, const Robot& b) {\n return a.position < b.position;\n });\n for(Robot r : robots){\n if(r.direction == \'L\'){\n bool f = true;\n while(!s.empty()){\n if(r.health > s.top().health){\n s.pop();\n r.health--; \n }\n else if(r.health == s.top().health){f = false;s.pop();break;}\n else {s.top().health--;break;}\n }\n if(f && s.empty())res[r.orgPos] = r.health;\n }\n else s.push(r);\n }\n while(!s.empty()){\n res[s.top().orgPos] = s.top().health;\n s.pop();\n }\n for(int i : res)if(i>0)finalRes.push_back(i);\n return finalRes;\n }\n};\n```
1
0
['C++']
0
robot-collisions
C++ friendly Detailed Explanation + Clean code with Explanatory Comments
c-friendly-detailed-explanation-clean-co-bo4k
Intuition\nDirections are given. So, the very first thought came to my mind was to use a simple stack, but then realized positions are not sorted so directions
ichetancoding
NORMAL
2024-07-23T10:08:05.625920+00:00
2024-07-23T10:29:03.771340+00:00
10
false
# Intuition\nDirections are given. So, the very first thought came to my mind was to use a simple stack, but then realized positions are not sorted so directions don\'t actually make any sense.\n\n# Approach\nIf something is important, it\'s the positions, but we can\'t just directly sort the positions because we have to return the health of robots in the order they were given. So, I took the following approach:\n\n1. Combine positions, healths, and directions into a single vector and sort them by positions.\n2. Use a stack to simulate the collision process:\n - Robots moving right are pushed onto the stack.\n - Robots moving left check for collisions with robots moving right. If the robot moving left has more health, it decreases its health and continues, otherwise, it stops.\n3. Store the surviving robots\' healths in a map using their positions as keys.\n4. Construct the result by iterating through the original positions and collecting the healths from the map to maintain the original order.\n\n# Complexity\n- Time complexity: O(nlogn)\nSorting the robots by their positions takes \uD835\uDC42(\uD835\uDC5B log \uD835\uDC5B).\n\n\n- Space complexity: O(n)\nWe use additional space for the stack and map to store the robots information, both of which can hold up to n elements.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {\n // Number of robots\n int n = positions.size();\n \n // Vector to store the health of surviving robots\n vector<int> ans; \n\n // Vector to store robots with their position, health, and direction\n vector<pair<int, pair<int, char>>> robots; \n\n // Step 1: Populate the robots vector with position, health, and direction\n for (int i = 0; i < n; ++i) {\n robots.push_back({positions[i], {healths[i], directions[i]}});\n }\n\n // Step 2: Sort robots based on their positions\n sort(robots.begin(), robots.end());\n\n // Step 3: Use a stack to simulate the collision process\n stack<pair<int, pair<int, char>>> st;\n\n for (int i = 0; i < n; ++i) {\n // Get Position of the current robot \n int pos = robots[i].first; \n\n // Get Health of the current robot\n int health = robots[i].second.first; \n\n // Get Direction of the current robot\n char dir = robots[i].second.second; \n\n if (dir == \'R\') {\n /* If the current robot is moving to the right, \n push it onto the stack */\n st.push({pos, {health, dir}});\n } else {\n //We ar ein else part, \n //it means we have encountered a robot moving left,\n //So, simply we will see if we get any past robot, \n //who is moving towards right\n\n\n //We have used while loop and not if because,\n //we want to check all the weak robots,\n //moving towards right, so that our robot moving, \n //towards left can kill all of them one by one,\n\n while (!st.empty() && st.top().second.second == \'R\' && st.top().second.first < health) {\n \n // Pop the robot moving right\n st.pop(); \n \n // Decrease the health of the current robot\n health--; \n }\n\n if (!st.empty() && st.top().second.second == \'R\') {\n // If there\'s still a robot moving right on the stack\n if (st.top().second.first == health) {\n // If both robots have the same health, \n //they both destroy each other\n st.pop();\n } else {\n // If the robot moving right has more health, \n //decrease its health by 1\n st.top().second.first--;\n }\n } else {\n // If no more robots moving right are left,\n // or the stack is empty, \n //push the current robot onto the stack\n if (health > 0) {\n st.push({pos, {health, dir}});\n }\n }\n }\n }\n\n // Step 4: Collect the surviving robots\' healths\n \n // Map to store the surviving robots,\n // with their position and health\n map<int, int> survived; \n while (!st.empty()) {\n auto top = st.top();\n st.pop();\n\n // Store the health of the surviving robot\n survived[top.first] = top.second.first; \n }\n\n // Step 5: Construct the result in the original order\n for (int i = 0; i < n; ++i) {\n if (survived.find(positions[i]) != survived.end()) {\n // Add the health of the surviving robot,\n // to the answer\n ans.push_back(survived[positions[i]]); \n }\n }\n\n return ans; // Return the final result\n }\n};\n\n```\n\nVisit www.codeascript.in and look out for more such explanations.
1
0
['C++']
0