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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
time-based-key-value-store | C++ || Custom Binary Search Function || Easy to understand | c-custom-binary-search-function-easy-to-nz2tv | \nclass TimeMap {\npublic:\n unordered_map<string,vector<pair<int,string>>>mp;\n TimeMap() {\n \n }\n \n void set(string key, string value | puneet801 | NORMAL | 2022-10-06T08:00:45.677637+00:00 | 2022-10-06T08:00:45.677681+00:00 | 509 | false | ```\nclass TimeMap {\npublic:\n unordered_map<string,vector<pair<int,string>>>mp;\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back({timestamp,value});\n }\n \n pair<int,string> searchEqualOrLesser(vector<pair<int,string>>&arr, int key){\n int n = arr.size();\n int low = 0, high = n-1,res = INT_MAX;\n while(low <= high){\n int mid = low + (high - low)/2;\n if(arr[mid].first < key){\n res = mid;\n low = mid+1;\n }else if(arr[mid].first > key){\n high = mid - 1;\n }else{\n res = mid;\n break;\n }\n }\n if(res == INT_MAX){\n return {INT_MAX,""};\n }\n return arr[res];\n }\n \n string get(string key, int timestamp) {\n pair<int,string> p = searchEqualOrLesser(mp[key],timestamp);\n if(p.first == INT_MAX){\n return "";\n }\n return p.second;\n }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n``` | 5 | 0 | ['C', 'Binary Tree'] | 1 |
time-based-key-value-store | unordered map and upper bound | unordered-map-and-upper-bound-by-aniketp-r99r | \nclass TimeMap {\npublic:\n unordered_map<string,map<int,string> > um;\n TimeMap() {\n \n }\n \n void set(string key, string value, int t | aniketpawar | NORMAL | 2022-10-06T06:31:48.581864+00:00 | 2022-10-06T06:31:48.581932+00:00 | 137 | false | ```\nclass TimeMap {\npublic:\n unordered_map<string,map<int,string> > um;\n TimeMap() {\n \n }\n \n void set(string key, string value, int ts) {\n um[key][ts]=value;\n }\n \n string get(string key, int ts) {\n if(um.find(key)==um.end())return "";\n auto it=um[key].upper_bound(ts);\n if(it==um[key].begin())return "";\n return (--it)->second;\n }\n};\n``` | 5 | 0 | [] | 0 |
time-based-key-value-store | [Typescript/Javascript] Binary Search + Hashmap | typescriptjavascript-binary-search-hashm-kr24 | Use map to store list of \'datums\' (value and timestamp).\nDescription says timestamps are set in increasing order, so that is hint to use binary search.\n\nIn | weakhero | NORMAL | 2022-04-16T15:36:50.758522+00:00 | 2024-09-21T17:54:20.818972+00:00 | 649 | false | Use map to store list of \'datums\' (value and timestamp).\nDescription says timestamps are set in increasing order, so that is hint to use binary search.\n\nIn a list of timestamps, given a target timestamp, we want to find the \'datum.timestamp\' <= timestamp. \nOnce our datum.timestamp <= timestamp (within the correct range), we optimise the `ans` by gradually increasing `l = m + 1`.\n\n\n```\ntype Datum = {\n value: string\n timestamp: number\n};\n\nclass TimeMap {\n map: Map<string, Array<Datum>>;\n\n constructor() {\n this.map = new Map<string, Array<Datum>>();\n }\n\n set(key: string, value: string, timestamp: number): void {\n const datums = this.map.get(key) || [];\n datums.push({ value, timestamp });\n this.map.set(key, datums)\n\n }\n\n get(key: string, timestamp: number): string {\n const datums = this.map.get(key) || [];\n return this.search(timestamp, datums);\n }\n\n search(timestamp: number, datums: Array<Datum>): string {\n let l = 0, u = datums.length - 1, ans = "";\n\n while (l <= u) {\n const m = l + Math.floor((u - l) / 2);\n const { value, timestamp: timestamp_prev } = datums[m];\n if (timestamp_prev <= timestamp) {\n ans = value;\n l = m + 1\n } else {\n u = m - 1\n }\n }\n\n return ans;\n }\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * var obj = new TimeMap()\n * obj.set(key,value,timestamp)\n * var param_2 = obj.get(key,timestamp)\n */\n ``` | 5 | 0 | ['Binary Tree', 'TypeScript', 'JavaScript'] | 0 |
time-based-key-value-store | C# | Built in BinarySearch method for lists & maps | 97% | c-built-in-binarysearch-method-for-lists-s2a4 | Very good question! I learned alot about the BinarySearch method for Lists in C#. Very useful so you don\'t have to imlpement binary search from scratch and ris | sms009 | NORMAL | 2021-10-12T21:20:22.791707+00:00 | 2021-10-12T21:20:22.791735+00:00 | 256 | false | Very good question! I learned alot about the ```BinarySearch``` method for ```Lists``` in C#. Very useful so you don\'t have to imlpement binary search from scratch and risk error/debugging time.\n\nHighly recommend reading: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.binarysearch?view=net-5.0#System_Collections_Generic_List_1_BinarySearch__0_System_Collections_Generic_IComparer__0__\n\nTo learn about the ```BinarySearch``` method.\n\n```\npublic class TimeMap {\n\n Dictionary<string, List<Tuple<int, string>>> cache;\n \n public TimeMap() \n {\n cache = new Dictionary<string, List<Tuple<int, string>>>(); \n }\n \n public void Set(string key, string value, int timestamp) \n {\n \n if(!cache.ContainsKey(key))\n {\n cache.Add(key, new List<Tuple<int, string>>());\n }\n \n cache[key].Add(new Tuple<int, string>(timestamp, value));\n }\n \n public string Get(string key, int timestamp) \n {\n var answer = "";\n \n if(cache.ContainsKey(key))\n {\n \n if(timestamp > cache[key][cache[key].Count - 1].Item1)\n {\n answer = cache[key][cache[key].Count - 1].Item2; \n }\n else if(timestamp < cache[key][0].Item1)\n {\n return answer;\n }\n else\n {\n\n var indexOfItem = cache[key].BinarySearch(new Tuple<int, string>(timestamp,key), new BinarySearchComparer());\n\n if(indexOfItem < 0) //wasn\'t found\n {\n var complement = ~indexOfItem;\n \n if(complement == cache[key].Count) //means that there\'s no item bigger than what was searched for, return ""\n {\n return answer;\n }\n \n answer = cache[key][complement - 1].Item2; \n //complement - 1 because of how BinarySearch works : \n /* \n The zero-based index of item in the sorted List<T>, if item is found; otherwise, \n a negative number that is the bitwise complement of the index of the next element that is larger than item or, \n if there is no larger element, the bitwise complement of Count.\n */\n \n return answer;\n }\n\n answer = cache[key][indexOfItem].Item2; \n }\n }\n \n return answer;\n }\n \n}\n\npublic class BinarySearchComparer : IComparer<Tuple<int, string>>\n{\n public int Compare(Tuple<int, string> a, Tuple<int, string> b)\n {\n return a.Item1.CompareTo(b.Item1);\n }\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.Set(key,value,timestamp);\n * string param_2 = obj.Get(key,timestamp);\n */\n``` | 5 | 0 | ['Binary Tree'] | 2 |
time-based-key-value-store | Simple Java solution using Map of TreeMaps | simple-java-solution-using-map-of-treema-gckc | ```\nclass TimeMap {\n \n Map> map;\n\n /* Initialize your data structure here. /\n public TimeMap() {\n map = new HashMap<>();\n }\n \ | crisa | NORMAL | 2021-05-18T03:54:51.903427+00:00 | 2021-05-18T03:54:51.903472+00:00 | 327 | false | ```\nclass TimeMap {\n \n Map<String, TreeMap<Integer, String>> map;\n\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n TreeMap<Integer, String> values = map.getOrDefault(key, new TreeMap<>());\n values.put(timestamp, value);\n map.put(key, values);\n }\n \n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) return "";\n Integer valueKey = map.get(key).floorKey(timestamp);\n if (valueKey == null) return "";\n return map.get(key).get(valueKey);\n }\n} | 5 | 0 | [] | 0 |
time-based-key-value-store | JavaScript solution [96, 61] | Binary Search | Clean | javascript-solution-96-61-binary-search-bzkiy | I spent more time writing binary search algorithm than anyting else. That\'s where started to regret that JS misses binary search method on arrays.\n\nRuntime: | i-love-typescript | NORMAL | 2021-03-24T03:05:03.038105+00:00 | 2021-03-24T03:06:32.097395+00:00 | 902 | false | I spent more time writing binary search algorithm than anyting else. That\'s where started to regret that JS misses binary search method on arrays.\n\nRuntime: 404 ms, faster than 96.55% of JavaScript online submissions for Time Based Key-Value Store.\nMemory Usage: 79.4 MB, less than 61.49% of JavaScript online submissions for Time Based Key-Value Store.\n\n```\nclass TimeMap {\n constructor() {\n this.map = new Map()\n this.searchTimestamp = (arr, timestamp) => {\n let l = 0, r = arr.length - 1\n while (l <= r) {\n const mid = Math.floor((l + r) / 2)\n if (arr[mid].timestamp === timestamp) return mid\n l = arr[mid].timestamp < timestamp ? mid + 1 : l\n r = arr[mid].timestamp > timestamp ? mid - 1 : r\n }\n return -l -1\n }\n } \n \n set(key, value, timestamp) {\n const arr = this.map.get(key) || []\n arr.push({ value, timestamp })\n this.map.set(key, arr)\n }\n \n get(key, timestamp) {\n const arr = this.map.get(key)\n if (!arr) return \'\'\n const index = this.searchTimestamp(arr, timestamp)\n if (index === -1) return \'\'\n if (index >= 0) return arr[index].value\n // Use previous value from the collection\n return arr[-index-2].value\n }\n}\n``` | 5 | 1 | ['JavaScript'] | 1 |
time-based-key-value-store | Python Bisect | python-bisect-by-wsy19970125-3y4b | \tclass TimeMap:\n\n\t\tdef init(self):\n\t\t\t"""\n\t\t\tInitialize your data structure here.\n\t\t\t"""\n\t\t\tself.d = defaultdict(list)\n\n\t\tdef set(self, | wsy19970125 | NORMAL | 2020-07-08T00:05:53.617328+00:00 | 2020-07-08T00:05:53.617357+00:00 | 254 | false | \tclass TimeMap:\n\n\t\tdef __init__(self):\n\t\t\t"""\n\t\t\tInitialize your data structure here.\n\t\t\t"""\n\t\t\tself.d = defaultdict(list)\n\n\t\tdef set(self, key: str, value: str, timestamp: int) -> None:\n\t\t\tself.d[key].append((timestamp, value))\n\n\n\t\tdef get(self, key: str, timestamp: int) -> str:\n\t\t\tindex = bisect.bisect(self.d[key], (timestamp + 1, \'\'))\n\t\t\tif index == 0:\n\t\t\t\treturn \'\'\n\t\t\telse:\n\t\t\t\treturn self.d[key][index - 1][1] | 5 | 0 | [] | 1 |
time-based-key-value-store | C++ Solution with inline code explanation | c-solution-with-inline-code-explanation-ig7rq | \nclass TimeMap {\npublic:\nunordered_map<string, map<int, string>> time_map;\n \n /** Initialize your data structure here. */\n TimeMap() {\n \ | linlin0208 | NORMAL | 2020-04-12T21:10:28.708455+00:00 | 2020-04-12T21:10:28.708489+00:00 | 393 | false | ```\nclass TimeMap {\npublic:\nunordered_map<string, map<int, string>> time_map;\n \n /** Initialize your data structure here. */\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n // use hash map to lookup ordered {timestamp, value} pairs by key in O(1).\n time_map[key].insert({ timestamp, value });\n }\n \n string get(string key, int timestamp) {\n auto exist = time_map.find(key) != time_map.end();\n if (!exist) {\n return "";\n }\n \n // use binary search to find the value with a timestamp greater the requested one.\n auto it = time_map[key].upper_bound(timestamp);\n auto minimum_it = time_map[key].begin();\n \n // if the first item with greater timestamp is equal to the first item in the time_map[key]\n // it means there is no value with a timestamp less than or equal to the requestd one \n if (it == minimum_it) {\n return "";\n }\n \n // return an item with the largest timestamp\n return prev(it)->second;\n }\n};\n``` | 5 | 0 | [] | 0 |
time-based-key-value-store | Javascript beat 100% solution. | javascript-beat-100-solution-by-jay_tsz_-rd13 | \nclass TimeMap{\n constructor(){\n this.map = {};\n }\n\n set(key, value, timestamp){\n if(!this.map[key]) this.map[key]= [];\n t | jay_tsz_wai | NORMAL | 2019-02-12T07:38:45.543458+00:00 | 2019-02-12T07:38:45.543525+00:00 | 866 | false | ```\nclass TimeMap{\n constructor(){\n this.map = {};\n }\n\n set(key, value, timestamp){\n if(!this.map[key]) this.map[key]= [];\n this.map[key].push({timestamp:timestamp, value:value});\n }\n\n get(key, timestamp){\n if(!this.map[key]) return undefined;\n return this.binarySearch(this.map[key],timestamp);\n }\n\n binarySearch(list ,timeStamp){\n if(list.length === 1)return list[0].value;\n let l = 0 , r = list.length-1;\n let mid;\n while(l<=r){\n mid = Math.floor ((l+r)/2);\n if(list[mid].timestamp === timeStamp )return list[mid].value;\n if(timeStamp < list[mid].timestamp) r = mid -1;\n else{\n l = mid+1;\n }\n }\n return list[mid].timestamp < timeStamp ? list[mid].value : list[mid-1]? list[mid-1].value: \'\';\n }\n}\n``` | 5 | 1 | [] | 2 |
time-based-key-value-store | C++ || Binary Search || HashMap | c-binary-search-hashmap-by-190111052008-o1bh | Intuition\nThe problem involves storing values with timestamps for different keys, and we need to retrieve the value that corresponds to a particular timestamp | 190111052008 | NORMAL | 2024-09-11T11:05:07.771665+00:00 | 2024-09-18T03:18:36.124502+00:00 | 505 | false | # Intuition\nThe problem involves storing values with timestamps for different keys, and we need to retrieve the value that corresponds to a particular timestamp for a given key. To solve this, we can use an `unordered_map`, where each key is a `string`, and the value is a dynamic array (`vector`) of pairs. Each pair contains a timestamp and the corresponding value.\n\n# Approach\n1. We initialize an `unordered_map` where the `key` is a `string`, and the `value` is a `vector` that stores pairs of `timestamps` and `values` (`pair<int, string>`). \n2. In the `set()` function, we store the value with its timestamp by adding the pair `{timestamp, value}` to the vector corresponding to the key in the map.\n3. For the `get()` function, we want to find the value associated with a given key and timestamp. To do this efficiently, we use a **binary search** on the vector of `{timestamp, value}` pairs.\n4. We directly reference the vector associated with the key in the map and perform binary search. This search is similar to the method used when inserting a value into the correct position in a sorted array. We look for the largest timestamp that is less than or equal to the given timestamp.\n\n# Complexity\n- Time complexity:\n1. The set() function runs in O(1) on average for inserting elements into the unordered_map.\n2. The get() function performs a binary search, which has a time complexity of O(log n), where n is the number of timestamps for a given key.\n\n- Space complexity:\nThe space complexity is O(n), where n is the total number of key-value pairs stored.\n\n# Code\n```cpp []\nclass TimeMap {\npublic:\n typedef pair<int, string> pis;\n unordered_map<string, vector<pis>> map;\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n map[key].push_back({timestamp, value});\n }\n \n string get(string key, int timestamp) {\n const vector<pis>& temp = map[key];\n\n int lo=0, hi=temp.size()-1; string ans="";\n while(lo <= hi){\n int mid = lo + (hi-lo)/2;\n\n if(temp[mid].first == timestamp){\n return temp[mid].second;\n }\n else if(temp[mid].first < timestamp){\n ans = temp[mid].second;\n lo = mid+1;\n }\n else{\n hi = mid-1;\n }\n }\n return ans;\n }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n```\n\n**PS**: Upvote if you like the solution !!! | 4 | 0 | ['String', 'Binary Search', 'C++'] | 0 |
time-based-key-value-store | Simple C++ Code || using Hash-Map || Faster than 90%+ users | simple-c-code-using-hash-map-faster-than-w70p | 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 | vishal_0410 | NORMAL | 2023-09-16T22:36:53.985455+00:00 | 2023-09-16T22:36:53.985484+00:00 | 322 | 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 TimeMap {\npublic:\n map<string,map<int,string>>mp;\n TimeMap() {\n mp=map<string,map<int,string>>();\n }\n \n void set(string key, string value, int time) {\n mp[key].insert({-1*time,value});\n }\n \n string get(string key, int time) {\n if(mp.find(key)==mp.end()) return "";\n\n auto it=mp[key].lower_bound(-1*time);\n\n if(it==mp[key].end()) return "";\n\n return it->second;\n }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n``` | 4 | 0 | ['Hash Table', 'String', 'Binary Search', 'Design', 'C++'] | 1 |
time-based-key-value-store | c++ || hash map || | c-hash-map-by-adroitabhi205-xtn0 | The idea is simple and straight forward. \nstore the key,timestam,value in map \nIn the get function use a loop from the asked time stamp till 1 and check if we | adroitabhi205 | NORMAL | 2022-10-06T03:21:06.992263+00:00 | 2022-10-06T03:21:06.992305+00:00 | 1,304 | false | The idea is simple and straight forward. \nstore the key,timestam,value in map \nIn the get function use a loop from the asked time stamp till 1 and check if we find any value in the map[key] then return that one only. \nif the loop does not return any value then return empty string. \n\n\n**c++ code**\n```\nclass TimeMap {\n unordered_map<string,unordered_map<int,string>>storage;\n \npublic:\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n storage[key][timestamp]=value;\n }\n \n string get(string key, int timestamp) {\n for(int t=timestamp;t>0;t--){\n if(storage[key].find(t)!=storage[key].end())return storage[key][t];\n }\n return "";\n }\n}; ``` | 4 | 1 | ['Hash Table', 'C'] | 1 |
time-based-key-value-store | Java | treemap | binary search | java-treemap-binary-search-by-conchwu-bsay | List + binary search\n\n\t//Runtime: 181 ms, faster than 87.71% of Java online submissions for Time Based Key-Value Store.\n //Memory Usage: 117.3 MB, less t | conchwu | NORMAL | 2022-10-06T01:31:16.359896+00:00 | 2022-10-06T01:31:43.981963+00:00 | 556 | false | # List + binary search\n```\n\t//Runtime: 181 ms, faster than 87.71% of Java online submissions for Time Based Key-Value Store.\n //Memory Usage: 117.3 MB, less than 91.94% of Java online submissions for Time Based Key-Value Store.\n //List + binary search\n // If M is the number of set function calls\n // N is the number of get function calls\n // L is average length of key and value strings.\n class TimeMap{\n\n //Space: O(M * L)\n Map<String, List<Pair<Integer, String>>> map;\n public TimeMap() {\n map = new HashMap<>();\n }\n\n //Time: O(M * L) <<< M calls\n public void set(String key, String value, int timestamp) {\n map.computeIfAbsent(key, k -> new ArrayList<>()).add(new Pair<>(timestamp, value));\n }\n\n //Time: O(N * L * LogM) <<< N calls\n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) return "";\n List<Pair<Integer, String>> list = map.get(key);\n int idx = Collections.binarySearch(list, new Pair<>(timestamp, ""), Comparator.comparingInt(Pair::getKey));\n if (idx == -1) return "";\n if (idx < 0) idx = Math.abs(idx) - 2;\n return list.get(idx).getValue();\n }\n }\n\n```\n# TreeMap\n```\n //Runtime: 158 ms, faster than 96.18% of Java online submissions for Time Based Key-Value Store.\n //Memory Usage: 117.5 MB, less than 89.86% of Java online submissions for Time Based Key-Value Store.\n //TreeMap\n // If M is the number of set function calls\n // N is the number of get function calls\n // L is average length of key and value strings.\n class TimeMap_treeMap{\n\n //Space: O(M * L)\n Map<String, TreeMap<Integer, String>> map;\n public TimeMap_treeMap() {\n map = new HashMap<>();\n }\n\n //Time: O(M * L * LogM) <<< M calls\n public void set(String key, String value, int timestamp) {\n map.computeIfAbsent(key, k ->new TreeMap<>()).put(timestamp, value);\n }\n\n //Time: O(N * L * LogM) <<< N calls\n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) return "";\n Map.Entry<Integer, String> entry = map.get(key).floorEntry(timestamp);\n return entry == null ? "" : entry.getValue();\n }\n }\n``` | 4 | 0 | ['Binary Search', 'Tree', 'Java'] | 0 |
time-based-key-value-store | 🗓️ Daily LeetCoding Challenge October, Day 6 | daily-leetcoding-challenge-october-day-6-rwcj | This problem is the Daily LeetCoding Challenge for October, Day 6. Feel free to share anything related to this problem here! You can ask questions, discuss what | leetcode | OFFICIAL | 2022-10-06T00:00:29.071475+00:00 | 2022-10-06T00:00:29.071570+00:00 | 3,184 | false | This problem is the Daily LeetCoding Challenge for October, Day 6.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/time-based-key-value-store/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain this 0 approach in the official solution</summary>
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 4 | 0 | [] | 31 |
time-based-key-value-store | C++|| Using Hashmap and Binary Search Approach || easy-understanding code | c-using-hashmap-and-binary-search-approa-n026 | \ntypedef pair<int, string> pis;\nclass TimeMap {\npublic:\n unordered_map<string, vector<pis>> m; \n TimeMap() {\n \n }\n \n string great | HereToRule | NORMAL | 2022-08-12T11:36:08.823105+00:00 | 2022-08-12T11:36:08.823149+00:00 | 307 | false | ```\ntypedef pair<int, string> pis;\nclass TimeMap {\npublic:\n unordered_map<string, vector<pis>> m; \n TimeMap() {\n \n }\n \n string greatestValLessThan(int timestamp, vector<pis>& s){\n int start = 0;\n int end = s.size()-1;\n int ans = INT_MIN;\n string str = "";\n while(start <= end){\n int middle = start + ((end-start)/2);\n auto x = s[middle];\n int num = x.first;\n string str_temp = x.second;\n if(num > timestamp){\n end = middle -1;\n }\n else{\n if(num > ans){\n str = str_temp;\n ans = num;\n }\n start = middle+1;\n }\n }\n return str;\n }\n \n void set(string key, string value, int timestamp) {\n m[key].push_back({timestamp,value}); \n }\n \n string get(string key, int timestamp) {\n \n string ans = "";\n ans = greatestValLessThan(timestamp,m[key]);\n return ans;\n }\n \n};\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n``` | 4 | 0 | ['C', 'Binary Tree'] | 0 |
time-based-key-value-store | Binary Search + Hashmap Solution in Python, Very Easy to Understand!!! | binary-search-hashmap-solution-in-python-ojii | Read carefully and you will find that it is actually a search question combined with hashmap!\n\nUse binary search!\nThe question actually asks us to find out t | GeorgePot | NORMAL | 2022-05-13T18:46:37.930862+00:00 | 2022-05-13T18:46:37.930887+00:00 | 498 | false | Read carefully and you will find that it is actually a **search question** combined with **hashmap**!\n\nUse **binary search**!\nThe question actually asks us to find out **the largest number that is smaller or equal to some target value**.\n\nInitiate a **map**, storing (key, [(time1, value1), (time2, value2), ...]\nWhen get, do the binary search based on timestamps, return the associated value.\n\n**Time:**\nset: O(1)\nget: O(lgn)\n**Space:**\nO(n)\n\n```\nclass TimeMap:\n\n def __init__(self):\n self.mapping = collections.defaultdict(list)\n \n def set(self, key, value, timestamp):\n self.mapping[key].append((timestamp, value))\n \n def get(self, key, timestamp):\n \n values = self.mapping[key]\n if not values:\n return \'\'\n \n left, right = 0, len(values) - 1\n while left + 1 < right:\n mid = (left + right) // 2\n pre_time, value = values[mid]\n if pre_time == timestamp:\n return value\n if pre_time > timestamp:\n right = mid\n else:\n left = mid\n if values[right][0] <= timestamp:\n return values[right][1]\n if values[left][0] <= timestamp:\n return values[left][1]\n \n return \'\'\n``` | 4 | 0 | ['Binary Tree', 'Python'] | 1 |
time-based-key-value-store | Python with bisect with one dict, easy to understand | python-with-bisect-with-one-dict-easy-to-z4q1 | \nfrom collections import defaultdict\nfrom bisect import bisect_right\nclass TimeMap:\n\n def __init__(self):\n self.tm = defaultdict(list)\n | mayankanand | NORMAL | 2022-04-18T08:05:49.942708+00:00 | 2022-04-18T08:05:49.942751+00:00 | 237 | false | ```\nfrom collections import defaultdict\nfrom bisect import bisect_right\nclass TimeMap:\n\n def __init__(self):\n self.tm = defaultdict(list)\n \n def set(self, key: str, value: str, timestamp: int) -> None:\n self.tm[key].append((timestamp, value))\n\n def get(self, key: str, timestamp: int) -> str:\n # gives the index of the *next* element after the given timestamp\n idx = bisect_right(a=self.tm[key], x=timestamp, key=lambda x: x[0])\n \n # if index is zero then there is no kv pair within the given timestamp\n if idx > 0:\n return self.tm[key][idx-1][1]\n else:\n return ""\n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n``` | 4 | 0 | ['Binary Tree', 'Python'] | 0 |
time-based-key-value-store | Python: Using Dict and Binary Search | python-using-dict-and-binary-search-by-b-p20m | Create a dictionary of key => List of (timestamp, value)\nFor e.g: "foo" => [(1,"bar"), (5,"bar2")]\n\n"constantly increasing" property of timestamps makes inse | benslie | NORMAL | 2021-12-23T20:04:45.433839+00:00 | 2021-12-23T20:04:45.433880+00:00 | 656 | false | Create a dictionary of key => List of (timestamp, value)\nFor e.g: "foo" => [(1,"bar"), (5,"bar2")]\n\n"constantly increasing" property of timestamps makes insertion in "set" operation easy by just appending the values in the list. \n\nAs the list is sorted, use binary search to get the value in O(logn) time. \nTime taken for get: O(1) to find the key, O(logn) to get the value => O(logn)\nTime taken for set: O(1) for insertion in a list\n\n```\nfrom collections import defaultdict\nfrom typing import Dict, List, Tuple\nclass TimeMap:\n\n def __init__(self):\n self.time_map: Dict[str,List[Tuple]] = defaultdict(list) \n \n\n def get_value(self, key: str, timestamp: int):\n arr = self.time_map[key]\n low = 0\n high = len(arr) - 1\n while low <=high:\n mid = (low + high)//2\n if timestamp >= arr[mid][0] and timestamp < arr[mid+1][0]:\n return arr[mid][1]\n elif timestamp < arr[mid][0]:\n high = mid - 1\n else:\n low = mid + 1\n return ""\n \n \n def set(self, key: str, value: str, timestamp: int) -> None:\n self.time_map[key].append((timestamp, value))\n\n def get(self, key: str, timestamp: int) -> str:\n if key not in self.time_map:\n return ""\n else:\n if timestamp < self.time_map[key][0][0]:\n return ""\n elif timestamp >= self.time_map[key][-1][0]:\n return self.time_map[key][-1][1]\n else:\n return self.get_value(key, timestamp)\n \n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n``` | 4 | 0 | ['Binary Tree', 'Python'] | 1 |
time-based-key-value-store | [python] binary search (82% faster) | python-binary-search-82-faster-by-mooris-cyca | \nclass TimeMap:\n\n def __init__(self):\n """\n Initialize your data structure here\n """\n self.d = collections.defaultdict(lis | moorissa | NORMAL | 2021-06-28T23:39:47.967937+00:00 | 2021-06-28T23:39:47.967987+00:00 | 597 | false | ```\nclass TimeMap:\n\n def __init__(self):\n """\n Initialize your data structure here\n """\n self.d = collections.defaultdict(list)\n\n\n def set(self, key: str, value: str, timestamp: int) -> None: # O(1)\n self.d[key].append((timestamp, value))\n \n\n def get(self, key: str, timestamp: int) -> str: # -- O(logN)\n # base case\n if key not in self.d or not self.d:\n return ""\n \n # key exists, check valid timestamps\n lst = self.d[key]\n if lst[-1][0] <= timestamp:\n return lst[-1][1]\n if lst[0][0] > timestamp:\n return ""\n \n # otherwise, we perform binary search to find the timestamp\n L, R = 0, len(lst) -1\n while L<R:\n mid=L+(R-L)//2\n t = lst[mid][0]\n if timestamp == t:\n return lst[mid][1]\n if timestamp > t:\n L = mid+1\n else:\n R = mid\n\n return lst[L-1][1] \n```\n### Complexity\ntime: O(logN) where N is number of keys in `get` function. `set` only takes O(1)\nspace: O(N) as we create data structure for all elements inserted\n | 4 | 0 | ['Binary Tree', 'Python'] | 1 |
time-based-key-value-store | easy to understand hash map/ priority queue beats 99%. every detail commented :) | easy-to-understand-hash-map-priority-que-yjcq | //Idea is to maintain a hashmap of the key value pairs, but each key has a max heap as its value. This takes care of both having multiple values \n//mapped to a | aag479 | NORMAL | 2021-05-02T04:20:46.867099+00:00 | 2021-05-02T04:20:46.867133+00:00 | 922 | false | //Idea is to maintain a hashmap of the key value pairs, but each key has a max heap as its value. This takes care of both having multiple values \n//mapped to a key and efficiently returning the one with the most recent timestamp. I use a "timestamp" object which stores both the actual value and the timestamp\n//the object implements javas comparable interface (an alternative would be to use a custom comparator in the constructor of the heap - either works) so that they are\n//automatically ordered by decreasing timestamp (highest timestamp at top). Then when we get a key, we keep popping from the heap while the value of the top element is \n//strictly greater than the value of the timestamp were looking for. We need to keep these values in a temporary list to add back to the heap in case they are looked up \n//in a later call. In the case that the timestamp is less than ALL values for the key, we return an empty string. \n```\nclass TimeMap {\n Map<String,Queue<TimeStamp>> map;\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n //instantiate a timestamp object with the time and the value.\n TimeStamp ts = new TimeStamp(timestamp,value);\n if(map.containsKey(key)){\n Queue<TimeStamp> current = map.get(key);\n //if we have seen this key before at to its queue.\n current.add(ts);\n map.put(key,current);\n }\n else{\n //if we havent seen it, add it and create a new queue with its value.\n //default ordering of priority queue in java is minheap, use collections to fix this.\n Queue<TimeStamp> current = new PriorityQueue<>(Collections.reverseOrder());\n current.add(ts);\n map.put(key, current);\n }\n }\n \n public String get(String key, int timestamp) {\n //this key is not found.\n if(!map.containsKey(key)){\n return "";\n }\n else{\n Queue<TimeStamp> current = map.get(key);\n List<TimeStamp> copy = new ArrayList<>();\n //search for greatest timestamp less than or equal to the one we are looking for.\n while(!current.isEmpty() && current.peek().time > timestamp){\n //copy the elements that we have popped to re add them later.\n copy.add(current.poll());\n }\n //while loop breaks at first time stamp less than or equal to our timestamp. return current.peek UNLESS the queue is empty which means every time stamp \n //was greater. In this case return empty string.\n String val = current.isEmpty() ? "" : current.peek().value;\n //add back values we popped in our search.\n current.addAll(copy);\n return val;\n }\n \n }\n}\nclass TimeStamp implements Comparable<TimeStamp>{\n //timestamp object maintains both time and value.\n public int time; \n public String value;\n TimeStamp(int time, String value){\n this.time=time;\n this.value=value;\n }\n //compare the nodes based on time so that the heap will be ordered correctly. This is an interface in Java, if not clear research comparable interface.\n public int compareTo(TimeStamp t ){\n if(this.time==t.time){\n return 0;\n }\n else{\n return this.time > t.time ? 1 : -1;\n }\n }\n \n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */ | 4 | 0 | ['Heap (Priority Queue)', 'Java'] | 1 |
time-based-key-value-store | Java Binary Search | java-binary-search-by-vikrant_pc-262d | \nclass TimeMap {\n Map<String, List<TimeValue>> map;\n\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap<> | vikrant_pc | NORMAL | 2021-03-06T07:10:39.619092+00:00 | 2021-03-06T07:10:39.619126+00:00 | 342 | false | ```\nclass TimeMap {\n Map<String, List<TimeValue>> map;\n\n /** Initialize your data structure here. */\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n map.putIfAbsent(key, new ArrayList<>());\n map.get(key).add(new TimeValue(value, timestamp));\n }\n \n public String get(String key, int timestamp) {\n List<TimeValue> list = map.get(key);\n if(list == null || timestamp < list.get(0).timestamp) return "";\n int start =0, end =list.size() - 1 , mid;\n while (start < end) {\n mid = (start + end + 1) / 2;\n if(list.get(mid).timestamp > timestamp) end = mid-1;\n else start = mid;\n }\n return list.get(end).value;\n }\n}\n\nclass TimeValue {\n int timestamp;\n String value;\n public TimeValue(String value, int timestamp) {\n this.timestamp = timestamp;\n this.value = value;\n }\n}\n``` | 4 | 0 | [] | 1 |
time-based-key-value-store | C++ std::unordered_map + std::upper_bound | c-stdunordered_map-stdupper_bound-by-igo-6yxi | \nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n unordered_map<string, vector<pair<string, int>>> mp; // [key, vec[val, time]]\n | igorb | NORMAL | 2020-06-02T23:41:31.122559+00:00 | 2020-06-03T04:34:54.170838+00:00 | 1,011 | false | ```\nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n unordered_map<string, vector<pair<string, int>>> mp; // [key, vec[val, time]]\n TimeMap() { \n }\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back({value, timestamp});\n }\n \n string get(string key, int timestamp) {\n auto& v = mp[key];\n auto it = upper_bound(v.begin(), v.end(), timestamp, [](int val, auto& p){return val < p.second;});\n return it == v.begin() ? "" : prev(it)->first;\n }\n};\n```\n\nAlternatively, we can implement simple binary search without STL:\n```\nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n unordered_map<string, vector<pair<string, int>>> mp; // [key, vec[val, time]]\n TimeMap() { \n }\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back({value, timestamp});\n }\n \n string get(string key, int timestamp) {\n auto& v = mp[key];\n int start = 0, end = (int)v.size()-1;\n while(start <= end)\n {\n int mid = start+(end-start)/2;\n v[mid].second > timestamp ? end = mid-1 : start = mid+1; // \'end\' will be equal or one less of TS\n }\n return end < 0 ? "" : v[end].first;\n }\n};\n``` | 4 | 0 | ['C', 'C++'] | 2 |
time-based-key-value-store | Java | Maxheap + HashMap | 100% Memory | 95% time (120 ms) | java-maxheap-hashmap-100-memory-95-time-bvz3v | The idea is to store a MaxHeap for every key. The Maxheap will work on the timestamp so as to get the max one on top. \n\n\nclass TimeMap {\n\n Map<String, P | techton | NORMAL | 2020-05-12T00:23:03.357591+00:00 | 2020-05-12T23:27:10.421914+00:00 | 319 | false | The idea is to store a MaxHeap for every key. The Maxheap will work on the timestamp so as to get the max one on top. \n\n```\nclass TimeMap {\n\n Map<String, PriorityQueue<Entry>> map;\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n PriorityQueue<Entry> pq;\n if(!map.containsKey(key)){\n pq = new PriorityQueue<>(new Comparator<Entry>(){\n @Override\n public int compare(Entry e1, Entry e2){\n return e2.timeStamp - e1.timeStamp;\n }\n });\n map.put(key, pq);\n }else{\n pq = map.get(key);\n }\n pq.add(new Entry(value, timestamp));\n \n }\n \n public String get(String key, int timestamp) {\n String result = "";\n if(map.containsKey(key)){\n PriorityQueue<Entry> pq = map.get(key);\n Deque<Entry> dq = new ArrayDeque<>();\n \n if(pq.peek().timeStamp == timestamp) \n return pq.peek().value;\n while(!pq.isEmpty() && pq.peek().timeStamp > timestamp) \n dq.add(pq.poll());\n if(!pq.isEmpty())\n result = pq.peek().value;\n while(!dq.isEmpty()) pq.add(dq.remove());\n }\n return result;\n }\n \n class Entry{\n String value;\n int timeStamp;\n \n Entry(String value, int timeStamp){\n this.value = value;\n this.timeStamp = timeStamp;\n }\n }\n \n}\n``` | 4 | 0 | [] | 2 |
time-based-key-value-store | C# 99.57%/100% with Binary Search | c-9957100-with-binary-search-by-vasaka-194u | \npublic class TimeMap {\n Dictionary<string, List<(int, string)>> map = new Dictionary<string, List<(int, string)>>();\n \n /** Initialize your data s | vasaka | NORMAL | 2019-10-03T19:57:04.261503+00:00 | 2019-10-03T19:57:04.261573+00:00 | 383 | false | ```\npublic class TimeMap {\n Dictionary<string, List<(int, string)>> map = new Dictionary<string, List<(int, string)>>();\n \n /** Initialize your data structure here. */\n public TimeMap() {\n \n }\n \n public void Set(string key, string value, int timestamp) {\n if (map.TryGetValue(key, out var list)) {\n list.Add((timestamp, value));\n } else {\n map[key] = new List<(int, string)>{(timestamp, value)};\n }\n }\n \n public string Get(string key, int timestamp) {\n if (map.TryGetValue(key, out var list)) \n return bs(list, timestamp);\n return "";\n }\n \n string bs(List<(int, string)> list, int target) {\n var start = 0;\n var end = list.Count - 1;\n \n while (start <= end) {\n var mid = (start + end) / 2;\n var (ts, val) = list[mid];\n if (ts == target) return val;\n if (ts > target) end = mid - 1;\n else start = mid + 1;\n }\n \n if (end >= 0) {\n var (_, res) = list[end];\n return res;\n } else return "";\n \n }\n}\n``` | 4 | 1 | ['Binary Search'] | 0 |
time-based-key-value-store | [CPP] A clear solution using STL( map and unordered_map) | cpp-a-clear-solution-using-stl-map-and-u-o1dc | Here is a clear c++ solution for this problem, and this solution only use map and unorder_map data structure in STL.\n\nFirst, we use a unordered_map to save Ke | wuxiaobai24 | NORMAL | 2019-09-16T12:26:42.485547+00:00 | 2019-09-16T12:26:42.485628+00:00 | 622 | false | Here is a clear c++ solution for this problem, and this solution only use `map` and `unorder_map` data structure in STL.\n\nFirst, we use a `unordered_map` to save Key and \'Value\'(not truely value). And then, we use a `map` to save Time and turely value in map\'s value, so that we can easy use the `lower_bound` api in `map` to finish search in time.\n\n```c++\nclass TimeMap {\npublic:\n \n TimeMap(){\n \n }\n \n void set(string key, string value, int timestamp) {\n data[key][timestamp] = value;\n } \n \n string get(string key, int timestamp) {\n auto it1 = data.find(key);\n if (it1 != data.end()) {\n auto it2 = it1->second.lower_bound(timestamp); \n if (it2 != it1->second.end()) {\n return it2->second;\n }\n }\n return "";\n }\n \n unordered_map<string, map<int, string, greater<int> >> data;\n};\n``` | 4 | 0 | ['C++'] | 0 |
time-based-key-value-store | simple c++ binary search solution | simple-c-binary-search-solution-by-xiliu-gvfi | \nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n TimeMap() {\n \n }\n \n void set(string key, string value, int | xiliuzju | NORMAL | 2019-07-13T19:39:41.570868+00:00 | 2019-07-13T19:39:41.570900+00:00 | 352 | false | ```\nclass TimeMap {\npublic:\n /** Initialize your data structure here. */\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n map_[key].push_back(std::make_pair(value, timestamp));\n }\n \n string get(string key, int timestamp) {\n vector<pair<string, int>>& records = map_[key];\n if (records.size() == 0 ||\n timestamp < records[0].second) return "";\n int lo = 0;\n int hi = records.size() - 1;\n while (lo < hi - 1) {\n int mid = lo + (hi - lo) / 2;\n if (records[mid].second < timestamp) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n \n \n if (records[hi].second <= timestamp) {\n return records[hi].first;\n } else {\n return records[lo].first;\n }\n }\nprivate:\n std::unordered_map<string, vector<pair<string, int>>> map_;\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n```\n | 4 | 0 | [] | 0 |
time-based-key-value-store | C# Solution | c-solution-by-roccosen-2jyc | Here is the C# Solution.\n\n\npublic class TimeMap \n{\n Dictionary<string, SortedList<int, string>> map = new Dictionary<string, SortedList<int, string>>(); | roccosen | NORMAL | 2019-04-21T17:08:23.544333+00:00 | 2019-04-21T17:08:23.544401+00:00 | 869 | false | Here is the C# Solution.\n\n```\npublic class TimeMap \n{\n Dictionary<string, SortedList<int, string>> map = new Dictionary<string, SortedList<int, string>>();\n\n /** Initialize your data structure here. */\n public TimeMap()\n {\n\n }\n\n public void Set(string key, string value, int timestamp)\n {\n if (!map.ContainsKey(key))\n map.Add(key, new SortedList<int, string>());\n\n SortedList<int, string> temp = map[key];\n temp.Add(timestamp, value);\n }\n\n public string Get(string key, int timestamp)\n {\n if (!map.ContainsKey(key))\n return string.Empty;\n\n IList<int> temp = map[key].Keys;\n\n int left = 0;\n int right = temp.Count - 1;\n while (left < right)\n {\n int mid = (left + right + 1) / 2;\n if (temp[mid] == timestamp)\n return map[key].Values[mid];\n\n if (temp[mid] < timestamp)\n left = mid;\n else\n right = mid - 1; \n }\n if(left == 0 && map[key].Keys[0] > timestamp)\n return string.Empty;\n return map[key].Values[left];\n }\n}\n\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.Set(key,value,timestamp);\n * string param_2 = obj.Get(key,timestamp);\n */\n``` | 4 | 0 | [] | 2 |
time-based-key-value-store | Swift two dictionaries | swift-two-dictionaries-by-wds8807-3jeh | Two dictionaries, one for (key: String, timestamp: Int), the other for (timeStamp: Int, value: String).\n\nclass TimeMap {\n\n /** Initialize your data struc | wds8807 | NORMAL | 2019-04-10T19:47:44.466165+00:00 | 2019-04-10T19:47:44.466255+00:00 | 388 | false | Two dictionaries, one for ```(key: String, timestamp: Int)```, the other for ```(timeStamp: Int, value: String)```.\n```\nclass TimeMap {\n\n /** Initialize your data structure here. */\n\tprivate var timestamps: [String: [Int]] = [:] \n\tprivate var values: [Int: String] = [:]\n\t\n\tinit() { }\n\t\n\tfunc set(_ key: String, _ value: String, _ timestamp: Int) {\n\t\ttimestamps[key, default: []].append(timestamp)\n\t\tvalues[timestamp] = value\n\t}\n\t\n\tfunc get(_ key: String, _ timestamp: Int) -> String {\n\t\tguard let array = timestamps[key] else { return "" }\n\t\tguard let first = array.first, timestamp >= first else { return "" }\n\t\tlet timeKey = binarySearch(array, timestamp)\n\t\treturn values[timeKey] ?? ""\n\t}\n\t\n\tprivate func binarySearch(_ array: [Int], _ target: Int) -> Int {\n\t\t\n\t\tvar L = 0, R = array.count - 1\n\t\t\n\t\twhile L < R {\n\t\t\tlet m = (L + R + 1) / 2\n\t\t\tif array[m] == target {\n\t\t\t\treturn target\n\t\t\t} else if target < array[m] {\n\t\t\t\tR = m - 1\n\t\t\t} else {\n\t\t\t\tL = m\n\t\t\t}\n\t\t}\n\t\treturn array[L]\n\t}\n}\n``` | 4 | 0 | [] | 0 |
time-based-key-value-store | O(N) solution beats 90% | Python 3 | Java | Javascript | on-solution-beats-90-python-3-java-javas-vpt7 | IntuitionNo thoughtsApproachCode Commented, just know that i had to submit the code multiple times to understand how it works, the describtion is incomprehsible | mawhadmd | NORMAL | 2025-01-02T23:38:01.880688+00:00 | 2025-01-02T23:38:01.880688+00:00 | 732 | false | # Intuition
No thoughts
# Approach
Code Commented, just know that i had to submit the code multiple times to understand how it works, the describtion is incomprehsible.
The`Set()` does one thing, which is checking if the key already exist in the `Self.map`, if so then it'll append the new `{value, stamp}`, `Self.map` becomes like this after multiple appends `[{value,stamp},{..},{..},...]`. If key doesn't exist in the Map, `Set()` will map the new key and therfore add new key `Self.map`
Key structure: `{'value': value,'stamp': timestamp}`
Suppose we have a key```love -> [{high,10},{low,20}] ```
`get()` will always `return ''` if the key doesn't exist e.g. `get(sad,20)`
- `get(love,5)` returns `''`, because 5 is smaller than 10 and 20
- ,`get(love,10)` returns high, since `{low,20}`'s timestamp is higher than 10 `20<=10 `, therefore returns false, and {high,10} is `10>=10` ture.
- and `get(love,20)` returns low, because basically `20<=10` true.
You can replace the loop with a binary search.
# Complexity
- Time complexity:
Set - O(1)
Get - O(N) (I know, Probably it's because of a lack of test cases)
- Space complexity:
O(N * M)
N is the number of keys
M is the number of values for each key

# Code Python
```python3 []
class TimeMap:
def __init__(self):
self.map = {} #creates a map
def set(self, key: str, value: str, timestamp: int) -> None:
if not self.map.get(key): #if the key doesn't exist create it
self.map[key] = [{'stamp':timestamp,'value':value}]
else: # if does exist, append the new value
self.map[key].append({'stamp':timestamp,'value':value})
def get(self, key: str, timestamp: int) -> str:
if not self.map.get(key): # if key doesn't exist return ''
return ''
# this for loops runs in reverse
# starting from len(self.map[key]) - 1, stops at -1, and each step decrements -1
for i in range(len(self.map[key]) - 1, -1, -1):
# if last item's stamp <= timestamp then print
if self.map[key][i]['stamp']<=timestamp:
return self.map[key][i]['value']
else:
return ''
```
# Code Java
``` Java []
import java.util.*;
class TimeMap {
private Map<String, List<Pair>> map;
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(new Pair(timestamp, value));
}
public String get(String key, int timestamp) {
if (!map.containsKey(key)) {
return "";
}
List<Pair> list = map.get(key);
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).stamp <= timestamp) {
return list.get(i).value;
}
}
return "";
}
private static class Pair {
int stamp;
String value;
public Pair(int stamp, String value) {
this.stamp = stamp;
this.value = value;
}
}
}
```
# Code Javascript
```Javascript []
class TimeMap {
constructor() {
this.map = new Map(); // creates a map
}
set(key, value, timestamp) {
if (!this.map.has(key)) {
this.map.set(key, []);
}
this.map.get(key).push({ stamp: timestamp, value: value });
}
get(key, timestamp) {
if (!this.map.has(key)) {
return "";
}
const list = this.map.get(key);
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].stamp <= timestamp) {
return list[i].value;
}
}
return "";
}
}
```
| 3 | 0 | ['Hash Table', 'Java', 'Python3', 'JavaScript'] | 0 |
time-based-key-value-store | Easy C++ Solution with Explanation | easy-c-solution-with-explanation-by-yash-c61i | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nExplained in the code u | YashodhanSonune | NORMAL | 2024-07-20T12:28:38.486655+00:00 | 2024-07-20T12:28:38.486677+00:00 | 624 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nExplained in the code using comments.\n\n# Complexity\n- Time complexity: Considering a single operation:-\n- \'set\' function -> O(1)\n- \'get\' function -> O(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 TimeMap {\npublic:\n // We are given a key, timestamp and a value to be stored\n // Consider the following example:\n // key = "yashodhan", value = "12", timestamp = 1\n // key = "yashodhan", value = "11", timestamp = 2\n // These values are stored in the data structure we create\n // This is the set function\n\n // In the get function the input is key and timestamp\n // Consider input -> key = "yashodhan", timestamp = 2\n // So we have to return "11" which is the value corresponding to key at given timestamp\n // Suppose input -> key = "yashodhan", timestamp = 10\n // Now the value at this timestamp does not exist\n // Instead we return the value at the most recent timestamp (which is at timestamp = 2 in this case)\n // We return "11"\n\n // So we create an unordered map which stores some data corresponding to the key\n // mpp[key] = some data\n // Now this data is stored in a vector of pair of int and string\n // mpp["yashodhan"] = {{1, "12"}, {2, "11"}}\n // (Since the timestamps are inputed in sorted order we dont need a set we can use a vector as they are already sorted)\n // So to search for a given input, we first check if the map contains the key\n // If no, return ""\n // Else we search through the array corresponding to the key\n // Now we need the value at timestamp or the value at the most recent timestamp\n // Or we find the lower bound of timestamp in the vector and return the value at the lower bound\n unordered_map<string, vector<pair<int, string>>> mpp;\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n mpp[key].push_back({timestamp, value});\n }\n \n string get(string key, int timestamp) {\n if(mpp.find(key) == mpp.end())\n return "";\n \n int low = 0, high = mpp[key].size() - 1;\n\n int maxTimeStamp = -1;\n while(low <= high)\n {\n int mid = (low + high) / 2;\n\n if(mpp[key][mid].first <= timestamp)\n {\n maxTimeStamp = max(maxTimeStamp, mid);\n low = mid + 1;\n }\n else\n high = mid - 1;\n }\n \n if(maxTimeStamp == -1)\n return "";\n return mpp[key][maxTimeStamp].second;\n }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n``` | 3 | 0 | ['C++'] | 1 |
time-based-key-value-store | 32.1 (Approach 1) | O(log n)✅ | Python & C++(Step by step explanation)✅ | 321-approach-1-olog-n-python-cstep-by-st-zx62 | Approach\n\nThe TimeMap class is designed to store key-value pairs where each value has an associated timestamp. The primary operations include setting a key-va | monster0Freason | NORMAL | 2024-01-30T18:29:23.903490+00:00 | 2024-01-30T18:29:23.903517+00:00 | 698 | false | # Approach\n\nThe `TimeMap` class is designed to store key-value pairs where each value has an associated timestamp. The primary operations include setting a key-value pair with a timestamp and retrieving the value associated with a key at a given timestamp.\n\n1. **Initialization:**\n - The class initializes an unordered map (`m`) to store key-value pairs. Each key maps to a vector of pairs, where each pair consists of a timestamp and a corresponding value.\n\n2. **Set Operation (`set` method):**\n - The `set` method takes three parameters: `key`, `value`, and `timestamp`.\n - It appends a new pair (`timestamp`, `value`) to the vector associated with the given key in the map. This allows multiple values for the same key, each associated with a specific timestamp.\n\n3. **Get Operation (`get` method):**\n - The `get` method takes two parameters: `key` and `timestamp`.\n - It first checks if the key exists in the map. If not, it returns an empty string since there is no information for the specified key.\n - For the existing key, it performs a binary search within the associated vector of pairs.\n - The binary search finds the largest timestamp less than or equal to the given timestamp. If found, it returns the corresponding value.\n - If no exact match is found, it returns the value associated with the largest timestamp less than the given timestamp, if such a value exists. Otherwise, it returns an empty string.\n\nThe approach efficiently stores and retrieves timestamped values using binary search within the vectors associated with each key in the unordered map.\n\n# Complexity\n\n- **Time complexity:**\n - Setting a key-value pair: O(1) (amortized time complexity for vector append).\n - Getting a value for a key at a given timestamp: O(log n) for binary search within the vector.\n- **Space complexity:**\n - O(n), where n is the total number of key-value pairs across all keys.\n\n# Code(Python)\n```python\nclass TimeMap:\n\n def __init__(self):\n # Initialize a defaultdict with lists to store key-value pairs.\n self.structure = defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n # Append a new pair [value, timestamp] to the list associated with the key.\n self.structure[key].append([value, timestamp])\n\n def get(self, key: str, timestamp: int) -> str:\n # Initialize an empty string to store the result.\n ans = ""\n # Retrieve the list of pairs associated with the given key.\n temp = self.structure.get(key, [])\n\n # Perform binary search within the list of pairs.\n low, high = 0, len(temp) - 1\n while low <= high:\n mid = (low + high) // 2\n\n # If the timestamp at mid is less than or equal to the target timestamp,\n # update the result and move the search to the right half.\n if temp[mid][1] <= timestamp:\n ans = temp[mid][0]\n low = mid + 1\n # If the timestamp at mid is greater than the target timestamp,\n # move the search to the left half.\n else:\n high = mid - 1\n\n return ans \n\n```\n\n# Code(C++)\n```c++\nclass TimeMap {\npublic:\n // Constructor to initialize the TimeMap\n TimeMap() {\n \n }\n \n // Function to set a key-value pair with a timestamp\n void set(string key, string value, int timestamp) {\n // Append the pair {timestamp, value} to the vector associated with the key in the map\n m[key].push_back({timestamp, value});\n }\n \n // Function to get the value associated with a key at a given timestamp\n string get(string key, int timestamp) {\n // Check if the key is present in the map\n if (m.find(key) == m.end()) {\n return ""; // If not present, return an empty string\n }\n \n int low = 0; // Initialize the low pointer for binary search\n int high = m[key].size() - 1; // Initialize the high pointer for binary search\n \n // Perform binary search within the vector associated with the key\n while (low <= high) {\n int mid = low + (high - low) / 2; // Calculate the middle index\n \n // Compare the timestamp at the middle index with the target timestamp\n if (m[key][mid].first < timestamp) {\n low = mid + 1; // Move the low pointer to explore higher timestamps\n } else if (m[key][mid].first > timestamp) {\n high = mid - 1; // Move the high pointer to explore lower timestamps\n } else {\n return m[key][mid].second; // If an exact match is found, return the corresponding value\n }\n }\n \n // If no exact match is found, return the value associated with the largest timestamp less than the target timestamp\n if (high >= 0) {\n return m[key][high].second;\n }\n return ""; // If no suitable value is found, return an empty string\n }\nprivate:\n unordered_map<string, vector<pair<int, string>>> m; // Data structure to store key-value pairs with timestamps\n};\n```\n\n\n# Please upvote the solution if you understood it.\n\n | 3 | 0 | ['String', 'Binary Search', 'Design', 'C++', 'Python3'] | 1 |
time-based-key-value-store | [Swift][Answer for the interview] | swiftanswer-for-the-interview-by-vilkis-4k8v | Code\n\n\nclass TimeMap {\n\n var dict = [String: [(Int, String)]]()\n\n init() {\n \n }\n func set(_ key: String, _ value: String, _ timesta | ViLkiS | NORMAL | 2023-10-16T07:42:52.374859+00:00 | 2023-10-30T07:05:50.886974+00:00 | 125 | false | # Code\n```\n\nclass TimeMap {\n\n var dict = [String: [(Int, String)]]()\n\n init() {\n \n }\n func set(_ key: String, _ value: String, _ timestamp: Int) {\n dict[key, default: []].append((timestamp, value))\n }\n \n func get(_ key: String, _ timestamp: Int) -> String {\n guard let one = dict[key] else { return "" }\n\n var l = 0\n var r = one.count - 1\n\n while l <= r {\n var mid = (l + r) / 2\n\n if one[mid].0 <= timestamp {\n l = mid + 1\n } else {\n r = mid - 1\n }\n }\n\n return r >= 0 ? one[r].1 : ""\n }\n}\n```\n\n# Upvote if it helped you\n | 3 | 0 | ['Swift'] | 1 |
time-based-key-value-store | OOP And Binary search | Beats 100% C++ Users in time | oop-and-binary-search-beats-100-c-users-rj768 | Intuition\n Describe your first thoughts on how to solve this problem. \n When I read that the inserted timestamps are always greater than the previous, and als | abdelazizSalah | NORMAL | 2023-09-13T12:24:38.976715+00:00 | 2023-09-13T12:34:35.137974+00:00 | 254 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* When I read that the inserted timestamps are always greater than the previous, and also we are looking for the obejct with certain timestamp, I realized that it is a binary search problem.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* This is an oop problem. \n* so lets divide it into 3 main steps\n### 1. Define the used variable\n* you should define the used variables as private data to apply the encapsulation, and prevent users outside the class to access them from outside the class.\n* our datastructure will be a map \n * its key should be string.\n * its value, should be a list of pairs\n * the first object should be integer.\n * while the second should be string. \n### 2. Define the used methods\n* we will need a utility function **BS** to solve the problem, so we should always define all the utility functions under the private setion, and I will discuss the **BS** logic later. \n* in the public section, there will be three main functions:\n 1. Constructor: whenever it is called, we should define new object from our datastructure.\n 2. set(key, value, time): this should insert new element into our datastructre, I will discuss the applied logic later.\n 3. get(key, time): this should check, if the key sent already exist, it should return the timestamp sent, if the timestamp not exist, it should return the string which has the largest timestamp before the sent timestamp.\n * ie: if we set (\'zizo\', \'\'mego\', 2)\n * then if we set (\'zizo\', \'bibo\', 4)\n * then we tried to get(\'zizo\' , 4) it should return bibo.\n * but if we tried to get(\'zizo\', 3) it should return mego, because mego has time stamp 2 which is the less than the sent one (3) and also the greatest one before 3.\n\n### 3. discuss each method logic.\n#### set(key, value, time)\n* here I have made a trick, to make it easier for me to detect empty or not found elements.\n* since in the constrains, the sent timestamps always start from 1.\n* so whenever I start to insert element for the first time, I insert at time 0 empty string, which means that before you have inserted any element, there was nothing there, and this will help me while applying the binary search logic to not put any extra special cases.\n* so i do a check, if this key exists before, then I just push it into its corresponding vector.\n* else, I insert the empty string at time 0\n* then insert the sent item.\n\n\n### get(key, time)\n* this getter will only call the utility function **BS**\n \n### BS(list, trgtTime)\n* this takes a value of certain key which is a vector of pair<int, string>\n* Then I apply simple binary search logic.\n* if there was only one element, then this element is not in the map, so I just return empty string.\n* else i define 3 pointers\n 1. bgn = 0 initially.\n 2. end = sz - 1 initially\n 3. mid = (bgn + end) / 2 -> always use this equation to update the mid pointer.\n* Then I define a string which is **lessThanTarget**, this should hold the element which is less than the trgt but has the largest timestamp.\n* then while the end pointer > bgn pointer, loop\n* and in each iteration we check \n 1. if the trgt > list[mid], then we should look in the left part, as we need a smaller element.\n 2. else if trgt < list[mid], then we should look in the right part, as we need a larger element, and should set lessThanTarget to the element in the mid because this may be our solution, if we did not find the exact timestamp.\n 3. else, then we have found the timestamp, so we should just return the string corresponding to it.\n* After I exit the loop, this means that end == bgn, so I just do a single extra check.\n * if list[mid] == trgt\n * then this is the item, so return the corresponding string.\n * else if it was less than the target, then this is the lattest inserted element before that timestamp, so we should return it.\n* Then at the end we should return lessThanTrgt which hold the lattest inserted element before that timestamp\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n - set:\n - O(log(n)) because we are searching in a hashing tree, which takes lgn\n - get: O(log(n)) because we just use binary search, and its complexity is logn\n - BS: same as get. \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n - O(n * m), as we may have n keys, and each key can have m entries.\n# Code\n```\n#define DPSolver ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); \nclass TimeMap\n{\npublic:\n TimeMap()\n {\n DPSolver;\n // timeMap = map<string, vector<pair<int, string>>>();\n }\n\n void set(string key, string value, int timestamp)\n {\n auto ptr = timeMap.find(key);\n if (ptr != timeMap.end())\n ptr->second.push_back({timestamp, value});\n else\n {\n timeMap[key].push_back({0, ""}); // initialize all inserted elements with empty element.\n timeMap[key].push_back({timestamp, value});\n }\n }\n\n string get(string key, int timestamp)\n {\n return BS(timeMap[key], timestamp);\n }\n\nprivate:\n map<string, vector<pair<int, string>>> timeMap;\n string BS(vector<pair<int, string>> &list, int trgtTime)\n {\n int sz = list.size();\n if (sz == 1)\n return list[0].second;\n int bgn = 0;\n int end = sz - 1;\n int mid = (end + bgn) / 2;\n string lessThanTrgt;\n while (end > bgn)\n {\n if (list[mid].first > trgtTime)\n end = mid;\n else if (list[mid].first < trgtTime)\n {\n bgn = mid + 1;\n lessThanTrgt = list[mid].second;\n }\n else\n return list[mid].second;\n mid = (end + bgn) / 2;\n }\n if (mid >= 0 && mid < sz)\n if (list[mid].first == trgtTime)\n return list[mid].second;\n else if (list[mid].first < trgtTime)\n lessThanTrgt = list[mid].second;\n\n return lessThanTrgt;\n }\n};\n``` | 3 | 0 | ['Hash Table', 'String', 'Binary Search', 'Design', 'C++'] | 0 |
time-based-key-value-store | Time Based Key-Value Store | time-based-key-value-store-by-rissabh361-30jj | 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 | rissabh361 | NORMAL | 2023-09-05T17:48:32.754208+00:00 | 2023-09-05T17:48:32.754231+00:00 | 281 | 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 TimeMap {\n unordered_map<string,vector<pair<string, int>>> mTime;\npublic:\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) { \n mTime[key].push_back({value, timestamp});\n }\n \n string get(string key, int timestamp) { \n int res = -1;\n if( mTime.find(key) != mTime.end()){ \n int start = 0, end = mTime[key].size()-1;\n \n while(start <= end){\n int mid = start + (end-start)/2;\n if(mTime[key][mid].second == timestamp){\n return mTime[key][mid].first;\n }else if(mTime[key][mid].second < timestamp){\n res = mid;\n start = mid+1;\n }else\n end = mid-1;\n } \n }\n \n return (res != -1) ? mTime[key][res].first : "";\n \n }\n};\n\n``` | 3 | 0 | ['C++'] | 0 |
time-based-key-value-store | Easy C++ Solution | easy-c-solution-by-vishnu_kumar-srivasta-weqh | Intuition\n Describe your first thoughts on how to solve this problem. \nThe code implements a time-based key-value store using the TimeMap class. The set funct | vishnu_Kumar-Srivastava | NORMAL | 2023-06-16T04:26:16.917575+00:00 | 2023-06-16T04:26:16.917595+00:00 | 832 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code implements a time-based key-value store using the TimeMap class. The set function is used to store a key-value pair with a corresponding timestamp, and the get function is used to retrieve the value associated with a key at a specific timestamp.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe TimeMap class uses an unordered map m to store the key-value pairs. Each key in the map is associated with a vector of pairs, where each pair represents a timestamp-value pair. The pairs within the vector are sorted in ascending order of timestamps.\n\nThe set function takes a key, value, and timestamp as inputs. It inserts the pair {timestamp, value} into the vector associated with the key in the map m. If the key does not exist in the map, a new vector is created and inserted with the initial pair. The pairs within the vector are maintained in sorted order.\n\nThe get function takes a key and timestamp as inputs and returns the value associated with the key at the largest timestamp less than or equal to the given timestamp. If the key does not exist in the map, an empty string is returned.\n\nTo find the value associated with the given key and timestamp, the code performs a binary search on the vector associated with the key in the map. It compares the target timestamp with the timestamps in the vector using the binary search approach. The search continues until the target timestamp is found, or the search range is exhausted. If the target timestamp is found, the corresponding value is returned. Otherwise, if the target timestamp is not found, the value associated with the largest timestamp less than the target timestamp is returned. This is achieved by returning the value associated with the pair at the index high, where high is the largest index before the search range was exhausted.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe set function has a time complexity of O(1) as it performs constant time operations to insert a pair into the vector associated with the key in the map.\nThe get function has a time complexity of O(log n), where n is the size of the vector associated with the key in the map. This is because it performs a binary search on the sorted vector to find the target timestamp or the largest timestamp less than the target timestamp.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n), where n is the total number of key-value pairs stored in the map. This is because the map m stores all the key-value pairs, and the size of the map is proportional to the number of pairs.\n# Code\n```\nclass TimeMap {\npublic:\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n m[key].push_back({timestamp,value});\n }\n \n string get(string key, int timestamp) {\n if(m.find(key)==m.end()){\n return "";\n }\n int low = 0;\n int high= m[key].size()-1;\n while(low<=high){\n int mid= low+ (high-low)/2;\n if(m[key][mid].first<timestamp){\n low=mid+1;\n }\n else if(m[key][mid].first>timestamp){\n high=mid-1;\n }\n else\n return m[key][mid].second;\n }\n \n if(high>=0)\n {\n return m[key][high].second;\n }\n \n return "";\n }\n private: \n unordered_map<string, vector<pair<int,string>>>m;\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n``` | 3 | 0 | ['C++'] | 0 |
time-based-key-value-store | Solution | solution-by-deleted_user-nnm2 | C++ []\nclass TimeMap {\npublic:\n TimeMap()\n {\n }\n void set(const string& key, const string& value, const int timestamp)\n {\n data_[k | deleted_user | NORMAL | 2023-05-17T12:31:34.985653+00:00 | 2023-05-17T13:20:13.753076+00:00 | 1,194 | false | ```C++ []\nclass TimeMap {\npublic:\n TimeMap()\n {\n }\n void set(const string& key, const string& value, const int timestamp)\n {\n data_[key].emplace_back(timestamp, value);\n }\n string get(const string& key, const int timestamp)\n {\n const auto itData = data_.find(key);\n if (itData == data_.end())\n {\n return "";\n }\n const std::vector<std::pair<int, string>>& values = itData->second;\n\n const auto it = std::lower_bound(values.rbegin(), values.rend(), timestamp, \n [&](const std::pair<int, string>& p, const int targeValue)\n {\n return p.first > targeValue;\n });\n if (it == values.rend())\n {\n return "";\n }\n return it->second;\n }\nprivate:\n std::unordered_map<string, std::vector<std::pair<int, string>>> data_;\n\n};\n```\n\n```Python3 []\nclass TimeMap:\n\n def __init__(self):\n self.values = collections.defaultdict(list)\n self.timestamps = collections.defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.values[key].append(value)\n self.timestamps[key].append(timestamp)\n\n def get(self, key: str, timestamp: int) -> str:\n\n if key not in self.values:\n return ""\n \n if timestamp >= self.timestamps[key][-1]:\n return self.values[key][-1]\n\n timestamps = self.timestamps[key]\n\n left = 0\n right = len(timestamps)-1\n\n ans = -1\n while left <= right:\n mid = (left + right) // 2\n\n if timestamps[mid] <= timestamp:\n ans = mid\n left = mid+1\n else:\n right = mid-1\n \n return "" if ans < 0 else self.values[key][ans]\n```\n\n```Java []\n class TimeMap extends TimeMap3<String, String> {\n protected String getDefaultValue() {\n return "";\n }\n }\n class TimeMap3<K, V> {\n private static class TimeMapNode<V> {\n V value;\n int timestamp;\n\n public TimeMapNode(V value, int timestamp) {\n this.value = value;\n this.timestamp = timestamp;\n }\n }\n private final Map<K, ArrayList<TimeMapNode<V>>> timeMap = new HashMap<>();\n\n public TimeMap3() { }\n\n public void set(K key, V value, int timestamp) {\n timeMap.computeIfAbsent(key, (v) -> new ArrayList<>())\n .add(new TimeMapNode<>(value, timestamp));\n }\n public V get(K key, int timestamp) {\n ArrayList<TimeMapNode<V>> values = timeMap.get(key);\n if (values == null || values.isEmpty()) {\n return getDefaultValue();\n }\n int start = 0;\n int end = values.size() - 1;\n if (timestamp < values.get(start).timestamp ) {\n return getDefaultValue();\n }\n if (timestamp >= values.get(end).timestamp) {\n return values.get(end).value;\n }\n while (start <= end) {\n int mid = (start + end)/2;\n TimeMapNode<V> midValue = values.get(mid);\n if (midValue.timestamp == timestamp) {\n return midValue.value;\n } else if (midValue.timestamp > timestamp) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n return values.get(end).value;\n }\n protected V getDefaultValue() {\n return null;\n }\n }\n```\n | 3 | 0 | ['C++', 'Java', 'Python3'] | 1 |
time-based-key-value-store | Pure BinarySearch | No fancy util functions | pure-binarysearch-no-fancy-util-function-jr2w | Intuition\n Describe your first thoughts on how to solve this problem. \n- whenever we any data which is in sorted order we always need to think about binarySea | napster01 | NORMAL | 2022-12-05T16:14:39.671488+00:00 | 2022-12-05T16:14:39.671533+00:00 | 610 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- whenever we any data which is in sorted order we always need to think about binarySearch\n- here we can see the data we are getting by timestamp, which will always be in increasing order, so that\'s the click.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Set() - straight forward append the data\n- Get() - pure binary serach\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSet() - O(1)\nGet() - O(logn) - binary search\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) - array\n\n# Code\n```\ntype TimeMap struct {\n KeyMap map[string][]Pair\n}\n\ntype Pair struct {\n val string\n timeStamp int\n}\n\n\nfunc Constructor() TimeMap {\n return TimeMap{\n KeyMap: make(map[string][]Pair),\n }\n}\n\n\nfunc (this *TimeMap) Set(key string, value string, timestamp int) {\n pairObj := Pair{\n val: value,\n timeStamp: timestamp,\n }\n\n if _, ok := this.KeyMap[key]; !ok {\n this.KeyMap[key] = make([]Pair, 0)\n }\n this.KeyMap[key] = append(this.KeyMap[key], pairObj)\n}\n\n\nfunc (this *TimeMap) Get(key string, timestamp int) string {\n if _, ok := this.KeyMap[key]; !ok {\n return ""\n }\n arr := this.KeyMap[key]\n if arr[0].timeStamp > timestamp {\n return ""\n }\n\n left := 0\n right := len(arr)-1\n\n for left < right {\n mid := left + (right-left)/2\n if arr[mid].timeStamp == timestamp {\n return arr[mid].val\n } else if arr[mid].timeStamp > timestamp {\n right = mid - 1\n } else {\n left = mid + 1\n }\n }\n if arr[left].timeStamp > timestamp {\n return arr[left-1].val\n }\n return arr[left].val\n}\n\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * obj := Constructor();\n * obj.Set(key,value,timestamp);\n * param_2 := obj.Get(key,timestamp);\n */\n``` | 3 | 0 | ['Hash Table', 'String', 'Binary Search', 'Design', 'Go'] | 0 |
time-based-key-value-store | [ Python ] ✅✅ Simple Python Solution Using Hashmap | Dictionary 🥳✌👍 | python-simple-python-solution-using-hash-vk5i | If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 1654 ms, faster than 40.05% of Python3 online submissi | ashok_kumar_meghvanshi | NORMAL | 2022-10-08T04:58:46.009968+00:00 | 2022-10-08T04:58:46.010008+00:00 | 684 | false | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 1654 ms, faster than 40.05% of Python3 online submissions for Time Based Key-Value Store.\n# Memory Usage: 70 MB, less than 86.19% of Python3 online submissions for Time Based Key-Value Store.\n\n\tclass TimeMap:\n\n\t\tdef __init__(self):\n\n\t\t\tself.dict = {}\n\n\t\tdef set(self, key: str, value: str, timestamp: int) -> None:\n\n\t\t\tif key not in self.dict:\n\t\t\t\tself.dict[key] = {}\n\n\t\t\tself.dict[key][timestamp] = value\n\n\t\tdef get(self, key: str, timestamp: int) -> str:\n\n\t\t\tif key not in self.dict:\n\t\t\t\treturn \'\'\n\n\t\t\twhile timestamp > 0:\n\n\t\t\t\tif timestamp in self.dict[key]:\n\t\t\t\t\treturn self.dict[key][timestamp]\n\n\t\t\t\ttimestamp = timestamp - 1\n\n\t\t\treturn \'\'\n\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D | 3 | 0 | ['Python', 'Python3'] | 1 |
time-based-key-value-store | python3 the most efficient and shortest algorithm | python3-the-most-efficient-and-shortest-dabth | ```\nclass TimeMap:\n\n def init(self):\n self.d={}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.d[(key,timestamp | benon | NORMAL | 2022-10-06T21:57:40.535791+00:00 | 2022-10-06T21:57:40.535826+00:00 | 838 | false | ```\nclass TimeMap:\n\n def __init__(self):\n self.d={}\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.d[(key,timestamp)]=value\n\n def get(self, key: str, timestamp: int) -> str:\n for i in range(timestamp,0,-1):\n if (key,i) in self.d:\n return self.d[(key,i)]\n return ""\n | 3 | 0 | ['Python', 'Python3'] | 4 |
time-based-key-value-store | 📌5 line code✅|Faster than 96.95% of CPP online submissions | HashMap | Binary Search | Map | 5-line-codefaster-than-9695-of-cpp-onlin-kvxk | \nclass TimeMap {\npublic:\n unordered_map<string,map<int,string>> umap;\n TimeMap() {}\n void set(string key, string value, int timestamp) {\n | code_hobby_2404 | NORMAL | 2022-10-06T18:24:53.861594+00:00 | 2022-10-06T18:27:57.626510+00:00 | 337 | false | ```\nclass TimeMap {\npublic:\n unordered_map<string,map<int,string>> umap;\n TimeMap() {}\n void set(string key, string value, int timestamp) {\n umap[key].insert({-1*timestamp,value});\n }\n string get(string key, int timestamp) {\n if(!umap.count(key)) return "";\n auto it=umap[key].lower_bound(-1*timestamp);\n return (*it).second;\n }\n};\n``` | 3 | 0 | ['Binary Tree', 'C++'] | 2 |
time-based-key-value-store | TreeMap | Simple | 85% Faster | treemap-simple-85-faster-by-evil_bios-akir | java\nclass TimeMap {\n Map <String, TreeMap<Integer, String>> map;\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set | evil_bios | NORMAL | 2022-10-06T16:55:06.713087+00:00 | 2022-10-06T16:55:06.713131+00:00 | 369 | false | ```java\nclass TimeMap {\n Map <String, TreeMap<Integer, String>> map;\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n if (map.get(key) == null)\n map.put(key, new TreeMap<>());\n map.get(key).put(timestamp, value);\n }\n \n public String get(String key, int timestamp) {\n if (map.get(key) == null || map.get(key).floorKey(timestamp) == null)\n return "";\n Integer temp = map.get(key).floorKey(timestamp);\n return map.get(key).get(temp);\n }\n}\n``` | 3 | 0 | ['Tree', 'Java'] | 0 |
time-based-key-value-store | Easiest soln | Java | TreeMap | | easiest-soln-java-treemap-by-amandubeyy-ad2r | \nclass TimeMap {\n\n HashMap<String, TreeMap<Integer, String>> map;\n \n public TimeMap() {\n map = new HashMap<>();\n }\n \n public v | amandubeyy | NORMAL | 2022-10-06T13:36:09.543771+00:00 | 2022-10-06T13:36:09.543806+00:00 | 314 | false | ```\nclass TimeMap {\n\n HashMap<String, TreeMap<Integer, String>> map;\n \n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n \n if(map.containsKey(key) == false){\n map.put(key, new TreeMap<>());\n }\n map.get(key).put(timestamp, value);\n }\n \n public String get(String key, int timestamp) {\n \n if(map.containsKey(key) == false) return "";\n \n TreeMap<Integer, String> t_map = map.get(key);\n \n Integer time = t_map.floorKey(timestamp);\n \n if(time != null) return t_map.get(time);\n \n return "";\n }\n}\n\n\n``` | 3 | 0 | ['Tree', 'Java'] | 0 |
time-based-key-value-store | c++ solution using map, simple and easy to understand | c-solution-using-map-simple-and-easy-to-zixzj | \nclass TimeMap {\n map<string, map<int, string, std::greater<int>>> dictionary;\npublic:\n TimeMap() {\n \n }\n \n void set(string key, s | MegaBeta | NORMAL | 2022-10-06T12:39:43.967351+00:00 | 2022-10-06T12:39:43.967392+00:00 | 599 | false | ```\nclass TimeMap {\n map<string, map<int, string, std::greater<int>>> dictionary;\npublic:\n TimeMap() {\n \n }\n \n void set(string key, string value, int timestamp) {\n dictionary[key][timestamp] = value;\n }\n \n string get(string key, int timestamp) {\n auto it = dictionary[key].lower_bound(timestamp);\n if (it != dictionary[key].end()){\n return it->second;\n }\n return "";\n }\n};\n\n``` | 3 | 0 | [] | 0 |
time-based-key-value-store | Java | HashMap+TreeMap | Searching | Easy to Understand | java-hashmaptreemap-searching-easy-to-un-grmf | \nclass TimeMap {\n HashMap<String, TreeMap<Integer, String>> map;\n public TimeMap() {\n map = new HashMap<String, TreeMap<Integer, String>>();\n | Suyash_25 | NORMAL | 2022-10-06T10:42:27.947566+00:00 | 2022-10-06T10:46:02.871419+00:00 | 546 | false | ```\nclass TimeMap {\n HashMap<String, TreeMap<Integer, String>> map;\n public TimeMap() {\n map = new HashMap<String, TreeMap<Integer, String>>();\n }\n\n public void set(String key, String value, int timestamp) {\n if (!map.containsKey(key)) map.put(key, new TreeMap<Integer, String>());\n map.get(key).put(timestamp, value);\n }\n \n public String get(String key, int timestamp) {\n if(!map.containsKey(key)) return "";\n Integer value = map.get(key).floorKey(timestamp);\n if(value != null) return map.get(key).get(value);\n return "";\n }\n}\n```\n***Why floorKey()?*** \n*`floorKey() is used to return the greatest key less than or equal to given key i.e. timestamp.`*\n\n*Kindly upvote if you find it helpful* | 3 | 0 | ['Tree', 'Java'] | 0 |
time-based-key-value-store | C++ || Map Implementation || Priority Queue | c-map-implementation-priority-queue-by-a-u1h9 | \nclass TimeMap {\npublic:\n unordered_map<string,string> mp;\n unordered_map<string,priority_queue<int>> mp2;\n \n TimeMap() {\n mp.clear(); | anujverma11062002 | NORMAL | 2022-10-06T08:52:25.583166+00:00 | 2022-10-06T08:52:46.666386+00:00 | 1,155 | false | ```\nclass TimeMap {\npublic:\n unordered_map<string,string> mp;\n unordered_map<string,priority_queue<int>> mp2;\n \n TimeMap() {\n mp.clear();\n mp2.clear();\n }\n \n void set(string key, string value, int timestamp) {\n string s = key + "_" + to_string(timestamp);\n mp2[key].push(timestamp); // storing all the timestamps for same key in descending order\n mp[s] = value;\n }\n \n string get(string key, int timestamp) {\n string s = key + "_" + to_string(timestamp);\n if(!mp.count(s)){ // if (key + timestamp) doesn\'t found then find the largest timestamp which is less equal to the given timestamp \n vector<int> vec;\n \n while(!mp2[key].empty() && mp2[key].top() > timestamp){\n vec.push_back(mp2[key].top());\n mp2[key].pop();\n }\n if(mp2[key].empty()){\n for(auto it:vec){\n mp2[key].push(it);\n }\n return ""; \n } \n string str = key + "_" + to_string(mp2[key].top());\n for(auto it:vec){\n mp2[key].push(it);\n }\n return mp[str];\n }\n return mp[s];\n }\n};\n\n``` | 3 | 0 | ['C', 'Heap (Priority Queue)', 'C++'] | 1 |
time-based-key-value-store | Java TreeMap Implementation | java-treemap-implementation-by-fllght-1kwm | Java\njava\nprivate final Map<String, TreeMap<Integer, String>> store;\n\n public TimeMap() {\n store = new HashMap<>();\n }\n\n public void set | FLlGHT | NORMAL | 2022-10-06T07:35:44.203451+00:00 | 2022-10-06T07:35:54.763443+00:00 | 209 | false | ##### Java\n```java\nprivate final Map<String, TreeMap<Integer, String>> store;\n\n public TimeMap() {\n store = new HashMap<>();\n }\n\n public void set(String key, String value, int timestamp) {\n if (!store.containsKey(key))\n store.put(key, new TreeMap<>());\n\n store.get(key).put(timestamp, value);\n }\n\n public String get(String key, int timestamp) {\n TreeMap<Integer, String> treeMap = store.get(key);\n if (treeMap == null)\n return "";\n\n Integer floorKey = treeMap.floorKey(timestamp);\n if (floorKey == null)\n return "";\n\n return treeMap.get(floorKey);\n }\n``` | 3 | 0 | ['Java'] | 1 |
count-alternating-subarrays | Simple C++ Solution || Counting | simple-c-solution-counting-by-adityaraj_-4jho | Approach\n1. The method iterates through the array nums starting from index 1.\nAt each iteration, it checks if the current element is equal to the previous ele | AdityaRaj_cpp | NORMAL | 2024-03-31T04:18:30.835794+00:00 | 2024-03-31T04:39:45.582834+00:00 | 2,109 | false | # Approach\n1. The method iterates through the array nums starting from index 1.\nAt each iteration, it checks if the current element is equal to the previous element.\n2. If they are equal, it means the alternating pattern is broken, so it calculates the length of the subarray and adds the count of alternating subarrays up to that point to the answer.\n3. It updates the`bg`(beginning) index to the current index to start counting the next subarray.\n4. After the loop, it calculates the length of the last subarray (from the last`bg`index to the end of the array) and adds its count to the answer.\n5. Finally, it returns the total count of alternating subarrays.\n\n# Complexity\n- Time complexity: `O(n)`\n- Space complexity: `O(1)`\n\n# Code\n```\nclass Solution\n{\npublic:\n long long countAlternatingSubarrays(vector<int> &nums)\n {\n int bg = 0;\n long long ans = 0;\n for (int i = 1; i < nums.size(); i++)\n {\n if (nums[i] == nums[i - 1])\n {\n long long len = i - bg;\n ans += (long long)(len * (len + 1) * 1ll) / 2;\n bg = i;\n }\n }\n long long len = nums.size() - bg;\n ans += (long long)(len * (len + 1) * 1ll) / 2;\n return ans;\n }\n};\n```\n\n#### Why is it even medium? \uD83D\uDE44\n | 16 | 2 | ['Sliding Window', 'C++'] | 3 |
count-alternating-subarrays | Python | DP | Easy to understand | python-dp-easy-to-understand-by-coder191-h26e | \nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n n = len(nums)\n dp = [1] * n\n \n for i in ran | Coder1918 | NORMAL | 2024-03-31T04:04:49.703112+00:00 | 2024-03-31T04:04:49.703137+00:00 | 928 | false | ```\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n n = len(nums)\n dp = [1] * n\n \n for i in range(1, n):\n if nums[i-1] != nums[i]:\n dp[i] = dp[i - 1] + 1\n \n return sum(dp)\n``` | 12 | 0 | ['Dynamic Programming', 'Python3'] | 1 |
count-alternating-subarrays | Simple java solution | simple-java-solution-by-siddhant_1602-wdha | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n | Siddhant_1602 | NORMAL | 2024-03-31T04:18:56.665673+00:00 | 2024-03-31T04:18:56.665694+00:00 | 1,058 | false | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long maxi=0;\n int i=0,j=0;\n for(i=0,j=0;i<nums.length-1;i++)\n {\n if(nums[i]==nums[i+1])\n {\n int val = i-j+1;\n maxi+=(long)val*((long)(val+1))/2;\n j=i+1;\n }\n }\n int val = i-j+1;\n maxi+=(long)val*((long)(val+1))/2;\n return maxi;\n }\n}\n``` | 11 | 1 | ['Java'] | 2 |
count-alternating-subarrays | Java Solution - Sliding Window | java-solution-sliding-window-by-makubex7-b375 | Intuition\n Describe your first thoughts on how to solve this problem. \n- Compare the current element with the previous element. \n- If they are different, inc | makubex74 | NORMAL | 2024-03-31T04:46:31.376653+00:00 | 2024-03-31T05:47:34.060207+00:00 | 443 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Compare the current element with the previous element. \n- If they are different, increase the length of the window. \n- If they are same, then calculate the number of subarrays that can be created.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Have two pointers, `start` and `end` to keep track of the current window with alternating `0s` and `1s`. The length of the of the current subarray `length` is given by `end - start`.\n- Calculate the number of subarrays that can be formed for any array of length `n` with the following formula.\nn\n\u2211 i = 1 + 2 + 3 + 4 + ... + n = n*(n+1)/2\ni=1\n- Update the `start` of the window and `end` of the window.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long count = 0;\n long length = 0;\n int start = 0;\n int end = 1;\n while(end < nums.length) {\n if(nums[end] != nums[end - 1]) {\n end++;\n } else {\n length = end - start;\n count += (length * (length + 1)) / 2;\n start = end;\n end++;\n }\n }\n length = end - start;\n count += (length * (length + 1)) / 2;\n return count;\n }\n}\n\n``` | 10 | 0 | ['Two Pointers', 'Sliding Window', 'Java'] | 1 |
count-alternating-subarrays | Python 3 || 7 lines, simple count || T/S: 98% / 93% | python-3-7-lines-simple-count-ts-98-93-b-if5t | \nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n\n ans, curr = 0, nums[0]\n\n for num in nums:\n | Spaulding_ | NORMAL | 2024-03-31T16:25:42.773859+00:00 | 2024-06-12T05:26:18.619355+00:00 | 509 | false | ```\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n\n ans, curr = 0, nums[0]\n\n for num in nums:\n prev, curr = curr, num\n \n if prev^curr == 0: cnt = 0\n\n cnt+= 1\n\n ans+= cnt\n \n return ans\n```\n[https://leetcode.com/problems/count-alternating-subarrays/submissions/1219322345/](https://leetcode.com/problems/count-alternating-subarrays/submissions/1219322345/)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(nums)`. | 8 | 0 | ['Python3'] | 1 |
count-alternating-subarrays | C++ | Sliding Window | Counting | Explained | c-sliding-window-counting-explained-by-d-gki8 | Approach\nWe know our subarray that contribute to answer must now have any adjacent values same. \n\tSo use a variable prev to store the last index whem element | dholiyoo | NORMAL | 2024-03-31T04:03:54.435093+00:00 | 2024-03-31T04:03:54.435116+00:00 | 1,254 | false | **Approach**\nWe know our subarray that contribute to answer must now have any adjacent values same. \n\tSo use a variable `prev` to store the last index whem element is different. Now iterate over the array if adjacent are not same, update `answer += (i - prev)`. If same set `prev = current` Index and iterate ahead. \n\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans = 0; \n \n //count all same \n long long n = nums.size(); \n ans = n; \n long long cnt = 1; \n long long prev = 0; \n for(long long i = 1; i < n; i++) {\n if(nums[i] != nums[i - 1]) {\n ans += (i - prev); \n \n } else {\n prev = i; \n }\n }\n return ans; \n }\n};\n``` | 7 | 0 | ['Counting', 'C++'] | 2 |
count-alternating-subarrays | Simple Java solution - Two pointer/Slding Window Time: O(n), Space: O(1) | simple-java-solution-two-pointerslding-w-3yaz | Intuition\n Describe your first thoughts on how to solve this problem. \nStart from the begining and find the longest alternating Subarray. For an array of size | piyush_tilokani | NORMAL | 2024-03-31T06:02:37.989762+00:00 | 2024-03-31T06:02:37.989797+00:00 | 95 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStart from the begining and find the longest alternating Subarray. For an array of size n, there are (1+2+3+...+n) **(i.e. sum of first n natural numbers)** subarrays that exist \n\nThat means for every alternating subarray of size `windowSize` there exist `((windowSize*(windowSize+1))/2)`**(formula for sum of first n natural numbers)** sub arrays. Do this for the whole array and you get rhe total number of alternating subarrays\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake 2 pointers `l` and `r`\n\nStart incrementing `r` untill element at `r` and `r+1` are unequal, The moment you find an element at `r` being equal to element at `r+1`, you have found an aklternating subarray of size `r-l+1` \n\nNow store this size in a variable `windowSize` and increment your answer by `((windowSize*(windowSize+1))/2)` do this untill `l` doesn\'t reach the end of the array\n\n\n**IMP NOTE: Declare this `windowSize` variable as long as it may store values greater than the maximum capacity of int and cause int overflow. I failed a submission due to this mistake.**\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long ans = 0;\n int l=0;\n int r=0;\n int n=nums.length;\n while(l<n){\n if(r<n-1 && nums[r]!=nums[r+1]){\n while(r<n-1 && nums[r]!=nums[r+1])\n r++;\n }\n long windowSize = r-l+1;\n ans += ((windowSize*(windowSize+1))/2);\n r += 1;\n l = r;\n } \n return ans;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
count-alternating-subarrays | SIMPLE SLIDING WINDOW SOLUTION | simple-sliding-window-solution-by-qbasic-0fv1 | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& num | calm_porcupine | NORMAL | 2024-03-31T04:01:48.535223+00:00 | 2024-04-01T07:01:40.377890+00:00 | 1,656 | false | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans = 0;\n int prev = -1;\n int j = 0;\n for(int i = 0;i<nums.size();i++){\n if(nums[i]==prev){\n j = i;\n }\n ans+=(i-j+1);\n prev = nums[i];\n }\n return ans;\n }\n};\n``` | 5 | 0 | ['Sliding Window', 'C++'] | 1 |
count-alternating-subarrays | Sliding window approach, easy to understand. | sliding-window-approach-easy-to-understa-y6f9 | Intuition\n Describe your first thoughts on how to solve this problem. \nwhen it comes to subarrays problem, i usually think of sliding window.\n# Approach\n De | kietng04 | NORMAL | 2024-04-03T06:58:20.196686+00:00 | 2024-04-03T06:58:20.196723+00:00 | 382 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwhen it comes to subarrays problem, i usually think of sliding window.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe definitely have nums.size() into our result first.\nif (nums[r] == nums[r-1]) then we have r - l subarray satisfy.\nelse we move the left pointer to the current index of right pointer\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n- Space complexity:\n$$O(1)$$ \n<!-- Add your space complexity here, e.g. $O(n)$$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n int l = 0, r = 1;\n long long res = nums.size();\n for (r; r < nums.size(); r++) {\n if (nums[r] == nums[r-1]) \n l = r;\n else \n res += r - l;\n }\n return res;\n }\n};\n``` | 4 | 0 | ['Two Pointers', 'Sliding Window', 'C++'] | 1 |
count-alternating-subarrays | aao solution samgho hindi me|| unique concept|| Bhut aasan h | aao-solution-samgho-hindi-me-unique-conc-13ew | Intuition\n Describe your first thoughts on how to solve this problem. \n# OR CODERS kya haal chaal h\nbhut hi aasan q puch liya \nmaine is question ko jab dekh | Aman028 | NORMAL | 2024-03-31T06:27:33.780612+00:00 | 2024-03-31T06:27:33.780642+00:00 | 78 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# OR CODERS kya haal chaal h\nbhut hi aasan q puch liya \nmaine is question ko jab dekha toh hume number of alternating subarrays nikalana h toh maine socha kyu n hum ye concept lagaye\n```\nconcept h\nnums = [0,1,1,1]\n- agar hume index=1 ko leke total subarrays index 1 tak hi \nkitne honge [1] [0,1] ye dono hi honge\nye humne kaise nikalna hoga, index--> 1-0+1=2 aise hi toh nikla hoga\n\n- agar hume index=2 ko leke total subarrays index 2 tak hi \nkitne honge [1] [0,1,1] [1,1] ye teeno hi honge\nye humne kaise nikalna hoga, index-->2-0+1=3 aise hi toh nikla hoga\n\n-ab maan lo hume index 2 se lekar index 1 se kitna subarray hoga\n[1] [1,1] yahi dono toh hoga, kaise nikala hoga \nindex-->2-1+1=2 aise hi toh nikala hoga\n```\ntoh formula nikla **index2-index1+1**\n\naao aaproach me dekhe kaise isko hum is question me kaise lagenyenge\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- humne i,j pointer liya dono 0 se start hua\n- humne check kiya ki pointer i and pointer j ke index pe same h toh ek hi subarray nikelga, ab starting wala index se ek hi toh banega.\n- fir humne j badha diya fir check kiya ki index j-1 and index j equal h kya h\n- agar equal h toh hum index j-1 ko nhi leke sakte subarray me yahi toh question tha ki same nhi lena, toh humne index i ko badha k j par hi kar diya or ab ek index se count me contribution ek hi toh hoga\n- agar equal nhi h toh hum formula laga k nikalenge ki kitna contribution hoga\n# aao example se samghe\n- Eg:- nums = [0,1,1,1]\n- i=0,j=0, toh sirf index 0 kitna contribute karega ek hi subarray ([0]) toh hoga count=1;\n- fir humne jo aage badha diya j=1, or check kiya ki j-1 and j par value same h ya alag alag h. alga h toh formula lagya j-i+1=1-0+1=2\nindex 1 ko leke subarrays [0,1] [1] toh count=3 ho gya, humne j badha diya\n - j=2, humne dekha ki j-1 and j equal h toh hum j-1 ko subarray me nhi leke sakte toh humne i ko badha k j par hi akr diya or sirf akela j toh ek hi contribute karega count me, count=4, j ko aage badha diya \n - j=3 humne dekha ki j-1 and j equal h toh hum j-1 ko subarray me nhi leke sakte toh humne i ko badha k j par hi akr diya or sirf akela j toh ek hi contribute karega count me, count=5, j ko aage badha diya\n - toh total subarrays (count=5) 5 nikala\n\n**code dekh lete h**\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1)\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long n=nums.size();\n long long i=0,j=0;\n long long ans=0;\n while(j<n)\n {\n //check kiya ki previous and current equal toh nhi\n if(j!=0&&nums[j-1]!=nums[j])\n {\n formula lagya\n long long add=(j-i+1);\n ans=ans+add;\n }\n //equal h toh sirf 1 hi contribute karega\n else\n {\n i=j;\n long long add=1;\n ans=ans+add;\n }\n j++;\n }\n return ans;\n }\n};\n```\n\n | 4 | 0 | ['Two Pointers', 'C++'] | 0 |
count-alternating-subarrays | Easy - Linear time and constant space | easy-linear-time-and-constant-space-by-s-wzdy | Intuition\n Describe your first thoughts on how to solve this problem. \nTo count the number of alternating subarrays in the given list of numbers, we can itera | slippinnjimmy | NORMAL | 2024-03-31T04:43:51.848586+00:00 | 2024-03-31T04:43:51.848605+00:00 | 295 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo count the number of alternating subarrays in the given list of numbers, we can iterate through the list while maintaining a count of consecutive alternating elements. Whenever we encounter a non-alternating element, we calculate the number of subarrays that can be formed using the current count and add it to the result. Finally, we return the total count of alternating subarrays.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n- We iterate through the list, keeping track of the count of consecutive alternating elements.\n- Whenever we encounter a non-alternating element, we calculate the number of subarrays that can be formed using the current count and add it to the result.\n- The total count of alternating subarrays is the sum of all such counts calculated for each non-alternating element encountered.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this approach is O(n), where n is the length of the input list. We iterate through the list once to calculate the count of alternating subarrays.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) since we are using only a constant amount of extra space for storing variables regardless of the size of the input list.\n# Code\n```\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n count = 1\n result = 0\n for i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n count += 1\n else:\n result += count * (count + 1) // 2\n count = 1\n result += count * (count + 1) // 2\n return result\n\n```\n\n\n | 4 | 0 | ['Python3'] | 1 |
count-alternating-subarrays | BEATS 100% || LEARN INTUITION BUILDING || DETAILED | beats-100-learn-intuition-building-detai-v8kz | Intuition\n Describe your first thoughts on how to solve this problem. \nApproaching problems like counting alternating subarrays involves thinking like a detec | Abhishekkant135 | NORMAL | 2024-03-31T04:11:20.093813+00:00 | 2024-03-31T04:11:20.093833+00:00 | 364 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nApproaching problems like counting alternating subarrays involves thinking like a detective. Imagine scanning the array for "clues" - elements differing by 1 alternately. A sliding window helps us focus on potential subarrays as we move along. We track their length and any relevant details (like consecutive differences here). As we gather evidence (valid subarrays), we accumulate the count. Finally, at the scene\'s end (array\'s end), we adjust for any misleading clues (edge cases) to reveal the final count of these alternating subarray patterns.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe provided code effectively calculates the number of subarrays in an array `nums` where elements alternate by differing exactly by 1. Here\'s a detailed explanation:\n\n**Functionality:**\n\n- It counts the number of subarrays within `nums` that satisfy the condition of having elements differing by 1 alternately.\n\n**Breakdown:**\n\n1. **Initialization:**\n - `n = nums.length`: Stores the length of the input array.\n - `ans = 0`: Initializes a variable to accumulate the count of valid subarrays.\n - `alt = 0`: Tracks the length of the current alternating subarray (initialized to 0).\n - `consecutives = 0`: Tracks the number of consecutive elements with the same difference (initialized to 0).\n - `if (n == 1)`: Base case - if there\'s only one element, it\'s considered a valid subarray, so return 1.\n\n2. **Iterating Through the Array:**\n - `int i = 1`: Starts the loop from the second element (`i = 1`) as the first element is already considered in the base case.\n - `while (i < n)`: The loop iterates as long as `i` is within the array bounds (`i < n`).\n\n3. **Checking for Alternating Difference:**\n - `alt = 1`: Resets `alt` to 1 for each new potential subarray starting at `i`.\n - `while (i < n && nums[i] == Math.abs(nums[i-1] - 1))`: This inner loop continues as long as:\n - `i` is within the array bounds (`i < n`).\n - The current element (`nums[i]`) differs by exactly 1 from the previous element (`nums[i-1]`).\n - Inside the inner loop:\n - `alt++`: Increments `alt` as the current element satisfies the alternating difference condition, extending the potential subarray.\n - `consecutives++`: Increments `consecutives` to track the number of consecutive elements with the same difference (increasing or decreasing by 1).\n - `ans += alt`: Adds the current length of the alternating subarray (`alt`) to the total count (`ans`). This considers all possible subarrays ending at each index `i` within the current potential subarray.\n - `i++`: Increments `i` to move to the next element for checking the next potential subarray.\n\n4. **Handling the End and Returning the Result:**\n - After the outer loop completes, the code considers elements that might not be part of a longer alternating subarray due to reaching the end of the array.\n - `return ans + n - consecutives`:\n - `ans`: The count of valid subarrays accumulated during the loop.\n - `n`: The total number of elements in the array.\n - `consecutives`: The number of consecutive elements with the same difference (these might not be part of a longer valid subarray).\n - Subtracting `consecutives` from `n` effectively removes any potential overcounting of subarrays due to considering consecutive elements at the end that might not be part of a valid alternating subarray.\n\n**Key Points:**\n\n- The code leverages sliding window logic to efficiently identify alternating subarrays.\n- The `alt` variable keeps track of the current subarray\'s length as long as the alternating difference condition is met.\n- The `consecutives` variable helps in adjusting the final count to avoid overcounting subarrays at the end of the array.\n- Overall, the code provides an accurate and efficient solution for counting alternating subarrays with a difference of 1.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n# GET MY LINKEDIN IN COMMENTS. LETS CONQUER DSA TOGETHER AND PLS UPVOTE\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long n=nums.length;\n long ans=0;\n long alt=0;\n long consecutives=0;\n if(n==1){\n return 1;\n }\n int i=1;\n while(i<n){\n alt=1;\n while(i<n && nums[i]==Math.abs(nums[i-1]-1)){\n alt++;\n consecutives++;\n ans+=alt;\n i++;\n }\n i++;\n }\n return ans+n-consecutives;\n }\n}\n``` | 4 | 0 | ['Array', 'Java'] | 1 |
count-alternating-subarrays | ✅ Java Solution | Easy to understand | java-solution-easy-to-understand-by-hars-xtzo | CODE\nJava []\npublic long countAlternatingSubarrays(int[] nums) {\n\tlong res = 0l;\n\tint n = nums.length;\n\tint i=0, j=1;\n\twhile(j < n){\n\t\tif(nums[j] = | Harsh__005 | NORMAL | 2024-03-31T04:02:22.677725+00:00 | 2024-03-31T04:02:22.677759+00:00 | 362 | false | ## **CODE**\n```Java []\npublic long countAlternatingSubarrays(int[] nums) {\n\tlong res = 0l;\n\tint n = nums.length;\n\tint i=0, j=1;\n\twhile(j < n){\n\t\tif(nums[j] == nums[j-1]) {\n\t\t\ti = j;\n\t\t} else {\n\t\t\tres += (j-i);\n\t\t}\n\t\tj++;\n\t}\n\treturn res+n;\n}\n``` | 4 | 0 | ['Java'] | 1 |
count-alternating-subarrays | Simple math solution JS || O(n) || O(1) | simple-math-solution-js-on-o1-by-dhnbrok-418u | Approach\n Describe your approach to solving the problem. \n- Declare a variable to count the consecutive number\n- If nums[i] !== nums[i - 1], increase the con | dhnbroken | NORMAL | 2024-04-02T04:35:04.147508+00:00 | 2024-04-02T04:38:59.801172+00:00 | 200 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- Declare a variable to count the consecutive number\n- If nums[i] !== nums[i - 1], increase the consecutive by 1\n- Else set consecutive = 1\n- Count will be increased by consecutive for each loop\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countAlternatingSubarrays = function (nums) {\n let count = nums.length,\n continues = 1;\n for (let i = 1; i < nums.length; i++) {\n if (nums[i] !== nums[i - 1]) {\n count += continues;\n continues++;\n } else {\n continues = 1;\n }\n }\n\n return count;\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
count-alternating-subarrays | Dynamic Programming🔥🔥 || Python | dynamic-programming-python-by-vinaypabba-fjsm | \n\n# Code\n\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n #dp=[1]*len(nums)\n s=1\n curr=1\n | vinaypabba48 | NORMAL | 2024-03-31T07:25:36.399676+00:00 | 2024-03-31T07:25:36.399698+00:00 | 32 | false | \n\n# Code\n```\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n #dp=[1]*len(nums)\n s=1\n curr=1\n for i in range(1,len(nums)):\n if nums[i]!=nums[i-1]:\n curr=curr+1\n s+=curr\n else:\n curr=1\n s+=curr\n \n return s\n \n``` | 3 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
count-alternating-subarrays | Beats 100% || Easy Soln - n*(n+1)/2 | beats-100-easy-soln-nn12-by-hina_bediya-jex3 | Intuition\n\n# Approach\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n\nclass Solution {\n public long countAlternatingSubarray | Hina_Bediya | NORMAL | 2024-03-31T04:31:06.560051+00:00 | 2024-03-31T04:47:07.050947+00:00 | 219 | false | # Intuition\n\n# Approach\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n if(nums.length==1)return 1;\n long ans=0;\n int i=0,j=0;\n \n while(j<nums.length-1){\n \n if(nums[j]==nums[j+1]){\n ans=ans+(long)(j-i+1)*(j-i+2)/2;\n i=j+1;\n }\n j++;\n }\n ans=ans+(long)(j-i+1)*(j-i+2)/2;\n return ans;\n }\n}\n``` | 3 | 0 | ['Math', 'Sliding Window', 'Java'] | 1 |
count-alternating-subarrays | C++ Solution beats 100% during contest 31-03-2024 | c-solution-beats-100-during-contest-31-0-pmti | Intuition\n\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- Tim | Edwards310 | NORMAL | 2024-03-31T04:17:24.701325+00:00 | 2024-03-31T04:17:24.701351+00:00 | 25 | false | # Intuition\n\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 long long countAlternatingSubarrays(vector<int>& nums) {\n int n = nums.size();\n long long r = 0;\n int l = 1;\n for(int i = 1; i < n; i++){\n if(nums[i] != nums[i - 1])\n l += 1;\n else{\n r += (long long)l * (l + 1) / 2;\n l = 1;\n }\n }\n r += (long long)l * (l + 1) / 2;\n return r;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
count-alternating-subarrays | Beats 100% user || very easy to understand | beats-100-user-very-easy-to-understand-b-ovkg | 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 | Tamradhwaj | NORMAL | 2024-03-31T04:08:53.386272+00:00 | 2024-03-31T04:08:53.386291+00:00 | 187 | 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 long long countAlternatingSubarrays(vector<int>& nums) {\n long long count=0;\n long long left =0;\n for(int right=0;right<nums.size();right++){\n\n if(right>0 && nums[right]==nums[right-1]){\n left=right;\n }\n count+=right-left+1;\n }\n return count;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
count-alternating-subarrays | Easiest Java Solution || Step by step | easiest-java-solution-step-by-step-by-1a-z9z6 | \n\n# Code\n\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long count=1;\n int ref=0; // changed when we encounter | 1asthakhushi1 | NORMAL | 2024-03-31T04:06:38.387468+00:00 | 2024-03-31T04:28:06.176829+00:00 | 846 | false | \n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long count=1;\n int ref=0; // changed when we encounter that digit at previous index is same as digit at current index\n int prev=nums[0];\n for(int i=1;i<nums.length;i++){\n if(prev!=nums[i])\n count+=(i-ref); // (i-ref) all possible subarrays formed between index ref and index i, since between i and ref, no same digit is side by side\n else\n ref=i; // as no more subarrays including this index can be generated, so fresh start from this index\n\n count+=1; // +1 (is for a subarray containing only the element at this particular index)\n prev=nums[i];\n }\n return count;\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
count-alternating-subarrays | Evaluate n(n + 1)/2 for each non repeating subarray | evaluate-nn-12-for-each-non-repeating-su-qayt | Intuition\n- Each set of equal value divide the array into two separate array\n- On each non repeating subarray of size n, then the total number of subarrays po | kreakEmp | NORMAL | 2024-03-31T04:01:33.951009+00:00 | 2024-03-31T04:01:33.951038+00:00 | 341 | false | # Intuition\n- Each set of equal value divide the array into two separate array\n- On each non repeating subarray of size n, then the total number of subarrays possible = n(n+1)/2\n- But in the solution, in place of calculating n(n + 1)/2, we can iterate and add all numbers from 1 to n that is equal to n(n+1)/2\n\n# Approach \n- Iterate over each item in nums\n- When ever found nums[i] equal to last value then reset the counter\n- Add the counter value to answer on each iteration\n\n# Code\n```\nlong long countAlternatingSubarrays(vector<int>& nums) {\n long long ans = 0;\n for(int i = 0, count = 1; i < nums.size(); ++i, count++){\n if(i > 0 && nums[i] == nums[i-1]) count = 1;\n ans += count;\n }\n return ans;\n}\n```\n\n---\n\n\n<b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted\n\n---\n | 3 | 0 | ['C++'] | 1 |
count-alternating-subarrays | C++ 100% Faster | Sliding Window--->O(1) Space | Line By Line Detailed Explanation | c-100-faster-sliding-window-o1-space-lin-5j2f | \n\n# Intuition\n- An alternating subarray has no consecutive elements with the same value. We can iterate through the array and keep track of the current subar | VYOM_GOYAL | NORMAL | 2024-03-31T04:00:45.407175+00:00 | 2024-03-31T04:04:22.807087+00:00 | 138 | false | \n\n# Intuition\n- An alternating subarray has no consecutive elements with the same value. We can iterate through the array and keep track of the current subarray length while checking if adjacent elements differ. If they differ, we can increment the subarray length. Once we encounter two consecutive elements with the same value, we\'ve reached the end of the current subarray.\n- There\'s an interesting fact about counting the number of subarrays of a certain length: the number of subarrays of length k is equal to the sum of 1 + 2 + ... + k. This formula captures the idea that we can choose any starting index within the subarray of length k.\n\n# Approach\n1. **Sliding Window:**\n - We use a sliding window approach with two pointers (left and right) to track the current subarray.\n2. **Iterate and Check:**\n - As we iterate through the array using right, we check if the current element (nums[right]) is different from the next element (nums[right + 1]).\n - If they differ, it\'s part of an alternating subarray, so we increment right to extend the subarray.\n3. **Calculate and Update:**\n - Once we encounter two consecutive elements with the same value, we\'ve reached the end of the current subarray.\n - We calculate the number of subarrays within the current subarray length using the formula (length * (length + 1)) / 2. This leverages the fact mentioned in the intuition.\n - We add this count to the overall count of alternating subarrays.\nWe update the left pointer to right to start a new subarray from the next element.\n\n# Implementation\n- The provided code effectively implements the sliding window approach with the mentioned formula. Here\'s a breakdown:\n\n1. **int countAlternatingSubarrays(vector<int>& nums):** This function takes the binary array nums as input.\n\n2. **int n = nums.size();:** Gets the size of the array n.\n - **long long count = 0;:** Initializes a variable count to store the total number of alternating subarrays.\n \n3. **int left = 0;:** Initializes left and right pointers, both starting at index 0.\n\n - **int right = 0;**\n4. **while (right < n):** A loop that continues as long as right hasn\'t reached the end of the array.\n\n5. **while (right < n - 1 && nums[right] != nums[right + 1]):** This inner loop extends the current subarray as long as adjacent elements differ.\n - It checks if right is within bounds and if the elements at right and right + 1 are different.\n - If they differ, we increment right to include the next element in the subarray.\n6. **long long length = right - left + 1;:** Calculates the length of the current subarray (right - left + 1).\n\n7. **count += static_cast<long long>(length * (length + 1)) / 2;:** Calculates the number of subarrays within the current subarray length and adds it to the count.\n\n - The casting to long long ensures we don\'t overflow for larger length values.\n8. **right++;:** Moves the right pointer forward to start a new subarray from the next element.\n\n9. **left = right;:** Updates the left pointer to the same position as right, effectively starting a new subarray.\n\n10. **return count;:** After the loop finishes iterating through the entire array, count holds the total number of alternating subarrays, which is returned\n\n# Complexity\n- Time complexity **O(n)**\n - The code iterates through the array at most twice (once in the outer loop and potentially once in the inner loop for each element). This results in a linear time complexity of O(n).\n\n- Space complexity: **O(1)**\n - The code uses a constant amount of extra space for variables like count, left, and right, which doesn\'t depend on the input size n.\n\n# Code\n```\n#pragma GCC optimize("03", "unroll-loops")\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n int n = nums.size();\n long long count = 0; \n \n int left = 0;\n int right = 0;\n \n while (right < n) {\n while (right < n - 1 && nums[right] != nums[right + 1]) {\n right++;\n }\n \n long long length = right - left + 1;\n \n count += static_cast<long long>(length * (length + 1)) / 2;\n \n right++;\n left = right;\n }\n \n return count;\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\n\n | 3 | 1 | ['Array', 'Sliding Window', 'C++'] | 2 |
count-alternating-subarrays | ✅💯🔥Simple Code🚀📌|| 🔥✔️Easy to understand🎯 || 🎓🧠Beats 100%🔥|| Beginner friendly💀💯 | simple-code-easy-to-understand-beats-100-78nn | 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 | atishayj4in | NORMAL | 2024-07-31T20:12:55.043138+00:00 | 2024-08-01T19:26:46.482244+00:00 | 101 | 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 public long countAlternatingSubarrays(int[] nums) {\n long ans = 1;\n int sub=0;\n int prev=nums[0];\n for(int i=1; i<nums.length; i++){\n if(nums[i]!=prev){\n ans+=(i-sub);\n } else{\n sub=i;\n }\n ans+=1;\n prev=nums[i];\n }\n return ans;\n }\n}\n```\n | 2 | 0 | ['Array', 'Math', 'C', 'Python', 'C++', 'Java'] | 0 |
count-alternating-subarrays | O(N) time and easy simple solution. | on-time-and-easy-simple-solution-by-21bc-brdc | Intuition\nCount number of continueous alternating number and all possible subarray that can be made using it. \n\n# Approach\nuse long to store the and take ca | 21bcs069 | NORMAL | 2024-04-03T07:55:25.792996+00:00 | 2024-04-03T07:55:25.793031+00:00 | 11 | false | # Intuition\nCount number of continueous alternating number and all possible subarray that can be made using it. \n\n# Approach\nuse long to store the and take care of overflow , count alternating 0 and 1 continueous if it break add answer to it and then at last add the last the left subarray. which i did after completing for loop.\n\n# Complexity\n- Time complexity:\nO(N)\n\n# Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans=0;\n int count=1;\n for(int i=1 ; i<nums.size(); i++)\n {\n if(nums[i]==nums[i-1])\n {\n ans+=(1ll*count*1ll*(count+1))/2;\n count=1; // to start new counting of alternates\n }\n else{\n count++;\n }\n }\n ans+=(1ll*count*1ll*(count+1))/2;\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'Math', 'C++'] | 0 |
count-alternating-subarrays | Python || O(1) Space🔥🔥|| DP | python-o1-space-dp-by-vinaypabba48-y88v | \n# Approach 1 (Uses O(N) Time)\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. | vinaypabba48 | NORMAL | 2024-03-31T11:19:50.073596+00:00 | 2024-03-31T11:19:50.073616+00:00 | 22 | false | \n# Approach 1 (Uses O(N) Time)\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:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n dp=[1]*len(nums) #Dp[i] represents num of subarrays upto i.\n \n for i in range(1,len(nums)):\n if nums[i]!=nums[i-1]: # if curr elemenet is not equal to previous element, then it can be the part of our subarray\n \n dp[i]=dp[i-1]+dp[i] # total subarrays upto prev+subarray with 1 current element \n \n return sum(dp)\n \n```\n# Approach 2 (Uses O(1) Space)\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n #dp=[1]*len(nums)\n s=1 # sum with only \n curr=1\n for i in range(1,len(nums)):\n if nums[i]!=nums[i-1]:\n curr=curr+1\n s+=curr\n else:\n curr=1\n s+=curr\n \n return s\n``` | 2 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
count-alternating-subarrays | 🔥Easy to Understand | Clean Code | C++ | | easy-to-understand-clean-code-c-by-antim-aq6p | Code\n\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long left = 0;\n long long res = nums.size( | Antim_Sankalp | NORMAL | 2024-03-31T10:45:58.956021+00:00 | 2024-04-06T12:58:10.058843+00:00 | 215 | false | # Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long left = 0;\n long long res = nums.size();\n long long i;\n for (i = 1; i < nums.size(); i++) \n {\n if (nums[i] != nums[i - 1])\n continue;\n\n long long len = i - left;\n res += (len * (len - 1) / 2);\n left = i;\n }\n \n long long len = i - left;\n if (i >= 2 && left != i)\n res += (len * (len - 1) / 2);\n\n return res;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
count-alternating-subarrays | simple | easy java solution | simple-easy-java-solution-by-rini03-v018 | Complexity\n- Time complexity:\nlinear time complexity O(n)\n\n- Space complexity:\nconstant space complexity O(1)\n\n# Code\n\nclass Solution {\n public lon | rini03 | NORMAL | 2024-03-31T07:48:40.441396+00:00 | 2024-03-31T07:51:01.996591+00:00 | 184 | false | # Complexity\n- Time complexity:\nlinear time complexity O(n)\n\n- Space complexity:\nconstant space complexity O(1)\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long count = 1;\n int start = 0; \n int end = 0;\n\n for (int i = 1; i < nums.length; i++) {\n end++;\n if (nums[i] == nums[i - 1]) {\n start = end;\n }\n \n count += end - start + 1;\n }\n\n return count;\n }\n}\n``` | 2 | 0 | ['Two Pointers', 'Sliding Window', 'Java'] | 1 |
count-alternating-subarrays | Dynamic programming|| Beats 100% | dynamic-programming-beats-100-by-niteshj-qunz | 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 | niteshjha01 | NORMAL | 2024-03-31T04:15:06.237790+00:00 | 2024-03-31T04:15:06.237818+00:00 | 367 | 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 public long countAlternatingSubarrays(int[] nums) {\n int n = nums.length;\n int[] dp = new int[n]; \n long count = 1; \n \n dp[0] = 1; \n \n for (int i = 1; i < n; i++) {\n if (nums[i] != nums[i - 1]) {\n \n dp[i] = dp[i - 1] + 1;\n } else {\n \n dp[i] = 1;\n }\n count += dp[i];\n }\n \n return count;\n }\n}\n\n``` | 2 | 0 | ['Dynamic Programming', 'Java'] | 3 |
count-alternating-subarrays | Simple C++ || Beginner Friendly || Beats 100% | simple-c-beginner-friendly-beats-100-by-advcj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n1. Initialize variables n to store the size of the input array nums, cn | dibendu07 | NORMAL | 2024-03-31T04:03:40.193782+00:00 | 2024-03-31T04:03:40.193814+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n1. Initialize variables `n` to store the size of the input array `nums`, `cnt` to store the count of alternating subarrays, and `len` to store the length of the current alternating subarray, initially set to 1.\n\n2. Iterate through the array `nums` starting from index 1.\n \n a. If the current element (`nums[i]`) is different from the previous element (`nums[i-1]`), increment the `len` variable to extend the current alternating subarray.\n \n b. If the current element is the same as the previous one, calculate the number of subarrays formed by the current alternating subarray (using the formula for sum of natural numbers), add it to `cnt`, and reset `len` to 1 to start a new subarray.\n\n3. After the loop, add the count of the last alternating subarray (if any) to `cnt`.\n\n4. Finally, return the value of `cnt`, which represents the total number of alternating subarrays.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long n = nums.size(), cnt=0 ,len=1;\n for (long long i=1; i<n; ++i) {\n if(nums[i] != nums[i-1]) {\n len++;\n }else{\n long long x = (len*(len + 1))/2;\n cnt+=x, len = 1;\n }\n }\n cnt += (len*(len + 1))/2;\n return cnt;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
count-alternating-subarrays | Beats 100% | Easy Java Solution | ✅✅✅✅ | beats-100-easy-java-solution-by-ikapoor1-yp72 | Please Upvote \u2705\u2705\n\n# Code\n\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long ans = 1;\n int count = 0; | Ikapoor123 | NORMAL | 2024-03-31T04:02:44.726336+00:00 | 2024-03-31T04:16:12.039542+00:00 | 136 | false | # Please Upvote \u2705\u2705\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long ans = 1;\n int count = 0;\n \n for(int i=1;i<nums.length;i++){\n ans++;\n if(nums[i]+nums[i-1] == 1) {\n ans+=(i-count);\n }\n else count=i;\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Math', 'Counting', 'Java'] | 0 |
count-alternating-subarrays | O(1) space and O(n) time - DP Approach Java | o1-space-and-on-time-dp-approach-java-by-m16r | IntuitionApproachDp approach using two variablesComplexity
Time complexity: O(n)
Space complexity: O(1)
Code | dhivya6613 | NORMAL | 2025-02-03T13:31:37.558455+00:00 | 2025-02-03T13:31:37.558455+00:00 | 67 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
Dp approach using two variables
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public long countAlternatingSubarrays(int[] nums) {
int n = nums.length, incLength = 1;
long maxLength = 1;
for(int i=1; i<n; i++){
incLength = (nums[i-1]!=nums[i]) ? incLength+1 : 1;
maxLength += incLength;
}
return maxLength;
}
}
``` | 1 | 0 | ['Dynamic Programming', 'Java'] | 0 |
count-alternating-subarrays | Easy 5 lines C++ Solution | easy-5-lines-c-solution-by-pushuu-uwvq | Intuition\n Describe your first thoughts on how to solve this problem. \nYou are tasked with counting the number of alternating subarrays in an array, where alt | pushuu | NORMAL | 2024-09-14T16:24:43.087508+00:00 | 2024-09-14T16:24:43.087527+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou are tasked with counting the number of alternating subarrays in an array, where alternating subarrays are defined as subarrays whose adjacent elements alternate between two different values. The key insight is that if two adjacent elements alternate, any subarray formed by extending the alternating property contributes to the count.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1-Start from the second last element and check if it alternates with the next element.\n\n2-If they alternate, increment the current count curr, otherwise reset curr to 0.\n\n3-Add the current count plus 1 (since the current element itself forms a subarray) to the total sum sm.\n\n4-The total number of alternating subarrays is stored in sm.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe algorithm iterates over the array once, so the time complexity is \n\uD835\uDC42(\uD835\uDC5B) where n is the number of elements in the input array nums.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is \uD835\uDC42(1)since only a few extra variables (sm, curr, etc.) are used, regardless of the size of the input.\n\n# Dry Run\nLet\'s do a dry run on the test case nums = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1] with your provided solution.\n\nInitialization:\nsm = 1 (since the last element always forms a valid subarray of length 1)\ncurr = 0\nn = 16 (length of the array)\nIteration (starting from i = n - 2 = 14 and going down to i = 0):\ni = 14:\n\nnums[14] = 0, nums[15] = 1\nThey alternate, so curr = 1 + curr = 1 + 0 = 1\nsm = sm + (1 + curr) = 1 + 1 + 1 = 3\ni = 13:\n\nnums[13] = 1, nums[14] = 0\nThey alternate, so curr = 1 + curr = 1 + 1 = 2\nsm = sm + (1 + curr) = 3 + 1 + 2 = 6\ni = 12:\n\nnums[12] = 0, nums[13] = 1\nThey alternate, so curr = 1 + curr = 1 + 2 = 3\nsm = sm + (1 + curr) = 6 + 1 + 3 = 10\ni = 11:\n\nnums[11] = 1, nums[12] = 0\nThey alternate, so curr = 1 + curr = 1 + 3 = 4\nsm = sm + (1 + curr) = 10 + 1 + 4 = 15\ni = 10:\n\nnums[10] = 0, nums[11] = 1\nThey alternate, so curr = 1 + curr = 1 + 4 = 5\nsm = sm + (1 + curr) = 15 + 1 + 5 = 21\ni = 9:\n\nnums[9] = 0, nums[10] = 0\nThey don\'t alternate, so curr = 0\nsm = sm + (1 + curr) = 21 + 1 + 0 = 22\ni = 8:\n\nnums[8] = 1, nums[9] = 0\nThey alternate, so curr = 1 + curr = 1 + 0 = 1\nsm = sm + (1 + curr) = 22 + 1 + 1 = 24\ni = 7:\n\nnums[7] = 0, nums[8] = 1\nThey alternate, so curr = 1 + curr = 1 + 1 = 2\nsm = sm + (1 + curr) = 24 + 1 + 2 = 27\ni = 6:\n\nnums[6] = 1, nums[7] = 0\nThey alternate, so curr = 1 + curr = 1 + 2 = 3\nsm = sm + (1 + curr) = 27 + 1 + 3 = 31\ni = 5:\n\nnums[5] = 0, nums[6] = 1\nThey alternate, so curr = 1 + curr = 1 + 3 = 4\nsm = sm + (1 + curr) = 31 + 1 + 4 = 36\ni = 4:\n\nnums[4] = 1, nums[5] = 0\nThey alternate, so curr = 1 + curr = 1 + 4 = 5\nsm = sm + (1 + curr) = 36 + 1 + 5 = 42\ni = 3:\n\nnums[3] = 0, nums[4] = 1\nThey alternate, so curr = 1 + curr = 1 + 5 = 6\nsm = sm + (1 + curr) = 42 + 1 + 6 = 49\ni = 2:\n\nnums[2] = 1, nums[3] = 0\nThey alternate, so curr = 1 + curr = 1 + 6 = 7\nsm = sm + (1 + curr) = 49 + 1 + 7 = 57\ni = 1:\n\nnums[1] = 0, nums[2] = 1\nThey alternate, so curr = 1 + curr = 1 + 7 = 8\nsm = sm + (1 + curr) = 57 + 1 + 8 = 66\ni = 0:\n\nnums[0] = 1, nums[1] = 0\nThey alternate, so curr = 1 + curr = 1 + 8 = 9\nsm = sm + (1 + curr) = 66 + 1 + 9 = 76\nFinal Result:\nThe total sum of alternating subarrays is 76.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long sm = 1, curr = 0;\n int n = nums.size();\n for(int i=n-2;i>=0;i--){\n if(nums[i] != nums[i+1])curr = 1+curr;\n else curr = 0;\n sm += (1+curr);\n }\n return sm;\n }\n};\n``` | 1 | 0 | ['Array', 'Math', 'C++'] | 0 |
count-alternating-subarrays | Beats 98% | beats-98-by-mdsrrkhan-qkvf | \n# Code\n\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int prev = nums[0];\n long count = 1;\n long ans = | mdsrrkhan | NORMAL | 2024-08-08T13:55:40.263165+00:00 | 2024-08-08T13:55:40.263199+00:00 | 7 | false | \n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int prev = nums[0];\n long count = 1;\n long ans = 0;\n for(int i = 1;i<nums.length;i++){\n if(nums[i]==1-prev){\n count++; \n }else{\n ans = ans+ (count*(count+1)/2);\n count = 1;\n }\n prev = nums[i]; \n }\n return ans+(count*(count+1)/2);\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
count-alternating-subarrays | ONE FOR LOOP!!!! | one-for-loop-by-hitesh__raj-omwr | 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 | Hitesh__Raj | NORMAL | 2024-08-03T05:05:24.616719+00:00 | 2024-08-03T05:05:24.616757+00:00 | 43 | 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(object):\n def countAlternatingSubarrays(self, nums):\n n=len(nums)\n nums.append(nums[-1])\n x=n\n t=0\n for i in range(1,n+1):\n if(nums[i]==nums[i-1]):\n x+=((t*(t+1))//2)\n t=0\n else:\n t+=1\n return x\n \n``` | 1 | 0 | ['Python'] | 0 |
count-alternating-subarrays | SIMPLE SOLUTION!!!(PYTHON) | simple-solutionpython-by-hitesh__raj-yuzj | 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 | Hitesh__Raj | NORMAL | 2024-08-03T05:04:30.506690+00:00 | 2024-08-03T05:04:30.506728+00:00 | 12 | 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(object):\n def countAlternatingSubarrays(self, nums):\n n=len(nums)\n nums.append(nums[-1])\n x=n\n t=0\n for i in range(1,n+1):\n if(nums[i]==nums[i-1]):\n x+=((t*(t+1))//2)\n t=0\n else:\n t+=1\n return x\n \n``` | 1 | 0 | ['Python'] | 0 |
count-alternating-subarrays | Simple Maths || C++ Solution | simple-maths-c-solution-by-nehagupta_09-p5iv | \n\n# Code\n\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans=0;\n long long len=1;\n | NehaGupta_09 | NORMAL | 2024-07-07T06:22:37.936487+00:00 | 2024-07-07T06:22:37.936517+00:00 | 0 | false | \n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans=0;\n long long len=1;\n for(int i=1;i<nums.size();i++)\n {\n if(nums[i]!=nums[i-1])\n {\n len++;\n }\n else\n {\n ans=ans+((len*(len+1))/2);\n len=1;\n }\n }\n ans=ans+((len*(len+1))/2);\n return ans;\n }\n};\n``` | 1 | 0 | ['Array', 'Math', 'C++'] | 0 |
count-alternating-subarrays | Fastest and Easiest Answer with Explanation || Dynamic Programming || Beats 98.92% of users | fastest-and-easiest-answer-with-explanat-yr0b | Approach\n Describe your approach to solving the problem. \nSolving the problem by using Dynamic Programming\n# Complexity\n- Time complexity:O(n)\n Add your ti | Saidakbar_Zokirovich | NORMAL | 2024-04-19T12:11:53.639501+00:00 | 2024-04-19T12:12:42.104176+00:00 | 38 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nSolving the problem by using Dynamic Programming\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n// Use Dynamic Programming to solve the problem\n// Make a grid like this\n// nums = [0,1,1,1]\n//\n// | | 0 | 1 | 1 | 1 |\n// ---------------------\n// | 0 | | | | |\n// ---------------------\n// | 1 | | | | |\n// ---------------------\n// | 1 | | | | |\n// ---------------------\n// | 1 | | | | |\n\n// Then you should iterate from begin to the end of the list\n// And check if the letter before the corrent digit is not\n// the same digit do that add one to the count of the current \n// subarray and put into the index [i][i] of the grid\n// If it is not do that put 1 into the index [i][i] of the grid\n\n// | | 0 | 1 | 1 | 1 |\n// ---------------------\n// | 0 | 1 | | | |\n// ---------------------\n// | 1 | | 2 | | |\n// ---------------------\n// | 1 | | | 1 | |\n// ---------------------\n// | 1 | | | | 1 |\n\n// each index of the grid tells how many alternating subarray\n// you can make by using this number which is in the index of\n// nums. For example: in second column there is 2. It means\n// alternating subarray by using the number 1: 0,1 and 1.\n\n// After filling the grid, return sum of the number of \n// alternating subarray by using the number which is in the index of nums.\n\n\nfunc countAlternatingSubarrays(nums []int) int64 {\n numberOfSubarray := 1\n sizeOfLastSabarray := 1\n for i := 1; i < len(nums); i++ {\n // Ckeck alternating or not\n if nums[i] != nums[i-1] {\n sizeOfLastSabarray += 1\n }else {\n sizeOfLastSabarray = 1\n }\n // Add the number of alternating subarray \n // by using the number which is in the index of nums\n numberOfSubarray += sizeOfLastSabarray\n }\n\n return int64(numberOfSubarray)\n}\n``` | 1 | 0 | ['Dynamic Programming', 'Go'] | 1 |
count-alternating-subarrays | Easy Solution using Dynamic Programming concept | easy-solution-using-dynamic-programming-5qp69 | \n# Approach\n Describe your approach to solving the problem. \nDynamic Programming\nConcept is same but without array adding them up right away\n# Complexity\n | kmuhammadjon | NORMAL | 2024-04-19T11:36:26.312844+00:00 | 2024-04-19T11:36:26.312874+00:00 | 21 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming\nConcept is same but without array adding them up right away\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc countAlternatingSubarrays(nums []int) int64 {\n var numberOfSubarrays int64\n var prev int64\n // prev is going to help to cal culate current subarrays len\n // if condition met and adding it to counter\n prev = 1\n numberOfSubarrays = 1\n for i := 1; i < len(nums); i++{\n if nums[i] != nums[i-1] {\n prev = prev + 1\n\n }else{\n prev = 1\n }\n numberOfSubarrays += prev\n }\n\n\n return numberOfSubarrays\n}\n``` | 1 | 0 | ['Array', 'Math', 'Dynamic Programming', 'Go'] | 1 |
count-alternating-subarrays | Simple C++ Solution || Counting || Easy To Understand | simple-c-solution-counting-easy-to-under-ji9f | \n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1)\n Add your space complexity here, e.g. O(n) \n\n# | Akshay1054 | NORMAL | 2024-04-04T15:48:27.315645+00:00 | 2024-04-04T15:48:27.315668+00:00 | 9 | false | \n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n int n=nums.size();\n long long res=1;\n long long check=0,curr=1;\n for(int i=1;i<n;i++){\n if(nums[i] != nums[i-1]){\n curr++;\n res += curr;\n }\n else{\n curr=1;\n res += curr;\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | ['Sliding Window', 'Counting', 'C++'] | 0 |
count-alternating-subarrays | Easy and basic approach||O(n)||Beats 98% | easy-and-basic-approachonbeats-98-by-ank-j19p | Intuition\n\nIntuition:\nThe code aims to count the number of alternating subarrays within the given array nums. An alternating subarray is defined as a contigu | Ankit--kr | NORMAL | 2024-04-03T21:00:45.832728+00:00 | 2024-04-03T21:00:45.832756+00:00 | 19 | false | # Intuition\n\nIntuition:\nThe code aims to count the number of alternating subarrays within the given array nums. An alternating subarray is defined as a contiguous subarray where adjacent elements have different values.\n\n# Approach\nInitialize variables right and left to track the boundaries of the current subarray and initialize ans to 0 to store the count of alternating subarrays.\nIterate through the array using a while loop until right reaches the second last element (n-1).\nWithin the loop, check if the current element (nums[right]) is different from the next element (nums[right+1]). If they are different, extend the current subarray by moving right pointer one step forward.\nIf the current element is equal to the next element, it indicates the end of the alternating subarray. Update left to be the index of the next element (right+1) and move right pointer one step forward.\nFor each iteration of the loop, update the count of alternating subarrays by adding the length of the current subarray (right - left + 1) to ans.\nFinally, return ans + 1 to account for the case when the whole array itself is an alternating subarray.\n\n# Complexity\n- Time complexity:\nThe while loop iterates through the array once, and within each iteration, constant-time operations are performed. Therefore, the time complexity is O(n), where n is the length of the input array nums.\n\n- Space complexity:\n The space complexity is O(1) because the algorithm uses only a constant amount of extra space regardless of the size of the input array.\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int n=nums.length;\n int right=0;\n int left=0;\n long ans=0;\n while(right<n-1){\n if(nums[right]!=nums[right+1]){\n right++;\n }else{\n left=right+1;\n right++;\n }\n ans+=right-left+1; \n }\n return ans+1;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
count-alternating-subarrays | AVS | avs-by-vishal1431-uss8 | 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 | Vishal1431 | NORMAL | 2024-04-02T22:34:42.048070+00:00 | 2024-04-02T22:34:42.048087+00:00 | 2 | 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 long long countAlternatingSubarrays(vector<int>& a) {\n long long ans=0,sum=1;\n for(int i=1;i<a.size();i++){\n if(a[i]!=a[i-1])sum++;\n else{\n ans+=((sum*(sum+1))/2);\n sum=1;\n }\n }\n ans+=((sum*(sum+1))/2);\n sum=1;\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
count-alternating-subarrays | C++ | Easy | c-easy-by-ak200199-29bo | 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 | AK200199 | NORMAL | 2024-04-02T09:12:21.238936+00:00 | 2024-04-02T09:12:21.238959+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:\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 long long countAlternatingSubarrays(vector<int>& nums) {\n long long count=1,res=nums.size(),n=nums.size();\n for(long long i=0;i<n-1;i++){\n if(nums[i]!=nums[i+1])count++;\n if(nums[i]!=nums[i+1]&&i==n-2){\n res=res-count+count*(count+1)/2;\n count=1;\n }\n if(nums[i]==nums[i+1]){\n res=res-count+count*(count+1)/2;\n count=1;\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
count-alternating-subarrays | Dynamic Programming: Count Alternating Subarrays Explained | dynamic-programming-count-alternating-su-8dkw | Intuition\nThe problem asks to count the number of alternating subarrays in the given array. An alternating subarray is defined as a contiguous subarray where t | pro_donkey | NORMAL | 2024-04-01T09:41:28.658381+00:00 | 2024-04-01T09:41:28.658401+00:00 | 94 | false | # Intuition\nThe problem asks to count the number of alternating subarrays in the given array. An alternating subarray is defined as a contiguous subarray where the elements alternate between being even and odd.\n\n# Approach\nTo solve this problem, we can use dynamic programming. We\'ll maintain a dynamic programming array `dp`, where `dp[i]` represents the length of the alternating subarray ending at index `i`. We initialize `dp[0]` to 1, as the subarray consisting of only the first element is always alternating.\n\nThen, we iterate through the array starting from index 1. At each index `i`, if the current element is different from the previous element, it means the current element can be added to the alternating subarray ending at index `i-1`, thus increasing its length by 1. Otherwise, if the current element is the same as the previous element, the alternating subarray ends at index `i-1`, and we start a new alternating subarray at index `i`.\n\nFinally, we return the sum of all elements in the `dp` array, which represents the total count of alternating subarrays in the given array.\n\n# Complexity\n- Time complexity: O(n), where n is the length of the input array `nums`.\n- Space complexity: O(n), as we use an additional array of size `n` to store the dynamic programming values.\n\n# Code\n```python\nfrom typing import List\n\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n n = len(nums)\n dp = [0] * n\n dp[0] = 1\n for i in range(1, n):\n if nums[i] != nums[i - 1]:\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = 1\n return sum(dp)\n | 1 | 0 | ['Python3'] | 0 |
count-alternating-subarrays | C++ || sliding window approach || beats 100% | c-sliding-window-approach-beats-100-by-a-4eb0 | \n# Code\n\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n int l = 0, r = 0, n = nums.size();\n long lo | Adnan_Alkam | NORMAL | 2024-03-31T23:30:20.153292+00:00 | 2024-03-31T23:30:20.153345+00:00 | 39 | false | \n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n int l = 0, r = 0, n = nums.size();\n long long ans = 0;\n \n while(r < n) {\n if (l != r && nums[r] == nums[r-1]) \n l = r;\n ans += r - l + 1;\n r++;\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'Sliding Window', 'C++'] | 0 |
count-alternating-subarrays | DP Solution if you need | dp-solution-if-you-need-by-___lovesh1808-vgxc | \n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(1)\n\n# Code\n\nfunc countAlternatingSubarrays(nums []int) int64 {\n return foo(nums, 0)\n}\ | ___lovesh1808___ | NORMAL | 2024-03-31T20:52:39.360030+00:00 | 2024-03-31T20:52:39.360062+00:00 | 29 | false | \n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(1)\n\n# Code\n```\nfunc countAlternatingSubarrays(nums []int) int64 {\n return foo(nums, 0)\n}\nfunc foo(nums []int, index int) int64 {\n if index == len(nums) {\n return 0\n }\n var sum int64 = 0\n for i := index; i < len(nums); i ++ {\n if i == 0 {\n sum += int64(1)\n continue\n }\n if nums[i] != nums[i - 1] {\n sum += int64(i - index + 1)\n } else {\n z := foo(nums[i:], 0)\n sum += z\n return sum\n }\n }\n return sum\n}\n``` | 1 | 0 | ['Dynamic Programming', 'Recursion', 'Go'] | 0 |
count-alternating-subarrays | Sliding window , C++ | sliding-window-c-by-code12repeat-d36h | Intuition\nuse sliding window approach\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\n Add your time compl | code12repeat | NORMAL | 2024-03-31T18:11:40.948571+00:00 | 2024-03-31T18:11:40.948593+00:00 | 28 | false | # Intuition\nuse sliding window approach\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 long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans=1,left=0;\n for(int i=1;i<nums.size();i++){\n if(nums[i]==nums[i-1])left=i;\n ans+=(i-left+1);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
count-alternating-subarrays | Super Easy C++ Solution | 4 lines codes | super-easy-c-solution-4-lines-codes-by-_-xsf0 | Code\n\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n if(nums.size() == 1) return 1;\n int i = 0, j = | _White_Rabbit_ | NORMAL | 2024-03-31T17:56:44.379249+00:00 | 2024-03-31T17:56:44.379289+00:00 | 8 | false | # Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n if(nums.size() == 1) return 1;\n int i = 0, j = 0;\n long long count = 0;\n while(j < nums.size() ) {\n count += (j-i+1);\n if(j < nums.size() - 1 && nums[j] == nums[j+1]) i = j+1;\n j++;\n }\n return count;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
count-alternating-subarrays | 1st Kotlin Solution | 1st-kotlin-solution-by-user3900b-0w0e | Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n fun countAlternatingSubarrays(nums: IntArray): Long {\n | user3900b | NORMAL | 2024-03-31T15:22:48.151383+00:00 | 2024-03-31T15:22:48.151402+00:00 | 12 | false | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n fun countAlternatingSubarrays(nums: IntArray): Long {\n var result = 1L\n var size = 1\n\n for (i in 1..nums.size-1) {\n size = if (nums[i-1] == nums[i]) 1 else size + 1\n result += size\n }\n\n return result\n }\n}\n``` | 1 | 0 | ['Kotlin'] | 0 |
count-alternating-subarrays | Simple and easy solution with comments, beats 90% ✅✅ | simple-and-easy-solution-with-comments-b-vl1o | \n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n | vaibhav2112 | NORMAL | 2024-03-31T13:43:45.834437+00:00 | 2024-03-31T13:43:45.834474+00:00 | 21 | false | \n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // long long countAlternatingSubarrays(vector<int>& arr) {\n // int i = 0 , j = 0, n = arr.size();\n // long long ans = 0;\n\n // while(j < n){\n // // check if j+1 < n, otherwise index out of bound here\n // if(j+1 < n && arr[j] != arr[j+1]){\n // j++;\n // }\n // // case of j == n-1 will be handeled here\n // else{\n // long long len = j - i + 1;\n // ans = ans + (len*(len+1))/2;\n // j++;\n // i = j;\n // }\n // }\n // return ans;\n // }\n\n\n // same logic using while loop\n long long countAlternatingSubarrays(vector<int>& arr) {\n int i = 0 , j = 0, n = arr.size();\n long long ans = 0;\n\n while(j < n){\n // check if j+1 < n, otherwise index out of bound here\n while(j+1 < n && arr[j] != arr[j+1]){\n j++;\n }\n long long len = j - i + 1;\n ans = ans + (len*(len+1))/2;\n j++;\n i = j;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
count-alternating-subarrays | Simple python3 solution | 766 ms - faster than 100.00% solutions | simple-python3-solution-766-ms-faster-th-xexe | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co | tigprog | NORMAL | 2024-03-31T13:04:14.533701+00:00 | 2024-03-31T13:04:14.533734+00:00 | 23 | false | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n result = 0\n prev = None\n length = 0\n for elem in nums:\n if elem == prev:\n length = 1\n else:\n length += 1\n result += length\n prev = elem\n return result\n``` | 1 | 0 | ['Math', 'Greedy', 'Counting', 'Python3'] | 0 |
count-alternating-subarrays | C++ | Easy and Short Sliding Window Approach | c-easy-and-short-sliding-window-approach-iw77 | Code\n\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans=0,i=0,j=0,n=nums.size();\n vector< | Shrutika_Pandey | NORMAL | 2024-03-31T10:46:19.369599+00:00 | 2024-03-31T10:46:19.369617+00:00 | 21 | false | # Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans=0,i=0,j=0,n=nums.size();\n vector<int> v;\n while(j<n){\n if(j==0 || nums[j]!=nums[j-1]){\n ans+=j-i+1; //counting all subarrays till the index\n }\n else{\n v.push_back(j);\n i=j;\n }\n j++;\n }\n //including the single value subarrays if not already included in ans due to surrounding same digits\n return ans+v.size();\n }\n};\n\n``` | 1 | 0 | ['Two Pointers', 'Sliding Window', 'C++'] | 0 |
count-alternating-subarrays | Simple Java Solution | simple-java-solution-by-rrr34-u7hr | Code\n\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int l=0;\n int r=0;\n long ans = 0;\n int p = -1 | rrr34 | NORMAL | 2024-03-31T09:40:07.207801+00:00 | 2024-03-31T09:40:07.207833+00:00 | 37 | false | # Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int l=0;\n int r=0;\n long ans = 0;\n int p = -1;\n while(r<nums.length){\n if(nums[r]==p){\n l = r;\n }\n ans += r-l+1;\n p =nums[r];\n \n r++;\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Two Pointers', 'Sliding Window', 'Java'] | 0 |
count-alternating-subarrays | Simple Java Solution | simple-java-solution-by-rrr34-u73x | Code\n\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int l=0;\n int r=0;\n long ans = 0;\n int p = -1 | rrr34 | NORMAL | 2024-03-31T09:40:04.995860+00:00 | 2024-03-31T09:40:04.995889+00:00 | 17 | false | # Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int l=0;\n int r=0;\n long ans = 0;\n int p = -1;\n while(r<nums.length){\n if(nums[r]==p){\n l = r;\n }\n ans += r-l+1;\n p =nums[r];\n \n r++;\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Two Pointers', 'Sliding Window', 'Java'] | 0 |
count-alternating-subarrays | VERY EASY C++ SOLUTION || Single FOR loop || Beginner's Friendly | very-easy-c-solution-single-for-loop-beg-96nu | Intuition\nTo count the number of alternating subarrays within the given array, we iterate through the array, keeping track of the length of alternating subarra | ishajangir2002 | NORMAL | 2024-03-31T09:08:06.412643+00:00 | 2024-03-31T09:08:06.412678+00:00 | 31 | false | # Intuition\nTo count the number of alternating subarrays within the given array, we iterate through the array, keeping track of the length of alternating subarrays encountered so far. Whenever we encounter a different element compared to the previous one, we increase the length of the alternating subarray. When the element is the same as the previous one, we calculate the number of alternating subarrays that can be formed using the current length of the subarray and add it to the answer. Finally, we return the total count of alternating subarrays.\n\n# Approach\nInitialize variables ans to store the final answer, n to store the size of the input vector, and cnt to keep track of the length of alternating subarrays.\nIterate through the elements of the vector starting from the second element.\nIf the current element is different from the previous one, increment the counter (cnt) to extend the length of the alternating subarray.\nIf the current element is the same as the previous one, calculate the number of alternating subarrays that can be formed using the current length of the subarray and add it to the answer. Reset the counter (cnt) to 1.\nAfter the loop, there might be remaining alternating subarrays that haven\'t been counted. Calculate and add them to the answer.\nReturn the final answer.\n\n# Complexity\n- Time complexity: O(n), where n is the size of the input vector. We traverse the array once.\n- Space complexity: O(1), as we are using only a constant amount of extra space regardless of the input size.\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long ans = 0;\n int n = nums.size();\n int cnt = 1;\n for (int i = 1; i < n; i++) {\n if (nums[i] != nums[i - 1]) {\n cnt++;\n } else {\n ans += ((1LL * cnt * (cnt + 1)) / 2);\n cnt = 1;\n }\n }\n ans += ((1LL * cnt * (cnt + 1)) / 2);\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
count-alternating-subarrays | Simply counting number of subarrays || 100% Beat || O(n) solution || C++ code | simply-counting-number-of-subarrays-100-erdsp | Keep counting number of subarrays ending at index i and keep adding to the answer. As soon as we get same adjacent number bring the counter back to 1.\n\nTime C | just_csk | NORMAL | 2024-03-31T08:52:49.220761+00:00 | 2024-03-31T09:02:37.009566+00:00 | 2 | false | **Keep counting number of subarrays ending at index i and keep adding to the answer. As soon as we get same adjacent number bring the counter back to 1.**\n\n**Time Complexity : O(n)\nSpace Complexity : O(1)**\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n int n = nums.size(), cnt = 1;\n long long ans = cnt;\n for(int i = 1; i < n; i++)\n {\n if(nums[i] != nums[i - 1])\n cnt++;\n else\n cnt = 1;\n \n ans += cnt;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Array', 'Counting', 'C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.