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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
distribute-candies | [Pyhton], hashmap, beats nearly 90% | pyhton-hashmap-beats-nearly-90-by-jasper-74wd | [Pyhton], hashmap, beats nearly 90%\nIf there is anything not perfect, please feel free to indicate my problems.\n\nclass Solution:\n def distributeCandies(s | jasper-w | NORMAL | 2020-04-12T15:05:52.155643+00:00 | 2020-04-12T15:05:52.155686+00:00 | 291 | false | **[Pyhton], hashmap, beats nearly 90%**\nIf there is anything not perfect, please feel free to indicate my problems.\n```\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n d = dict()\n dict_size = 0\n for num in candies:\n if num not in d:\n d[num] = 1\n dict_size += 1\n \n list_size = len(candies) // 2\n \n result = list_size if list_size < dict_size else dict_size\n return result\n``` | 3 | 0 | ['Python'] | 0 |
distribute-candies | Python3 - easy solution | python3-easy-solution-by-nablet-wzru | \nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n unique = len(set(candies))\n half = len(candies) // 2\n \n | nablet | NORMAL | 2019-09-16T06:14:23.832597+00:00 | 2019-09-16T06:14:23.832638+00:00 | 241 | false | ```\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n unique = len(set(candies))\n half = len(candies) // 2\n \n return unique if unique < half else half\n```\nRuntime: 912 ms, faster than 98.86% of Python3 online submissions for Distribute Candies.\nMemory Usage: 15.8 MB, less than 8.33% of Python3 online submissions for Distribute Candies. | 3 | 1 | [] | 0 |
distribute-candies | C++ 2 line solution, Using Hash Set | c-2-line-solution-using-hash-set-by-pooj-piw6 | Runtime: 284 ms, faster than 72.52% of C++ online submissions for Distribute Candies.\nMemory Usage: 51.1 MB, less than 33.33% of C++ online submissions for Dis | pooja0406 | NORMAL | 2019-09-04T08:17:02.611509+00:00 | 2019-09-04T08:17:02.611541+00:00 | 464 | false | Runtime: 284 ms, faster than 72.52% of C++ online submissions for Distribute Candies.\nMemory Usage: 51.1 MB, less than 33.33% of C++ online submissions for Distribute Candies.\n\n```\nint distributeCandies(vector<int>& candies) {\n \n unordered_set<int> mp;\n for(int i : candies) mp.insert(i);\n \n return min(candies.size()/2, mp.size());\n } | 3 | 0 | ['C', 'C++'] | 1 |
distribute-candies | Ruby solution | ruby-solution-by-stefanpochmann-vrsa | \ndef distribute_candies(candies)\n [candies.uniq.size, candies.size / 2].min\nend\n | stefanpochmann | NORMAL | 2017-05-07T06:08:03.441000+00:00 | 2018-08-10T19:54:55.552610+00:00 | 410 | false | ```\ndef distribute_candies(candies)\n [candies.uniq.size, candies.size / 2].min\nend\n``` | 3 | 1 | [] | 2 |
distribute-candies | easy solution to wrap around👌 | easy-solution-to-wrap-around-by-flashpog-9e6c | IntuitionYou're given an array candyType representing types of candies. The Goal is to maximize the number of diffrent candies one can get
The total number of c | flashpogu | NORMAL | 2025-04-06T18:30:58.862437+00:00 | 2025-04-06T18:30:58.862437+00:00 | 59 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
You're given an array candyType representing types of candies. The Goal is to **maximize the number of diffrent candies** one can get
- The total number of candies is n.
- The maximum number of candies one can get is n / 2.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Number of Candies she can eat is **n / 2**.
2. Count Diffrent Types of Candies.
3. Store unique candies to list **res**
4. If number of unique types is greater than or equal to **n / 2**, return **n / 2**
# Complexity
- Time complexity: ***O(n)***
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: ***O(n)***
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
res = []
candies = int(len(candyType) / 2)
hashmap = {}
for i in candyType:
hashmap[i] = hashmap.get(i, 0) + 1
for i in hashmap.keys():
res.append(i)
if len(res) >= candies:
return candies
if len(res) < candies:
return len(res)
``` | 2 | 0 | ['Array', 'Hash Table', 'Python3'] | 0 |
distribute-candies | Simple to understand code with correct variable names | Python3 solution ⚡ | simple-to-understand-code-with-correct-v-qh2z | Code | thiyophin22 | NORMAL | 2025-04-05T13:38:42.612515+00:00 | 2025-04-05T13:38:42.612515+00:00 | 28 | false | # Code
```python3 []
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
unique_number_type_of_candies = len(set(candyType))
candies_allowed_to_eat = len(candyType) // 2
return min(candies_allowed_to_eat, unique_number_type_of_candies)
``` | 2 | 0 | ['Python3'] | 0 |
distribute-candies | Easy Cpp | Using map | Beginner Friendly | easy-cpp-using-map-beginner-friendly-by-nfi7l | Intuition
Alice wants to eat half of the candies.
We need to maximize the number of different types she eats.
If the number of unique candy types is less than n | Abhishek-Verma01 | NORMAL | 2025-03-17T11:25:22.626895+00:00 | 2025-03-17T11:25:22.626895+00:00 | 151 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
* Alice wants to eat half of the candies.
* We need to maximize the number of different types she eats.
* If the number of unique candy types is less than n/2, she gets all unique ones.
* If there are more unique types, she can only eat n/2.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Count the total candies (n) and the maximum Alice can eat (n/2).
2. Use a map to count unique candy types.
3. Compare unique candy count (avail) with n/2:
* If avail < n/2, return avail (Alice gets all unique ones).
* Otherwise, return n/2 (Alice eats the allowed half).
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n)
# Code
```cpp []
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
int n = candyType.size(); // Get the total number of candies
int eat = n / 2; // Maximum candies Alice can eat (half of total)
map<int, int> mp; // Use a map to count unique candy types
for(int i : candyType) {
mp[i]++; // Store the frequency of each candy type
}
int avail = mp.size(); // Count unique candy types
if(avail < eat) { // If unique types are less than the max Alice can eat
return avail; // She gets all unique types
}
return eat; // Otherwise, she gets the max allowed (n/2)
}
};
``` | 2 | 0 | ['Array', 'Hash Table', 'Ordered Map', 'C++'] | 0 |
distribute-candies | beats everyone | beats-everyone-by-asmit_kandwal-tdr1 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Asmit_Kandwal | NORMAL | 2025-01-05T14:29:31.404249+00:00 | 2025-01-05T14:29:31.404249+00:00 | 384 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
unordered_map<int,int> candycount;
for(auto candy : candyType){
candycount[candy]++;
}
int hashcount = candycount.size();
int halfsize = candyType.size()/2;
return min(hashcount,halfsize);
}
};
``` | 2 | 0 | ['C++'] | 0 |
distribute-candies | Python3 // ONE LINER // VERY EASY CODE | python3-one-liner-very-easy-code-by-alys-pmkd | Code | AlysWalys44 | NORMAL | 2025-01-01T12:53:55.875234+00:00 | 2025-01-01T12:53:55.875234+00:00 | 358 | false | # Code
```python3 []
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
return int(min(len(candyType)/2,len(set(candyType))))
``` | 2 | 0 | ['Python3'] | 0 |
distribute-candies | Easy Solution in Java | easy-solution-in-java-by-rishabh_234-c79v | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is to distribute candies such that the sister gets the maximum number of di | r_90 | NORMAL | 2024-10-03T18:12:38.532408+00:00 | 2024-10-03T18:12:38.532443+00:00 | 621 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to distribute candies such that the sister gets the maximum number of different types of candies. Since the sister can only get half of the total candies, the goal is to maximize the number of unique candy types she receives.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use a Set to Track Unique Candies:\n - Create a Set to store unique candy types.\n - Iterate through the candyType array and add each candy type to the Set.\n1. Calculate the Maximum Number of Candies the Sister Can Get:\n - Calculate n, which is half the length of the candyType array.\n - Compare the size of the Set (number of unique candy types) with n.\n - If the number of unique candy types is greater than or equal to n, return n (since the sister can only get n candies).\n - Otherwise, return the size of the Set (since the sister can get all unique types).\n# **PLEASE UPVOTE**\n**feel free to ask**\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```java []\nclass Solution {\n public int distributeCandies(int[] candyType) {\n Set<Integer> set = new HashSet<>();\n\n for (var i : candyType) \n set.add(i);\n \n var n = candyType.length / 2;\n\n if (set.size() >= n) \n return n;\n else \n return set.size();\n }\n}\n``` | 2 | 0 | ['Array', 'Hash Table', 'Java'] | 0 |
distribute-candies | 🍬3 line code🍬🍭🍬🍭🍬🍭 | 3-line-code-by-vibin_raj_kk-ycag | 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 | vibin_raj_kk | NORMAL | 2024-05-25T06:31:28.314132+00:00 | 2024-05-25T06:31:28.314163+00:00 | 130 | 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```\n/**\n * @param {number[]} candyType\n * @return {number}\n */\nvar distributeCandies = function (candyType) {\n let x = candyType.length/2\n let arr = [... new Set(candyType)]\nreturn Math.min(x,arr.length)\n\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
distribute-candies | easy to understand JS | easy-to-understand-js-by-javad_pk-9ape | 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 | javad_pk | NORMAL | 2024-05-18T04:40:24.353690+00:00 | 2024-05-18T04:40:24.353720+00:00 | 250 | 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```\n/**\n * @param {number[]} arr\n * @return {number}\n */\nvar distributeCandies = function(arr) {\n return new Set([...arr]).size > arr.length/2 ? arr.length/2 : new Set([...arr]).size\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
distribute-candies | simple dimple | simple-dimple-by-sayedadinan-1oza | 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 | sayedadinan | NORMAL | 2024-01-27T04:17:41.796439+00:00 | 2024-01-27T04:17:41.796470+00:00 | 268 | 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 int distributeCandies(List<int> candyType) {\n int n=candyType.length ~/2;//length divided by two\n Set<int>s=candyType.toSet();//taking unique values by converting to set\n return n < s.length ? n : s.length ; // if(n<s.length){return n}else{return s.length}\n }\n }\n}\n``` | 2 | 0 | ['Dart'] | 1 |
distribute-candies | ✅✅Easy Solution using Set | easy-solution-using-set-by-udaydewasi_26-uaqu | Intuition\nVery easy approach using set let\'s understand it.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. First we define a | Udaydewasi_26 | NORMAL | 2023-11-02T19:59:40.138593+00:00 | 2023-11-02T19:59:40.138612+00:00 | 27 | false | # Intuition\n**Very easy approach using set let\'s understand it.**\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First we define a unordered_set.\n2. Now we fill set by using loop.\n3. Size of set is showing number of all deferent cnadies.\n4. There are a condition that Alice can eat maximum n/2 candies.\n5. If n/2 is less then size of set than answer will be n/2 otherwise \n answer will be size of set.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- **O(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- **O(N)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n unordered_set<int> temp;\n for(int i = 0; i < candyType.size(); i++){\n temp.insert(candyType[i]);\n }\n if(temp.size()>candyType.size()/2)\n return candyType.size()/2;\n return temp.size();\n }\n};\n``` | 2 | 0 | ['Array', 'Hash Table', 'C++'] | 0 |
distribute-candies | Use Set | Simple two liner | O(N) Time | O(N) space Complexity | use-set-simple-two-liner-on-time-on-spac-2yts | Intuition\nFind Unique and return minimum from unique or half of the array length\n\n# Approach\nWe need to find the maximum number of unique candy that she can | pawan481992 | NORMAL | 2023-11-02T19:54:38.582842+00:00 | 2023-11-02T19:55:33.636929+00:00 | 110 | false | # Intuition\nFind Unique and return minimum from unique or half of the array length\n\n# Approach\nWe need to find the maximum number of unique candy that she can eat. So first of all find the count of all unique candy. I used Java Set to find unique. Second thing to keep in mind was that she can\'t eat more than half of her candies. So return minimum from Unique and half of the array size. \n\nIf you like my approach, please up vote!!!\n\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n \n Set<Integer> set = new HashSet<>();\n for(int i: candyType) {\n set.add(i);\n } \n return Math.min(candyType.length/2, set.size());\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
distribute-candies | Using Set Simplest Solution | using-set-simplest-solution-by-roronoa_z-gbhz | 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 | roronoa_zoro05 | NORMAL | 2023-08-25T13:04:59.445488+00:00 | 2023-08-25T13:04:59.445513+00:00 | 47 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n int n=candyType.size();\n unordered_set<int>s;\n for(auto x: candyType){\n s.insert(x);\n }\n if(s.size()>n/2){\n return n/2;\n }\n return s.size();\n }\n};\n``` | 2 | 0 | ['Hash Table', 'Ordered Set', 'C++'] | 0 |
distribute-candies | Easy Approach in JAVA | easy-approach-in-java-by-nishanth_franci-fzic | 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 | NISHANTH_FRANCIS | NORMAL | 2023-08-17T03:57:00.312446+00:00 | 2023-08-17T03:57:00.312466+00:00 | 719 | 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 int distributeCandies(int[] candyType) {\n Set<Integer> set = new HashSet();\n for(int i:candyType) set.add(i);\n if(set.size()>(candyType.length/2))\n return candyType.length/2;\n return set.size();\n }\n}\n``` | 2 | 0 | ['Hash Table', 'C++', 'Java'] | 0 |
distribute-candies | C++ || Easy Approach || Using SET || T.C. O(N) | c-easy-approach-using-set-tc-on-by-ayush-6r89 | INTUTION :-\n can_eat finds the how many candies alice can eat\n using set we can find unique candies alice have \n \n if set_size==can_eat ( i.e. if number | ayushmishra101 | NORMAL | 2023-06-03T04:10:11.335176+00:00 | 2023-06-03T04:10:11.335206+00:00 | 222 | false | **INTUTION :-\n can_eat finds the how many candies alice can eat\n using set we can find unique candies alice have \n \n if set_size==can_eat ( i.e. if number of candies alice can eat is equals to unique candies alice has)\n return set_size or can_eat\n \n else if can_eat>set_size (i.e. if the number of candies alice can eat is greater than unique candies alice has)\n return set_size\n \n else can_eat<set_size (i.e. if the number of candies alice can eat is less than unique candies she has)\n return can_eat\n ***\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n int size=candyType.size();\n int can_eat=size/2;\n \n set<int>s;\n for(int i=0;i<size;i++){\n s.insert(candyType[i]);\n }\n \n int set_size=s.size();\n \n if(can_eat==set_size)\n return set_size;\n \n else if(can_eat>set_size)\n return set_size;\n \n return can_eat;\n }\n};\n```\n\n | 2 | 0 | ['C', 'Ordered Set'] | 1 |
distribute-candies | single line python code : | single-line-python-code-by-kd2425-1wnh | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nwe take the given array | kd2425 | NORMAL | 2023-06-01T14:52:19.600900+00:00 | 2023-06-01T14:52:19.600940+00:00 | 830 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe take the given array and make it a set and compare it with half of the length of the given array and take the least value among them \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(set(candyType)),len(candyType)//2)\n``` | 2 | 0 | ['Python3'] | 1 |
distribute-candies | Solution | solution-by-deleted_user-sm04 | C++ []\nclass Solution {\n public:\n int distributeCandies(vector<int>& candies) {\n bitset<200001> bitset;\n\n for (const int candy : candies)\n bi | deleted_user | NORMAL | 2023-04-11T14:28:51.655474+00:00 | 2023-04-11T16:03:42.864131+00:00 | 1,597 | false | ```C++ []\nclass Solution {\n public:\n int distributeCandies(vector<int>& candies) {\n bitset<200001> bitset;\n\n for (const int candy : candies)\n bitset.set(candy + 100000);\n\n return min(candies.size() / 2, bitset.count());\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n a=len(candyType)//2\n b=len(set(candyType))\n return min(a,b)\n```\n\n```Java []\nclass Solution {\n public int distributeCandies(int[] candyType) {\n\n int n= candyType.length;\n int min= Integer.MAX_VALUE;\n int max= Integer.MIN_VALUE;\n \n int typesOfNum= 0;\n\n for(int i : candyType) {\n min= Math.min(min, i);\n max= Math.max(max, i);\n }\n boolean arr[]= new boolean[max-min+1];\n\n for(int i : candyType) {\n int j= i - min;\n\n if(!arr[j]) {\n arr[j]= true;\n typesOfNum++;\n }\n }\n return Math.min(n/2, typesOfNum);\n }\n}\n```\n | 2 | 0 | ['C++', 'Java', 'Python3'] | 0 |
distribute-candies | C++ solution | 82.48% time, 54.53% space | used unordered set | c-solution-8248-time-5453-space-used-uno-3vcr | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(unique elements)\n Add your space complexity here, e.g. | photon_einstein | NORMAL | 2023-03-10T23:59:32.352517+00:00 | 2023-03-10T23:59:32.352556+00:00 | 824 | false | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(unique elements)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType);\n};\n/***************************************************************/\nint Solution::distributeCandies(vector<int>& candyType) {\n int i, n;\n unordered_set<int> s;\n n = candyType.size();\n for (i = 0; i < n; ++i) {\n s.insert(candyType[i]);\n }\n if (n/2 <= s.size()) {\n return n/2;\n } else {\n return s.size();\n }\n}\n/***************************************************************/\n\n``` | 2 | 0 | ['C++'] | 0 |
distribute-candies | 🔥 3 line Java solution🔥 | 3-line-java-solution-by-abdullakh-akfy | Code\n\nclass Solution {\n public int distributeCandies(int[] candyType) {\n Set<Integer> set = new HashSet();\n for (int i : candyType) set.ad | abdullakh | NORMAL | 2023-02-09T15:50:26.939501+00:00 | 2023-02-09T15:50:26.939548+00:00 | 1,206 | false | # Code\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n Set<Integer> set = new HashSet();\n for (int i : candyType) set.add(i);\n return Math.min(set.size(), candyType.length / 2);\n }\n}\n``` | 2 | 0 | ['Array', 'Hash Table', 'Java'] | 0 |
distribute-candies | Simple Explained Solution | simple-explained-solution-by-darian-cata-wczv | \n\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n int types_num = set<int>(candies.begin(), candies.end()).size();\n | darian-catalin-cucer | NORMAL | 2023-02-09T06:46:47.505668+00:00 | 2023-02-09T06:46:47.505720+00:00 | 2,493 | false | \n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n int types_num = set<int>(candies.begin(), candies.end()).size();\n return types_num > candies.size()/2 ? candies.size()/2 : types_num;\n }\n};\n``` | 2 | 0 | ['Swift', 'C++', 'Go', 'Ruby', 'Bash'] | 0 |
distribute-candies | 🔥Python||Python3|| esay soultion to understand🔥 | pythonpython3-esay-soultion-to-understan-8vnq | Approach\nMy approach was to loop over the candys, each candy I see I will add to the result counter and save it in a hashset. If we see a candy that already wa | vilkinshay | NORMAL | 2023-01-16T18:45:03.008915+00:00 | 2023-01-16T18:45:03.008949+00:00 | 2,381 | false | # Approach\nMy approach was to loop over the candys, each candy I see I will add to the result counter and save it in a hashset. If we see a candy that already was seen then we skip it, else we add it. we do it until we reached n/2 candys or we got to the end of the list.\n\n# Complexity\n- Time complexity:\nO(n) becuase we went over the array once\n\n- Space complexity:\nO(n) becuase we saved at most n/2 numbers.\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n seen = {}\n i = 0\n amount_allowed = 0\n while(i<len(candyType) and amount_allowed<len(candyType)//2):\n if seen.get(candyType[i],0)==0:\n amount_allowed+=1\n seen[candyType[i]] = 1\n i+=1\n return amount_allowed\n\n\n\n``` | 2 | 0 | ['Hash Table', 'Python', 'Python3'] | 0 |
distribute-candies | Beats 80% Beginner Friendly O(n) Solution 🔥🔥🔥🔥 | beats-80-beginner-friendly-on-solution-b-1eml | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nclass Solution {\n public int distributeCandies(int[] candyType) {\n\n | jaiyadav | NORMAL | 2023-01-04T05:35:14.975566+00:00 | 2023-01-04T05:35:14.975611+00:00 | 697 | false | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n\n Set<Integer>st=new HashSet<>();\n\n for(int i=0;i<candyType.length;i++){\n st.add(candyType[i]);\n if(st.size()>candyType.length/2)return candyType.length/2;\n }\n\n return st.size();\n\n }\n}\n``` | 2 | 0 | ['Array', 'Hash Table', 'Java'] | 0 |
distribute-candies | Javascript Noob Solution | javascript-noob-solution-by-shoshinsha_c-7dmf | Intuition\nI thought this was complicated because the description was a bit vague. I knew i needed a loop to go through the array and keep track of unique integ | shoshinsha_coder | NORMAL | 2022-12-13T08:02:14.301900+00:00 | 2022-12-13T08:02:14.301951+00:00 | 229 | false | # Intuition\nI thought this was complicated because the description was a bit vague. I knew i needed a loop to go through the array and keep track of unique integers.\n\n# Approach\nI started with an object to store my integers and a count of their occurances in an object(count{...}) Then i used an if statement to see if the amount of keys was less than the N /2 requirement. I would return the number of keys(unique integers) if so and else i\'d return N/2(candyType.length/2).\n(I\'m new to coding so trying to explain my reasoning is tough)\n# Complexity\n- Time complexity:\n??? O(n)\nnot sure\n\n- Space complexity:\n???\n# Code\n```\n/**\n * @param {number[]} candyType\n * @return {number}\n */\nvar distributeCandies = function(candyType) {\n var count = {};\n for(let i = 0; i<candyType.length; i++) {\n var num = candyType[i]\n count[num] = count[num] ? +1 : 1;\n }\n if(Object.keys(count).length < candyType.length/2) {\n return Object.keys(count).length\n } else {\n return candyType.length/2\n }\n };\n``` | 2 | 0 | ['JavaScript'] | 0 |
distribute-candies | JAVA | HashSet | Easy ✅ | java-hashset-easy-by-sourin_bruh-2uz9 | Please Upvote :D\n\nclass Solution {\n public int distributeCandies(int[] candyType) {\t\n Set<Integer> set = new HashSet<>();\n for (int c : c | sourin_bruh | NORMAL | 2022-11-27T20:21:07.101727+00:00 | 2022-11-27T20:21:50.920242+00:00 | 676 | false | ### **Please Upvote** :D\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\t\n Set<Integer> set = new HashSet<>();\n for (int c : candyType) set.add(c);\n\t\t\n return Math.min(set.size(), candyType.length / 2);\n }\n}\n\n// TC: O(n), SC: O(n)\n``` | 2 | 0 | ['Java'] | 0 |
distribute-candies | python||210ms||simplest approach|| using len,set and min | python210mssimplest-approach-using-lense-ouhv | \t\t\t\tclass Solution:\n\t\t\t\t\tdef distributeCandies(self, candyType: List[int]) -> int:\n\t\t\t\t\t\ta=len(candyType)//2\n\t\t\t\t\t\tb=len(set(candyType)) | 2stellon7 | NORMAL | 2022-09-27T20:10:12.526924+00:00 | 2022-09-27T20:10:12.527007+00:00 | 327 | false | \t\t\t\tclass Solution:\n\t\t\t\t\tdef distributeCandies(self, candyType: List[int]) -> int:\n\t\t\t\t\t\ta=len(candyType)//2\n\t\t\t\t\t\tb=len(set(candyType))\n\t\t\t\t\t\treturn min(a,b)\n | 2 | 0 | ['Python'] | 0 |
distribute-candies | JavaScript One Liner | javascript-one-liner-by-emerald_barium-94j4 | \nvar distributeCandies = function(candyType) {\n\t// The Set will remove all of the duplicates from candyType\n return Math.min(candyType.length / 2, new Se | emerald_barium | NORMAL | 2022-08-31T11:29:53.663897+00:00 | 2022-08-31T11:36:58.186907+00:00 | 315 | false | ```\nvar distributeCandies = function(candyType) {\n\t// The Set will remove all of the duplicates from candyType\n return Math.min(candyType.length / 2, new Set(candyType).size);\n};\n``` | 2 | 0 | ['Ordered Set', 'JavaScript'] | 1 |
distribute-candies | One liner [Python][Waku Waku] | one-liner-pythonwaku-waku-by-arimanyus-5bda | \nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return int(min(len(set(candyType)), len(candyType)/2))\n\n\n | arimanyus | NORMAL | 2022-08-16T15:58:28.050543+00:00 | 2022-08-16T15:58:28.050597+00:00 | 158 | false | ```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return int(min(len(set(candyType)), len(candyType)/2))\n```\n\n | 2 | 0 | ['Python'] | 1 |
distribute-candies | Java || Fastest || Without Set and Hashmap || Very Easy | java-fastest-without-set-and-hashmap-ver-e4g2 | ```\n public int distributeCandies(int[] candyType) {\n Arrays.sort(candyType);\n int type = candyType[0];\n int count = 1;\n for | jaydeepgodhani | NORMAL | 2022-07-31T14:52:09.221027+00:00 | 2022-07-31T14:52:09.221069+00:00 | 67 | false | ```\n public int distributeCandies(int[] candyType) {\n Arrays.sort(candyType);\n int type = candyType[0];\n int count = 1;\n for(int i:candyType){\n if(i!=type){\n count++;\n type=i;\n }\n }\n if(count<candyType.length/2) return count;\n else return candyType.length/2;\n } | 2 | 0 | ['Array', 'Sorting', 'Java'] | 0 |
distribute-candies | JAVA HashSet 5-Line code | java-hashset-5-line-code-by-yudhisthirsi-bd3e | class Solution {\n public int distributeCandies(int[] candyType) {\n HashSet h = new HashSet<>();\n int count = 0;\n for(int i =0 ;i< candyType | yudhisthirsinghcse2023 | NORMAL | 2022-05-18T08:23:09.246587+00:00 | 2022-05-18T08:23:09.246620+00:00 | 191 | false | class Solution {\n public int distributeCandies(int[] candyType) {\n HashSet<Integer> h = new HashSet<>();\n int count = 0;\n for(int i =0 ;i< candyType.length ; i++){\n \n h.add(candyType[i]);\n \n }\n return Math.min(candyType.length/2 , h.size());\n }\n} | 2 | 0 | ['Java'] | 0 |
distribute-candies | C solution || sorting || Easily Understandable || O(log n) | c-solution-sorting-easily-understandable-3138 | \nint cmp_func(const void *a, const void *b)\n{\n return (*(int *)a - *(int *)b);\n}\n\nint distributeCandies(int* candyType, int candyTypeSize)\n{ \n | revanthrajashe | NORMAL | 2022-03-23T00:51:19.278038+00:00 | 2022-03-23T00:51:19.278074+00:00 | 152 | false | ```\nint cmp_func(const void *a, const void *b)\n{\n return (*(int *)a - *(int *)b);\n}\n\nint distributeCandies(int* candyType, int candyTypeSize)\n{ \n int different_candy_cnt = 1;\n int edible_candies = candyTypeSize / 2;\n \n qsort(candyType, candyTypeSize, sizeof(int), cmp_func);\n \n for (int i = 0, j = 0; j < candyTypeSize; j++) {\n if (candyType[i] != candyType[j]) {\n i = j;\n different_candy_cnt++;\n }\n }\n \n return (edible_candies > different_candy_cnt) ? different_candy_cnt : edible_candies;\n}\n``` | 2 | 0 | ['C'] | 0 |
distribute-candies | Distribute Candies Solution Java | distribute-candies-solution-java-by-bhup-h193 | class Solution {\n public int distributeCandies(int[] candies) {\n BitSet bitset = new BitSet(200001);\n\n for (final int candy : candies)\n bitset. | bhupendra786 | NORMAL | 2022-03-22T06:47:26.415288+00:00 | 2022-03-22T06:47:26.415332+00:00 | 98 | false | class Solution {\n public int distributeCandies(int[] candies) {\n BitSet bitset = new BitSet(200001);\n\n for (final int candy : candies)\n bitset.set(candy + 100000);\n\n return Math.min(candies.length / 2, bitset.cardinality());\n }\n}\n | 2 | 0 | ['Array', 'Hash Table'] | 0 |
distribute-candies | Java using BitSet | java-using-bitset-by-red_hue-9f2f | \nclass Solution {\n int m = 100000;\n public int distributeCandies(int[] candyType) {\n BitSet bset = new BitSet();\n int count = 0;\n | red_hue | NORMAL | 2021-08-25T11:38:16.498308+00:00 | 2021-08-25T11:38:16.498355+00:00 | 47 | false | ```\nclass Solution {\n int m = 100000;\n public int distributeCandies(int[] candyType) {\n BitSet bset = new BitSet();\n int count = 0;\n int len = candyType.length/2;\n for(int i:candyType){\n if(!bset.get(i+m)) {\n if(++count == len) return count;\n bset.set(i+m);\n }\n }\n return count; \n }\n}\n``` | 2 | 0 | [] | 0 |
distribute-candies | Short & Sweet C++ Solution | short-sweet-c-solution-by-mananvarma5401-39sl | \nint distributeCandies(vector<int>& candyType) {\n set<int> s;\n for (auto i:candyType)\n s.insert(i);\n if (s.size() > candyTy | mananvarma5401 | NORMAL | 2021-08-09T10:55:51.042174+00:00 | 2021-08-09T10:55:51.042205+00:00 | 73 | false | ```\nint distributeCandies(vector<int>& candyType) {\n set<int> s;\n for (auto i:candyType)\n s.insert(i);\n if (s.size() > candyType.size()/2)\n return candyType.size()/2;\n else\n return s.size();\n }\n``` | 2 | 0 | [] | 0 |
distribute-candies | easy solution with explanation | easy-solution-with-explanation-by-sourav-qlw1 | * if you like the solution please vote so it can reach maximum people\n\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n | souravsingpardeshi | NORMAL | 2021-05-28T14:03:33.329450+00:00 | 2021-05-28T14:03:33.329488+00:00 | 169 | false | ### * if you like the solution please vote so it can reach maximum people\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n sl=len(list(set(candyType))) # count of different candies.\n a=len(candyType)/2 # count of how many he can eat.\n if a>sl: # if count of how many he can it is greter than count of available candies we return available candies count\n return int(sl) \n return int(a) # else if count of available candies is greter than he can eat we return maximum no. that is a which he can eat\n``` | 2 | 1 | ['Python', 'Python3'] | 0 |
distribute-candies | Easy Java | 4 lines code | easy-java-4-lines-code-by-praveensingh31-4o0p | ```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n HashSet set = new HashSet<>();\n for(int c : candyType) set.add(c);\n | praveensingh3128 | NORMAL | 2021-05-27T08:34:55.479634+00:00 | 2021-05-27T08:34:55.479688+00:00 | 71 | false | ```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n HashSet<Integer> set = new HashSet<>();\n for(int c : candyType) set.add(c);\n \n int eat = candyType.length/2;\n return set.size()<eat ? set.size() : eat;\n }\n} | 2 | 0 | [] | 0 |
distribute-candies | C++ | O(nlogn), Faster than 96.20% | Simple Solution | c-onlogn-faster-than-9620-simple-solutio-1vme | Alternate Solution here. \n\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n int unique = 1;\n sort(candyType.beg | prishitakadam | NORMAL | 2021-05-01T10:45:17.982440+00:00 | 2021-05-01T10:49:41.619295+00:00 | 147 | false | Alternate Solution [here](https://github.com/prishitakadam/LeetCode/blob/master/Problems/575.%20Distribute%20Candies.cpp). \n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n int unique = 1;\n sort(candyType.begin(), candyType.end());\n int* p = candyType.data();\n \n for(int i=0; i<candyType.size()-1; i++){\n if(p[i] != p[i+1])\n unique++;\n }\n \n if(unique < candyType.size()/2)\n return unique;\n else\n return candyType.size()/2;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
distribute-candies | faster than 98.69% of C++ online submissions | faster-than-9869-of-c-online-submissions-d3bm | I have first sorted the vector, then I have tried to find the unique element. \nAfter doing that, the code does either of the following:-\n1 . If number of dist | xenikh32 | NORMAL | 2021-03-19T01:34:18.940307+00:00 | 2021-03-19T01:34:18.940375+00:00 | 113 | false | I have first sorted the vector, then I have tried to find the unique element. \nAfter doing that, the code does either of the following:-\n1 . If number of distinct elements is less than half the size of the vector, return the former\n2. Else, return the latter.\n\nHere is the code:-\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n int disc = 0;\n sort(candyType.begin(),candyType.end());\n for(int i = 0;i < candyType.size();i++){\n while(i < candyType.size() - 1 && candyType[i] == candyType[i+1])\n i++;\n disc++;\n }\n int res = candyType.size()/2;\n if(disc > res)\n return res;\n return disc;\n } \n};\n```\n | 2 | 0 | [] | 0 |
distribute-candies | [C++] Distribute Candies | Using Set | c-distribute-candies-using-set-by-badhan-e3dw | In this problem we have to find the maximum number of different types of candies she can eat if she only eats n / 2 of them. So, \n Find unique candies by using | badhansen | NORMAL | 2021-03-01T21:33:20.533067+00:00 | 2021-06-16T15:29:47.888368+00:00 | 57 | false | In this problem we have to find the `maximum` number of different types of candies she can eat if she only eats `n / 2` of them. So, \n* Find unique candies by using a set\n* Return min of (unique candies(size of set) and half the no of candies)\n\n```c++\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n set<int> st;\n for(auto &el : candyType){\n st.insert(el);\n }\n int answer = min(st.size(), candyType.size() / 2);\n return answer;\n }\n};\n``` | 2 | 1 | [] | 0 |
distribute-candies | Java | Easy | Simple | O(n) time | java-easy-simple-on-time-by-sunflower96-9xv3 | \nclass Solution {\n public int distributeCandies(int[] candyType) {\n int n = candyType.length;\n HashSet < Integer > hs = new HashSet < Integ | SunFlower96 | NORMAL | 2021-03-01T18:40:36.187228+00:00 | 2021-03-01T18:40:36.187285+00:00 | 152 | false | ```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n int n = candyType.length;\n HashSet < Integer > hs = new HashSet < Integer > ();\n for (int i: candyType) {\n hs.add(i);\n }\n return hs.size() > (n / 2) ? n / 2 : hs.size();\n }\n}\n``` | 2 | 1 | [] | 1 |
distribute-candies | C++. One-liner Solution!!!!!!! | c-one-liner-solution-by-m-d-f-r4my | ```\nclass Solution {\npublic:\n int distributeCandies(vector& candyType) {\n return min(candyType.size() / 2, set(candyType.begin(), candyType.end()) | m-d-f | NORMAL | 2021-03-01T11:47:41.652219+00:00 | 2021-03-01T11:47:41.652245+00:00 | 122 | false | ```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n return min(candyType.size() / 2, set<int>(candyType.begin(), candyType.end()).size());\n }\n}; | 2 | 1 | ['C', 'C++'] | 0 |
distribute-candies | Distribute Candies C++ | O(N) 1-liner | easy-explained | distribute-candies-c-on-1-liner-easy-exp-n47m | The solution and observations upon which it is based is mentioned below: \n The answer to the question can be atmost candyType.size() / 2 since Alice can\'t eat | archit91 | NORMAL | 2021-03-01T09:17:17.463527+00:00 | 2021-03-01T15:51:57.976480+00:00 | 202 | false | The solution and observations upon which it is based is mentioned below: \n* The answer to the question can be atmost `candyType.size() / 2` since Alice can\'t eat more than half of the total candies.\n* We start by choosing different types of *candyType*. A chosen candyType will be inserted into a hashset so that we won\'t select the same one again. \n* The above step will be done iteratively till we either **reach the end of array** or number of chosen different candyType denoted by **`ans` becomes `candyType.size() / 2`**, since it can\'t be anymore than that.\n\nNote: The above loop might end even with only 1 candyType selected which may be less than the maximum `n/2` candy amount allowed to be selected. But we are only concerned with selecting **maximum different candyTypes** and not maximum candies. \n\n```\nint distributeCandies(vector<int>& candyType) {\n int ans = 0, n = candyType.size(), i = 0;\n unordered_set<int>s;\n \n while(i < n && ans < (n / 2)){\n if(s.find(candyType[i]) == s.end())\n s.insert(candyType[i]), ans++;\n i++;\n }\n return ans;\n}\n```\n\n**Time Complexity**: **`O(N)`**, for iterating once through `candyType` at max. Insertion into hashset has amortized time-complexity of `O(1)`.\n\n**Space Complexity**: **`O(N)`**, for maintaining the hashset.\n\n--------------------\nNow for those who came for 1-liners, the above solution can be compacted into a 1-liner as below (referred from [@votrubac\'s post](https://leetcode.com/problems/distribute-candies/discuss/102946/C%2B%2B-1-liner)) - \n```\nint distributeCandies(vector<int>& candyType) {\n return min(size(unordered_set<int>(begin(candyType), end(candyType))), size(candyType) / 2);\n}\n```\n\n | 2 | 0 | ['C'] | 0 |
spiral-matrix-ii | 4-9 lines Python solutions | 4-9-lines-python-solutions-by-stefanpoch-yjun | Solution 1: Build it inside-out - 44 ms, 5 lines\n\nStart with the empty matrix, add the numbers in reverse order until we added the number 1. Always rotate the | stefanpochmann | NORMAL | 2015-07-18T22:51:09+00:00 | 2018-10-18T15:58:31.726878+00:00 | 56,478 | false | **Solution 1: *Build it inside-out*** - 44 ms, 5 lines\n\nStart with the empty matrix, add the numbers in reverse order until we added the number 1. Always rotate the matrix clockwise and add a top row:\n\n || => |9| => |8| |6 7| |4 5| |1 2 3|\n |9| => |9 8| => |9 6| => |8 9 4|\n |8 7| |7 6 5|\n\nThe code:\n\n def generateMatrix(self, n):\n A, lo = [], n*n+1\n while lo > 1:\n lo, hi = lo - len(A), lo\n A = [range(lo, hi)] + zip(*A[::-1])\n return A\n\nWhile this isn't O(n^2), it's actually quite fast, presumably due to me not doing much in Python but relying on `zip` and `range` and `+` being fast. I got it accepted in 44 ms, matching the fastest time for recent Python submissions (according to the submission detail page).\n\n---\n\n**Solution 2: *Ugly inside-out*** - 48 ms, 4 lines\n\nSame as solution 1, but without helper variables. Saves a line, but makes it ugly. Also, because I access A[0][0], I had to handle the n=0 case differently.\n\n def generateMatrix(self, n):\n A = [[n*n]]\n while A[0][0] > 1:\n A = [range(A[0][0] - len(A), A[0][0])] + zip(*A[::-1])\n return A * (n>0)\n\n---\n\n**Solution 3: *Walk the spiral*** - 52 ms, 9 lines\n\nInitialize the matrix with zeros, then walk the spiral path and write the numbers 1 to n*n. Make a right turn when the cell ahead is already non-zero.\n\n def generateMatrix(self, n):\n A = [[0] * n for _ in range(n)]\n i, j, di, dj = 0, 0, 0, 1\n for k in xrange(n*n):\n A[i][j] = k + 1\n if A[(i+di)%n][(j+dj)%n]:\n di, dj = dj, -di\n i += di\n j += dj\n return A | 724 | 6 | ['Python'] | 98 |
spiral-matrix-ii | My Super Simple Solution. Can be used for both Spiral Matrix I and II | my-super-simple-solution-can-be-used-for-vwv5 | This is my solution for Spiral Matrix I, [https://oj.leetcode.com/discuss/12228/super-simple-and-easy-to-understand-solution][1]. If you can understand that, th | qwl5004 | NORMAL | 2014-10-24T04:14:11+00:00 | 2018-10-25T21:10:35.388949+00:00 | 54,750 | false | This is my solution for Spiral Matrix I, [https://oj.leetcode.com/discuss/12228/super-simple-and-easy-to-understand-solution][1]. If you can understand that, this one is a no brainer :)\n\nGuess what? I just made several lines of change (with comment "//change") from that and I have the following AC code:\n\n public class Solution {\n public int[][] generateMatrix(int n) {\n // Declaration\n int[][] matrix = new int[n][n];\n \n // Edge Case\n if (n == 0) {\n return matrix;\n }\n \n // Normal Case\n int rowStart = 0;\n int rowEnd = n-1;\n int colStart = 0;\n int colEnd = n-1;\n int num = 1; //change\n \n while (rowStart <= rowEnd && colStart <= colEnd) {\n for (int i = colStart; i <= colEnd; i ++) {\n matrix[rowStart][i] = num ++; //change\n }\n rowStart ++;\n \n for (int i = rowStart; i <= rowEnd; i ++) {\n matrix[i][colEnd] = num ++; //change\n }\n colEnd --;\n \n for (int i = colEnd; i >= colStart; i --) {\n if (rowStart <= rowEnd)\n matrix[rowEnd][i] = num ++; //change\n }\n rowEnd --;\n \n for (int i = rowEnd; i >= rowStart; i --) {\n if (colStart <= colEnd)\n matrix[i][colStart] = num ++; //change\n }\n colStart ++;\n }\n \n return matrix;\n }\n }\n\nObviously, you could merge colStart and colEnd into rowStart and rowEnd because it is a square matrix. But this is easily extensible to matrices that are m*n.\n\nHope this helps :)\n\n\n [1]: https://oj.leetcode.com/discuss/12228/super-simple-and-easy-to-understand-solution | 357 | 1 | ['Java'] | 47 |
spiral-matrix-ii | [Python] rotate, when need, explained | python-rotate-when-need-explained-by-dba-fu1e | Let us notice one clue property about our spiral matrix: first we need to go to the right and rotate clockwise 90 degrees, then we go down and again when we rea | dbabichev | NORMAL | 2020-12-07T09:02:05.016751+00:00 | 2020-12-07T09:05:59.616041+00:00 | 6,669 | false | Let us notice one clue property about our spiral matrix: first we need to go to the right and rotate clockwise 90 degrees, then we go down and again when we reached bottom, we rotate 90 degrees clockwise and so on. So, all we need to do is to rotate 90 degrees clockwise when we need:\n1. When we reached border of our matrix\n2. When we reached cell which is already filled.\n\nLet `x, y` be coordinates on our `grid` and `dx, dy` is current direction we need to move. In geometrical sense, rotate by `90` degrees clockwise is written as `dx, dy = -dy, dx`.\n\nNote, that `matrix[y][x]` is cell with coordinates `(x,y)`, which is not completely obvious.\n\n**Complexity**: time complexity is `O(n^2)`, we process each element once. Space complexity is `O(n^2)` as well.\n\n```\nclass Solution:\n def generateMatrix(self, n):\n matrix = [[0] * n for _ in range(n)]\n x, y, dx, dy = 0, 0, 1, 0\n for i in range(n*n):\n matrix[y][x] = i + 1\n if not 0 <= x + dx < n or not 0 <= y + dy < n or matrix[y+dy][x+dx] != 0:\n dx, dy = -dy, dx\n x, y = x + dx, y + dy\n return matrix\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 185 | 2 | [] | 14 |
spiral-matrix-ii | Simple C++ solution(with explaination) | simple-c-solutionwith-explaination-by-al-lx5u | \n class Solution {\n public:\n vector > generateMatrix(int n) {\n vector > ret( n, vector(n) );\n \tint k = 1, i | allenyick | NORMAL | 2015-01-14T01:55:35+00:00 | 2018-10-03T05:31:12.533739+00:00 | 25,898 | false | \n class Solution {\n public:\n vector<vector<int> > generateMatrix(int n) {\n vector<vector<int> > ret( n, vector<int>(n) );\n \tint k = 1, i = 0;\n \twhile( k <= n * n )\n \t{\n \t\tint j = i;\n // four steps\n \t\twhile( j < n - i ) // 1. horizonal, left to right\n \t\t\tret[i][j++] = k++;\n \t\tj = i + 1;\n \t\twhile( j < n - i ) // 2. vertical, top to bottom\n \t\t\tret[j++][n-i-1] = k++;\n \t\tj = n - i - 2;\n \t\twhile( j > i ) // 3. horizonal, right to left \n \t\t\tret[n-i-1][j--] = k++;\n \t\tj = n - i - 1;\n \t\twhile( j > i ) // 4. vertical, bottom to top \n \t\t\tret[j--][i] = k++;\n \t\ti++; // next loop\n \t}\n \treturn ret;\n }\n }; | 143 | 2 | [] | 14 |
spiral-matrix-ii | ✅ C++ || 0ms || 100 % || Easy To Understand | c-0ms-100-easy-to-understand-by-knockcat-5v5s | 59. Spiral Matrix II\nKNOCKCAT\n\n1. Easy C++\n2. Line by Line Explanation with Comments.\n3. Detailed Explanation \u2705\n4. Please Upvote if it helps\u2B06\uF | knockcat | NORMAL | 2022-04-13T00:52:34.606229+00:00 | 2022-12-31T06:59:03.207807+00:00 | 15,721 | false | # 59. Spiral Matrix II\n**KNOCKCAT**\n```\n1. Easy C++\n2. Line by Line Explanation with Comments.\n3. Detailed Explanation \u2705\n4. Please Upvote if it helps\u2B06\uFE0F\n5. Link to my Github Profile contains a repository of Leetcode with all my Solutions. \u2B07\uFE0F\n\t//\uD83D\uDE09If you Like the repository don\'t foget to star & fork the repository\uD83D\uDE09\n```\n\n[LeetCode](http://github.com/knockcat/Leetcode) **LINK TO LEETCODE REPOSITORY**\n\nPlease upvote my comment so that i get to win the 2022 giveaway and motivate to make such discussion post.\n**Happy new Year 2023 to all of you**\n**keep solving keep improving**\nLink To comment\n[Leetcode Give away comment](https://leetcode.com/discuss/general-discussion/2946993/2022-Annual-Badge-and-the-Giveaway/1734919)\n\n**ALGORITHM**\n* We **have to fill the matrix layer by layer in four direction**.\n* From **left to right** \u27A1\uFE0F:\n\t* the **row will remain constant** while **column is updated till reaches n-1**.\n* From **Top to bottom** \u2B07\uFE0F(moving down)\n\t* The **column will remain constant as n-1** and **we will start filling from r1 + 1**, as first row is filled in previous step & row will be updated.\n* From **right to left** \u2B05\uFE0F\n\t* we will **start filling from c2 - 1 because c2 is filled in previous step**.\n\t* so the **row will be fixed** and c2 will be updated from c2-1 till its greater than c1.\n* From **botom to up** \u2B06\uFE0F (move up)\n\t* the **column will be fixed as c1** while row will be updated form r2 till it greater than r1.\n* After that we will **updates the row and column pointers, as now we will have to fill the inner layers.**\n\n**ANALYSIS -:**\n* TIME COMPLEXITY = **O(N^2)**\n* SPACE COMPLEXITY = **O(1)**\n\n**CODE WITH EXPLANATION**\n```\n\t\t\t\t// \uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\uD83D\uDE09Please upvote if it helps \uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n int r1 = 0, r2 = n-1;\n int c1 = 0, c2 = n-1;\n int val = 0;\n\t\t\n\t\t// result matrix\n vector<vector<int>> v(n, vector<int> (n));\n while(r1 <= r2 && c1 <= c2)\n {\n // left to right (row will be fixed)\n for(int i = c1; i <= c2; ++i)\n v[r1][i] = ++val;\n\t\t\t\t\n\t\t\t\t// move down(col will be fixed)\n for(int i = r1+1; i <= r2; ++i)\n v[i][c2] = ++val;\n\t\t\t\t\n // move right to left\n // move up\n if(r1 < r2 && c1 < c2)\n {\n // move right to left (row will be fixed)\n for(int i = c2-1; i>c1; --i)\n v[r2][i] = ++val;\n\t\t\t\t\t\n\t\t\t\t\t// move up (col will be fixed)\n\t\t\t\t\tfor(int i = r2; i>r1; --i) \n v[i][c1] = ++val;\n }\n ++r1;\n --r2;\n ++c1;\n --c2;\n }\n return v;\n }\n\t// for github repository link go to my profile.\n};\n``` | 140 | 2 | ['C', 'C++'] | 18 |
spiral-matrix-ii | Python easy to follow solution. | python-easy-to-follow-solution-by-oldcod-dakc | \n def generateMatrix(self, n):\n if not n:\n return []\n res = [[0 for _ in xrange(n)] for _ in xrange(n)]\n left, right | oldcodingfarmer | NORMAL | 2015-08-03T13:22:24+00:00 | 2015-08-03T13:22:24+00:00 | 9,735 | false | \n def generateMatrix(self, n):\n if not n:\n return []\n res = [[0 for _ in xrange(n)] for _ in xrange(n)]\n left, right, top, down, num = 0, n-1, 0, n-1, 1\n while left <= right and top <= down:\n for i in xrange(left, right+1):\n res[top][i] = num \n num += 1\n top += 1\n for i in xrange(top, down+1):\n res[i][right] = num\n num += 1\n right -= 1\n for i in xrange(right, left-1, -1):\n res[down][i] = num\n num += 1\n down -= 1\n for i in xrange(down, top-1, -1):\n res[i][left] = num\n num += 1\n left += 1\n return res | 98 | 1 | ['Python'] | 14 |
spiral-matrix-ii | Video Explanation | video-explanation-by-niits-xfom | Solution Video⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️■ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1Subscr | niits | NORMAL | 2024-12-22T15:00:34.358708+00:00 | 2024-12-22T15:00:53.592709+00:00 | 3,416 | false |
# Solution Video
https://youtu.be/pLjhGbKMxL4
### ⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️
**■ Subscribe URL**
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
Subscribers: 12,166
Thank you for your support!
---
# Approach
This is based on Python code. Other languages might be different.
1. Initialize the variables x, y, dx, and dy to 0, 0, 1, and 0 respectively.
2. Create a 2D list res of size n x n and initialize all its elements to 0.
3. For i in the range of n x n, do the following:
- Set the element at res[y][x] to i+1.
- Check if the next element in the current direction is outside the matrix or has already been visited. If so, change the direction by swapping dx and dy and negating one of them.
- Update x and y by adding dx and dy respectively.
4. Return the resulting matrix res.
---
I have related question and use the same logic
https://youtu.be/RSjo4A8WfQ8
---
# Complexity
This is based on Python code. Other languages might be different.
- Time complexity: O(n^2)
it visits every cell in the n * n matrix exactly once
- Space complexity: O(n^2)
We create n * n matrix
```python []
def generateMatrix(self, n: int) -> List[List[int]]:
x, y, dx, dy = 0, 0, 1, 0
res = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n * n):
res[y][x] = i + 1
if not 0 <= x + dx < n or not 0 <= y + dy < n or res[y+dy][x+dx] != 0:
dx, dy = -dy, dx
x += dx
y += dy
return res
```
```javascript []
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let x = 0, y = 0, dx = 1, dy = 0;
let res = Array.from({length: n}, () => Array.from({length: n}, () => 0));
for (let i = 0; i < n * n; i++) {
res[y][x] = i + 1;
if (!(0 <= x + dx && x + dx < n && 0 <= y + dy && y + dy < n && res[y+dy][x+dx] === 0)) {
[dx, dy] = [-dy, dx];
}
x += dx;
y += dy;
}
return res;
};
```
```java []
class Solution {
public int[][] generateMatrix(int n) {
int x = 0, y = 0, dx = 1, dy = 0;
int[][] res = new int[n][n];
for (int i = 0; i < n * n; i++) {
res[y][x] = i + 1;
if (!(0 <= x + dx && x + dx < n && 0 <= y + dy && y + dy < n && res[y+dy][x+dx] == 0)) {
int temp = dx;
dx = -dy;
dy = temp;
}
x += dx;
y += dy;
}
return res;
}
}
```
```C++ []
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int x = 0, y = 0, dx = 1, dy = 0;
vector<vector<int>> res(n, vector<int>(n, 0));
for (int i = 0; i < n * n; i++) {
res[y][x] = i + 1;
if (!(0 <= x + dx && x + dx < n && 0 <= y + dy && y + dy < n && res[y+dy][x+dx] == 0)) {
int temp = dx;
dx = -dy;
dy = temp;
}
x += dx;
y += dy;
}
return res;
}
};
```
---
Thank you for reading my post.
##### ⭐️ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
##### ⭐️ My recent video
#56 Merge Intervals
https://youtu.be/DAppffTClNQ | 97 | 0 | ['Array', 'Matrix', 'C++', 'Java', 'Python3', 'JavaScript'] | 1 |
spiral-matrix-ii | Share my java solution | share-my-java-solution-by-samaritan-b9mz | public static int[][] generateMatrix(int n) {\n\t\tint[][] ret = new int[n][n];\n\t\tint left = 0,top = 0;\n\t\tint right = n -1,down = n - 1;\n\t\tint count = | samaritan | NORMAL | 2015-06-04T03:30:37+00:00 | 2018-10-20T05:59:54.295417+00:00 | 18,689 | false | public static int[][] generateMatrix(int n) {\n\t\tint[][] ret = new int[n][n];\n\t\tint left = 0,top = 0;\n\t\tint right = n -1,down = n - 1;\n\t\tint count = 1;\n\t\twhile (left <= right) {\n\t\t\tfor (int j = left; j <= right; j ++) {\n\t\t\t\tret[top][j] = count++;\n\t\t\t}\n\t\t\ttop ++;\n\t\t\tfor (int i = top; i <= down; i ++) {\n\t\t\t\tret[i][right] = count ++;\n\t\t\t}\n\t\t\tright --;\n\t\t\tfor (int j = right; j >= left; j --) {\n\t\t\t\tret[down][j] = count ++;\n\t\t\t}\n\t\t\tdown --;\n\t\t\tfor (int i = down; i >= top; i --) {\n\t\t\t\tret[i][left] = count ++;\n\t\t\t}\n\t\t\tleft ++;\n\t\t}\n\t\treturn ret;\n\t} | 97 | 1 | ['Java'] | 11 |
spiral-matrix-ii | Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | pythonjavacsimple-solutioneasy-to-unders-sgrw | !! BIG ANNOUNCEMENT !!\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies relat | techwired8 | NORMAL | 2023-05-10T00:09:52.374094+00:00 | 2023-05-10T00:13:48.591013+00:00 | 15,702 | false | **!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. I planned to give for next 10,000 Subscribers as well. If you\'re interested **DON\'T FORGET** to Subscribe\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n\n# or\n\n# Click the Link in my Profile\n\n# Approach:\n\n- Initialize an empty matrix of size n x n with all elements set to zero.\n- Define variables left, right, top, bottom, and num.\n- Use a while loop to iterate over the matrix in a spiral order.\n- In each iteration, fill in the top row, right column, bottom row, and left column of the remaining submatrix, in that order.\n- Increment/decrement the values of left, right, top, and bottom accordingly after each iteration, and update the value of num to be filled in the next iteration.\n- Return the generated matrix.\n# Intuition:\n\nThe code generates the matrix by filling in its elements in a spiral order, starting from the top-left corner and moving clockwise. It uses the variables left, right, top, and bottom to keep track of the current submatrix being filled in, and the variable num to keep track of the next number to be filled in the matrix. The algorithm fills in the matrix in four steps:\n\n- Fill in the top row from left to right.\n- Fill in the right column from top to bottom.\n- Fill in the bottom row from right to left.\n- Fill in the left column from bottom to top.\n\nAfter each step, the corresponding variable (left, right, top, or bottom) is incremented or decremented to exclude the already filled elements in the next iteration. The algorithm stops when the submatrix being filled in becomes empty, i.e., left > right or top > bottom. Finally, the generated matrix is returned.\n\n\n```Python []\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n if not n:\n return []\n matrix = [[0 for _ in range(n)] for _ in range(n)]\n left, right, top, bottom, num = 0, n-1, 0, n-1, 1\n while left <= right and top <= bottom:\n for i in range(left, right+1):\n matrix[top][i] = num \n num += 1\n top += 1\n for i in range(top, bottom+1):\n matrix[i][right] = num\n num += 1\n right -= 1\n if top <= bottom:\n for i in range(right, left-1, -1):\n matrix[bottom][i] = num\n num += 1\n bottom -= 1\n if left <= right:\n for i in range(bottom, top-1, -1):\n matrix[i][left] = num\n num += 1\n left += 1\n return matrix\n\n```\n```Java []\nclass Solution {\n public int[][] generateMatrix(int n) {\n if (n == 0) {\n return new int[0][0];\n }\n int[][] matrix = new int[n][n];\n int left = 0, right = n-1, top = 0, bottom = n-1, num = 1;\n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num++;\n }\n left++;\n }\n }\n return matrix;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n if (n == 0) {\n return {};\n }\n vector<vector<int>> matrix(n, vector<int>(n, 0));\n int left = 0, right = n-1, top = 0, bottom = n-1, num = 1;\n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num++;\n }\n left++;\n }\n }\n return matrix;\n }\n};\n\n```\n# An Upvote will be encouraging \uD83D\uDC4D | 70 | 0 | ['Array', 'C++', 'Java', 'Python3'] | 8 |
spiral-matrix-ii | Simple C++ solution | simple-c-solution-by-jaewoo-386x | class Solution {\n public:\n vector<vector<int> > generateMatrix(int n) {\n vector<vector<int> > vv(n, vector<int>(n));\n \n | jaewoo | NORMAL | 2015-04-03T22:22:31+00:00 | 2018-09-04T10:58:34.875200+00:00 | 5,263 | false | class Solution {\n public:\n vector<vector<int> > generateMatrix(int n) {\n vector<vector<int> > vv(n, vector<int>(n));\n \n int rowStart = 0, rowEnd = n - 1;\n int colStart = 0, colEnd = n - 1;\n int cnt = 1;\n \n while(rowStart <= rowEnd && colStart <= colEnd)\n {\n for(int i = colStart; i<= colEnd; i++)\n vv[rowStart][i] = cnt++;\n rowStart++;\n \n for(int i = rowStart; i<= rowEnd; i++)\n vv[i][colEnd] = cnt++;\n colEnd--;\n \n for(int i = colEnd; i>= colStart; i--)\n vv[rowEnd][i] = cnt++;\n rowEnd--;\n \n for(int i = rowEnd; i>= rowStart; i--)\n vv[i][colStart] = cnt++;\n colStart++;\n }\n \n return vv;\n }\n }; | 67 | 0 | [] | 5 |
spiral-matrix-ii | [Python] Smart Simulate by marking as Visited - Super Clean & Concise | python-smart-simulate-by-marking-as-visi-50kg | Idea\n- Initially, we move by the RIGHT direction.\n- If we meet the boundary or we meet visited cell then we change to the next direction.\n- Directions are in | hiepit | NORMAL | 2021-09-17T06:32:05.139837+00:00 | 2022-04-14T00:21:35.406765+00:00 | 1,410 | false | **Idea**\n- Initially, we move by the RIGHT direction.\n- If we meet the boundary or we meet visited cell then we change to the next direction.\n- Directions are in order [RIGHT, DOWN, LEFT, TOP].\n- We iterate `n^2` times to fill `n^2` values to our answer.\n\n\n\n```python\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n ans = [[0] * n for _ in range(n)]\n DIR = [0, 1, 0, -1, 0] # (r + DIR[i], c + DIR[i+1]) corresponding to move [RIGHT, DOWN, LEFT, TOP]\n r, c = 0, 0 # start at cell (0, 0)\n d = 0 # start with RIGHT direction\n for num in range(1, n*n+1):\n nr, nc = r + DIR[d], c + DIR[d+1]\n if not 0 <= nr < n or not 0 <= nc < n or ans[nr][nc] != 0: # If out of bound or already visited\n d = (d + 1) % 4 # Change next direction\n nr, nc = r + DIR[d], c + DIR[d+1]\n \n ans[r][c] = num\n r, c = nr, nc\n \n return ans\n```\n**Complexity**\n- Time: `O(N^2)`, where `N <= 20` is length of side of the square matrix.\n- Extra space (without couting output as space): `O(1)` | 58 | 0 | [] | 1 |
spiral-matrix-ii | ✔💯 DAY 405 | BRUTE->BETTER->OPTIMAL->3-LINER | 0MS-100% | | [PYTHON/JAVA/C++] | EXPLAINED 🆙🆙🆙 | day-405-brute-better-optimal-3-liner-0ms-yq5a | \n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n\n\n# BRUTE\nThe brute force solution to generate a matrix in spiral order | ManojKumarPatnaik | NORMAL | 2023-05-10T02:52:25.005100+00:00 | 2023-05-10T16:18:47.496465+00:00 | 5,840 | false | \n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n\n\n# BRUTE\nThe brute force solution to generate a matrix in spiral order is to simulate the process of filling the matrix in a spiral order. We can start by initializing the matrix with zeros and then fill the matrix in a spiral order by moving right, down, left, and up. We keep track of the current position in the matrix and the direction of movement. Whenever we reach the boundary of the matrix or encounter a non-zero element, we change the direction of movement. We continue this process until all the elements in the matrix are filled.\n\n```java []\npublic int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n int num = 1;\n int row = 0;\n int col = 0;\n int direction = 0;\n int[] dr = {0, 1, 0, -1};\n int[] dc = {1, 0, -1, 0};\n while (num <= n * n) {\n matrix[row][col] = num;\n num++;\n int nextRow = row + dr[direction];\n int nextCol = col + dc[direction];\n if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || matrix[nextRow][nextCol] != 0) {\n direction = (direction + 1) % 4;\n }\n row += dr[direction];\n col += dc[direction];\n }\n return matrix;\n }\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n int num = 1;\n int row = 0;\n int col = 0;\n int direction = 0;\n vector<int> dr = {0, 1, 0, -1};\n vector<int> dc = {1, 0, -1, 0};\n while (num <= n * n) {\n matrix[row][col] = num;\n num++;\n int nextRow = row + dr[direction];\n int nextCol = col + dc[direction];\n if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || matrix[nextRow][nextCol] != 0) {\n direction = (direction + 1) % 4;\n }\n row += dr[direction];\n col += dc[direction];\n }\n return matrix;\n}\n```\n```python []\ndef generateMatrix(n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n num = 1\n row = 0\n col = 0\n direction = 0\n dr = [0, 1, 0, -1]\n dc = [1, 0, -1, 0]\n while num <= n * n:\n matrix[row][col] = num\n num += 1\n nextRow = row + dr[direction]\n nextCol = col + dc[direction]\n if nextRow < 0 or nextRow >= n or nextCol < 0 or nextCol >= n or matrix[nextRow][nextCol] != 0:\n direction = (direction + 1) % 4\n row += dr[direction]\n col += dc[direction]\n return matrix\n```\n# Complexity\nThe time complexity of the brute force solution is O(n^2) because we need to fill all the elements in the matrix. The space complexity is also O(n^2)+2*O(1D) because we need to create a matrix of size n x n to store the elements and two direction 1D arrays.\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Better Solution:\n\nA better solution to generate a matrix in spiral order is to use a recursive approach. We can divide the matrix into four sub-matrices and fill each sub-matrix in a spiral order recursively. We start by filling the top row of the matrix, then fill the right column, then the bottom row, and finally the left column. We repeat this process for the remaining sub-matrix until all the elements in the matrix are filled.\n\n```java []\npublic int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n fillMatrix(matrix, 0, n - 1, 0, n - 1, 1);\n return matrix;\n }\n\n public void fillMatrix(int[][] matrix, int top, int bottom, int left, int right, int num) {\n if (top > bottom || left > right) {\n return;\n }\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n for (int i = top + 1; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n if (top < bottom && left < right) {\n for (int i = right - 1; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n for (int i = bottom - 1; i > top; i--) {\n matrix[i][left] = num;\n num++;\n }\n }\n fillMatrix(matrix, top + 1, bottom - 1, left + 1, right - 1, num);\n }\n\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n fillMatrix(matrix, 0, n - 1, 0, n - 1, 1);\n return matrix;\n}\n\nvoid fillMatrix(vector<vector<int>>& matrix, int top, int bottom, int left, int right, int num) {\n if (top > bottom || left > right) {\n return;\n }\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n for (int i = top + 1; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n if (top < bottom && left < right) {\n for (int i = right - 1; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n for (int i = bottom - 1; i > top; i--) {\n matrix[i][left] = num;\n num++;\n }\n }\n fillMatrix(matrix, top + 1, bottom - 1, left + 1, right - 1, num);\n}\n```\n```python []\ndef generateMatrix(n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n fillMatrix(matrix, 0, n - 1, 0, n - 1, 1)\n return matrix\n\ndef fillMatrix(matrix: List[List[int]], top: int, bottom: int, left: int, right: int, num: int) -> None:\n if top > bottom or left > right:\n return\n for i in range(left, right + 1):\n matrix[top][i] = num\n num += 1\n for i in range(top + 1, bottom + 1):\n matrix[i][right] = num\n num += 1\n if top < bottom and left < right:\n for i in range(right - 1, left - 1, -1):\n matrix[bottom][i] = num\n num += 1\n for i in range(bottom - 1, top, -1):\n matrix[i][left] = num\n num += 1\n fillMatrix(matrix, top + 1, bottom - 1, left + 1, right - 1, num)\n```\n# Complexity\nThe time complexity of the better solution is O(n^2) because we need to fill all the elements in the matrix. The space complexity is also O(n^2) because we need to create a matrix of size n x n to store the elements. However, the space complexity of the recursive approach is O(n2)+o(log n) because we use the call stack to store the recursive calls, which has a maximum depth of log n.\n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n# optimal\n\n```java []\npublic int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n int top = 0;\n int bottom = n - 1;\n int left = 0;\n int right = n - 1;\n int num = 1;\n while (top <= bottom && left <= right) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num;\n num++;\n }\n left++;\n }\n }\n return matrix;\n }\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n int top = 0;\n int bottom = n - 1;\n int left = 0;\n int right = n - 1;\n int num = 1;\n while (top <= bottom && <= right) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num;\n num++;\n }\n left++;\n }\n }\n return matrix;\n}\n```\n```python []\ndef generateMatrix(n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n top = 0\n bottom = n - 1\n left = 0\n right = n - 1\n num = 1\n while top <= bottom and left <= right:\n for i in range(left, right + 1):\n matrix[top][i] = num\n num += 1\n top += 1\n for i in range(top, bottom + 1):\n matrix[i][right] = num\n num += 1\n right -= 1\n if top <= bottom:\n for i in range(right, left - 1, -1):\n matrix[bottom][i] = num\n num += 1\n bottom -= 1\n if left <= right:\n for i in range(bottom, top - 1, -1):\n matrix[i][left] = num\n num += 1\n left += 1\n return matrix\n```\n# Complexity\nThe time complexity of the optimal solution is O(n^2) because we need to fill all the elements in the matrix. The space complexity is o(n2)+ O(1) because we only need to create a constant number of variables to store the boundaries of the matrix and the current number to fill.\n\nIn terms of time complexity, the optimal solution is the best because it has the same time complexity as the other two solutions but uses a single loop instead of recursion or simulating the process of filling the matrix. In terms of space complexity, the optimal solution is the best because it only uses a constant amount of space, whereas the other two solutions use a matrix of size n x n or a call stack of size log n.\n\n# concise code\n# Algorithm\n##### \u2022\tUse four variables i, j, di, and dj to keep track of the current position and direction\n##### \u2022\tThen starts by initializing the matrix with all zeros\n##### \u2022\tIt then fills the matrix in a spiral order by moving in the current direction and changing direction when it encounters a non-zero element\n##### \u2022\tThe loop variable k starts from 1 and goes up to n * n\n##### \u2022\tIn each iteration, then sets the value of the current position (i, j) to k\n##### \u2022\tIt then checks if the next position in the current direction (i + di, j + dj) is already filled with a non-zero value\n##### \u2022\tIf it is, changes the direction by swapping di and dj and negating one of them\n##### \u2022\tFinally, updates the current position by adding di to i and dj to j\n##### \u2022\tOnce the loop is complete, the matrix is filled in a spiral order and returns the matrix\n\n```java []\npublic int[][] generateMatrix(int n) {\n int matrix[][] = new int[n][n],i = 0, j = 0, di = 0, dj = 1;\n for (int k = 1; k <= n * n; k++) {\n matrix[i][j] = k;\n if (matrix[(i + di + n) % n][(j + dj + n) % n] != 0) {\n int temp = di;\n di = dj;\n dj = -temp;\n }\n i += di;\n j += dj;\n } return matrix;\n}\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n int i = 0, j = 0, di = 0, dj = 1;\n for (int k = 1; k <= n * n; k++) {\n matrix[i][j] = k;\n if (matrix[(i + di + n) % n][(j + dj + n) % n] != 0) {\n int temp = di;\n di = dj;\n dj = -temp;\n }\n i += di;\n j += dj;\n }\n return matrix;\n}\n```\n```python []\ndef generateMatrix(self, n):\n A = [[0] * n for _ in range(n)]\n i, j, di, dj = 0, 0, 0, 1\n for k in xrange(n*n):\n A[i][j] = k + 1\n if A[(i+di)%n][(j+dj)%n]:\n di, dj = dj, -di\n i += di\n j += dj\n return A\n```\n\n# dry run for n=3\n##### \u2022\tInitially, we create a new n x n matrix filled with zeros\n##### \u2022\tWe also initialize i and j to 0, and di and dj to 0 and 1 respectively\n##### \u2022\tWe then enter a loop that runs from k=1 to k=n*n\n##### \u2022\tIn each iteration of the loop, we do the following:We set the value of the current cell to k\n##### \u2022\tWe check if the next cell in the direction of (di, dj) is already filled\n##### \u2022\tIf it is, we change the direction of motion by swapping di and dj and negating the new value of dj\n##### \u2022\tWe update the values of i and j by adding di and dj respectively\n##### \u2022\tAfter the loop completes, we return the filled matrix\n##### \u2022\tThe final matrix is:\n```\n1 2 3\n8 9 4\n7 6 5\n```\n# 3 LINES code\n# Algorithm\n##### \u2022\tFirst initializes an empty list A and a variable lo to n*n+1\n##### \u2022\tIt then enters a loop that continues until lo is less than or equal to 1\n##### \u2022\tIn each iteration, set hi to the current value of lo and updates lo to lo - len(A)\n##### \u2022\tIt then creates a new list of integers from lo to hi and appends it to the beginning of A\n##### \u2022\tThen reverses the order of the remaining elements in A and transposes the resulting list of lists using the zip() function\n##### \u2022\tThis effectively rotates the matrix by 90 degrees counterclockwise\n##### \u2022\tThe loop continues until lo is less than or equal to 1, at which point the matrix is filled in a spiral order and returns A\n\n```PYTHON []\ndef generateMatrix(self, n):\n A = [[n*n]]\n while A[0][0] > 1:\n A = [range(A[0][0] - len(A), A[0][0])] + zip(*A[::-1])\n return A * (n>0)\n```\n```PYTHON []\ndef generateMatrix(self, n):\n A, lo = [], n*n+1\n while lo > 1:\n lo, hi = lo - len(A), lo\n A = [range(lo, hi)] + zip(*A[::-1])\n return A\n```\n# dry run for n=3\n##### \u2022\tInitially, A is set to [[9]]\n##### \u2022\tIn the while loop, we check if the first element of A is greater than 1\n##### \u2022\tSince it is, we perform the following steps:We create a new list B containing a range of numbers from A[0][0] - len(A) to A[0][0] - 1\n##### \u2022\tIn this case, B is equal to range(7, 9)\n##### \u2022\tWe then take the transpose of A using zip(*A[::-1])\n##### \u2022\tThe [::-1] reverses the order of the elements in A, and the * unpacks the elements of A as arguments to zip\n##### \u2022\tThe zip function then groups the elements of each sub-list of A with the corresponding elements of B, effectively rotating the matrix by 90 degrees counterclockwise\n##### \u2022\tWe concatenate B with the result of step 2 to form a new matrix A\n##### \u2022\tWe repeat steps 1-3 until the first element of A is equal to 1\n##### \u2022\tFinally, we return A multiplied by (n>0), which is equivalent to returning A if n is positive and an empty list if n is zero\n\nAt each iteration, the code fills in one element of the matrix in a spiral order. The final matrix is filled in the following order:\n1 2 3\n8 9 4\n7 6 5\n\n\n\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A | 55 | 0 | ['Array', 'Python', 'C++', 'Java', 'Python3'] | 5 |
spiral-matrix-ii | Python easy-to-understand solution with fully commented code (ref: caikehe's solution) | python-easy-to-understand-solution-with-7wit7 | NOTE: this solution is an adaption of @caikehe\'s brilliant and clean solution.\n\nintuition:\n\n- initialize a matrix of zeros\n- fill in the numbers in a spir | ghjf0079 | NORMAL | 2019-12-25T20:35:44.096093+00:00 | 2020-01-02T06:06:04.930803+00:00 | 3,074 | false | NOTE: this solution is an adaption of @caikehe\'s [brilliant and clean solution](https://leetcode.com/problems/spiral-matrix-ii/discuss/22290/Python-easy-to-follow-solution).\n\nintuition:\n\n- initialize a matrix of zeros\n- fill in the numbers in a spiral order layer-by-layer\n\nie. if n =3, initialize a 3-by-3 matrix\n```\n[\n [ 0, 0, 0 ],\n [ 0, 0, 0 ],\n [ 0, 0, 0 ]\n]\n```\ndivide up the matrix into 4 types of layers\n```python\n top = 0 # top layer: top row index\n right = n - 1 # right layer: right col index\n down = n - 1 # bottom layer: bottom row index\n left = 0 # left layer: left col index\n```\n\n```\n[ \n [ X, 0, 0 ], <-- you start filling in numbers at the top-left position\n [ 0, 0, 0 ],\n [ 0, 0, 0 ]\n]\n```\n\nwhen filling the top layer (horizontal row), fix the row index and increment the col index.\nafter you are done with the top layer (horizontal row), move the top layer inward(downward) \n\n```python\n for i in range(left, right+1): # from left to right. right + 1 to reach the last position in a row\n\t matrix[top][i] = num # to fill top row, fix the top row index and increment the col position\n num += 1 # update num\n top += 1 # after traversing top row, move top row index inward(downward) by one unit\n```\n\nyour matrix will be\n\n\n```\n[\n [ 1, 2, 3 ],\n [ 0, 0, X ], <--- since you increment the top layer by 1, you will start fillin in the next number here at the \'x\' position\n [ 0, 0, 0 ]\n]\n```\n\nrepeat for the right col (vertical layer going down), bottom row (horizontal layer going right to left), left col (vertical layer going from bottom up)\n```\n[\n [ 1, 2, 3 ],\n [ 0, 0, 4 ], \n [ 0, X, 5 ] <--- since you increment the right layer by -1, you will start fillin in the next number here at the \'x\' position\n]\n```\n\n```\n[\n [ 1, 2, 3 ],\n [ X, 0, 4 ], <--- since you increment the bottom layer by -1, you will start fillin in the next number here at the \'x\' position\n [ 7, 6, 5 ]\n]\n```\n\ntime O(n by n)\nspace O(n by n)\n\n```python\n# 59 Spiral Matrix II\nclass Solution:\n def generateMatrix(self, n):\n matrix = []\n if not n: return matrix\n\n # construct a matrix of zeros\n for row in range(n):\n rowArray = []\n for col in range(n):\n rowArray.append(0)\n matrix.append(rowArray)\n\n # layer by layer strategy\n num = 1\n top = 0 # top layer: top row index\n right = n - 1 # right layer: right col index\n down = n - 1 # bottom layer: bottom row index\n left = 0 # left layer: left col index\n\t\t \n\t\t # while layers closing inward but not overlapping. if overlap = reached end of spiral matrix\n while left <= right and top <= down: \n # top row\n for i in range(left, right+1): # from left to right. right + 1 to reach the last position in a row\n matrix[top][i] = num # to fill top row, fix the top row index and increment the col position\n num += 1 # update num\n top += 1 # after traversing top row, move top row index inward(downward) by one unit\n\n # right col\n for i in range(top, down+1): # from top to bottom. bottom + 1 to reach the last positin in a col\n matrix[i][right] = num # to fill the right col, fix the right col index and increment the row position\n num += 1 # update num\n right -= 1 # after traversing right col, move right col index inward(towards the left) by one unit\n\n # bottom row\n for i in range(right, left-1, -1): # from left to right, in reverse order. left-1 to reach the leftmost position in a row\n matrix[down][i] = num\n num += 1 # update num\n down -= 1 # after traversing bottom row, move bottom row index inward(upward) by one unit\n\n # left col\n for i in range(down, top-1, -1): # from bottom to top, in reverse order. top-1 to reach the topmost position in a col\n matrix[i][left] = num # to fill the left col, fix the left col index and increment the row position\n num += 1\n left += 1 # after traversing left col, move left col index inward(towards the right) by one unit\n\n # repeat until top-bottom or left-right indices collide (ie. have completed all layers)\n return matrix\n``` | 42 | 0 | ['Python', 'Python3'] | 1 |
spiral-matrix-ii | ✔️ [Python3] STRAIGHTFORWARD (^▽^), Explained | python3-straightforward-v-explained-by-a-cqg2 | UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.\n\nWe use helper function here that fills only one circle at th | artod | NORMAL | 2022-04-13T01:22:04.512053+00:00 | 2022-04-13T01:22:04.512097+00:00 | 4,076 | false | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nWe use helper function here that fills only one circle at the time.\n\nTime: **O(n^2)**\nSpace: **O(1)**\n\nRuntime: 35 ms, faster than **82.95%** of Python3 online submissions for Spiral Matrix II.\nMemory Usage: 13.9 MB, less than **85.84%** of Python3 online submissions for Spiral Matrix II.\n\n```\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n res = [[0] * n for _ in range(n)]\n \n def fill_circle(el, start, n):\n i, j = start, start \n for k in range(j, j + n): \n res[i][k], el = el, el + 1\n for k in range(i + 1, i + n): \n res[k][j + n - 1], el = el, el + 1\n for k in reversed(range(j, j + n - 1)): \n res[i + n - 1][k], el = el, el + 1\n for k in reversed(range(i + 1, i + n - 1)): \n res[k][j], el = el, el + 1\n \n el, start = 1, 0\n while n > 0:\n fill_circle(el, start, n)\n el = el + 4*(n - 1)\n n, start = n - 2, start + 1\n \n return res\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.** | 31 | 1 | ['Python3'] | 4 |
spiral-matrix-ii | If we can't write data to the matrix, we change the direction,a simple python solution | if-we-cant-write-data-to-the-matrix-we-c-dlvt | class Solution:\n # @return a list of lists of integer\n def generateMatrix(self, n):\n matrix = [[0]*n for _ in range(n)]\n directions = (( | tusizi | NORMAL | 2015-01-22T05:14:09+00:00 | 2015-01-22T05:14:09+00:00 | 2,959 | false | class Solution:\n # @return a list of lists of integer\n def generateMatrix(self, n):\n matrix = [[0]*n for _ in range(n)]\n directions = ((0, 1), (1, 0), (0, -1), (-1, 0))\n d = 0\n y, x = 0, 0\n for i in range(1, n*n+1):\n matrix[y][x] = i\n dy, dx = directions[d % 4]\n if -1 < y+dy < n and -1 < x+dx < n and matrix[y+dy][x+dx] == 0:\n y, x = y+dy, x+dx\n else:\n d += 1\n dy, dx = directions[d % 4]\n y, x = y+dy, x+dx\n return matrix\n\nChange the direction If the we can't write to the matrix | 26 | 0 | ['Python'] | 4 |
spiral-matrix-ii | 9 lines python solution | 9-lines-python-solution-by-oscartsai-gisu | (1) Create a matrix to store the coordinates\n> (0,0) (0,1) (0,2)\n\n> (1,0) (1,1) (1,2)\n\n> (2,0) (2,1) (2,2)\n\n(2) Read it out using the trick of "[Spiral M | oscartsai | NORMAL | 2015-07-18T21:24:07+00:00 | 2015-07-18T21:24:07+00:00 | 4,849 | false | (1) Create a matrix to store the coordinates\n> (0,0) (0,1) (0,2)\n\n> (1,0) (1,1) (1,2)\n\n> (2,0) (2,1) (2,2)\n\n(2) Read it out using the trick of "[Spiral Matrix I][1]"\n\n> (0,0) (0,1) (0,2) (1,2) (2,2) ...\n\n(3) Put 1, 2, 3, ... n**2 at these coordinates sequentially. Done.\n\n def generateMatrix(self, n):\n \n result = [[0 for i in range(n)] for j in range(n)]\n coord = [[(i,j) for j in range(n)] for i in range(n)]\n \n count = 1\n \n while coord:\n for x, y in coord.pop(0):\n result[x][y] = count\n count += 1\n coord = zip(*coord)[::-1]\n\n return result\n\n\n [1]: https://leetcode.com/discuss/46516/lines-recursive-python-solution-lines-solution-recursion | 26 | 0 | ['Python'] | 10 |
spiral-matrix-ii | Java | TC: O(N^2) | SC: O(1) | Multiple optimized ways to solve this question | java-tc-on2-sc-o1-multiple-optimized-way-6giw | Using Switch-Case - Simulating the spiral traversal\njava\n/**\n * Using Switch-Case: Traverse Right -> Down -> Left -> Up\n *\n * Time Complexity: O(N^2)\n *\n | NarutoBaryonMode | NORMAL | 2021-10-09T03:27:52.477899+00:00 | 2021-10-09T03:34:41.963720+00:00 | 1,109 | false | **Using Switch-Case - Simulating the spiral traversal**\n```java\n/**\n * Using Switch-Case: Traverse Right -> Down -> Left -> Up\n *\n * Time Complexity: O(N^2)\n *\n * Space Complexity: O(1) excluding the result space.\n */\nclass Solution {\n public int[][] generateMatrix(int n) {\n if (n < 0) {\n throw new IllegalArgumentException("Invalid input");\n }\n\n int[][] result = new int[n][n];\n if (n == 0) {\n return result;\n }\n\n int top = 0;\n int bottom = n - 1;\n int left = 0;\n int right = n - 1;\n int num = 1;\n int dir = 0;\n\n while (top <= bottom && left <= right) {\n switch (dir) {\n case 0: // Left\n for (int i = left; i <= right; i++) {\n result[top][i] = num++;\n }\n top++;\n break;\n case 1: // Down\n for (int i = top; i <= bottom; i++) {\n result[i][right] = num++;\n }\n right--;\n break;\n case 2: // Right\n for (int i = right; i >= left; i--) {\n result[bottom][i] = num++;\n }\n bottom--;\n break;\n case 3: // Up\n for (int i = bottom; i >= top; i--) {\n result[i][left] = num++;\n }\n left++;\n }\n dir = (dir + 1) % 4;\n }\n\n return result;\n }\n}\n```\n\n---\n**Without using Switch-Case - Simulating the spiral traversal**\n\n```java\n/**\n * Traverse Right -> Down -> Left -> Up\n *\n * Time Complexity: O(N^2)\n *\n * Space Complexity: O(1) excluding the result space.\n */\nclass Solution {\n public int[][] generateMatrix(int n) {\n if (n < 0) {\n throw new IllegalArgumentException("Invalid input");\n }\n\n int[][] result = new int[n][n];\n if (n == 0) {\n return result;\n }\n\n int rowBegin = 0;\n int rowEnd = n - 1;\n int colBegin = 0;\n int colEnd = n - 1;\n int num = 1;\n\n while (rowBegin <= rowEnd && colBegin <= colEnd) {\n // Traverse Right\n for (int i = colBegin; i <= colEnd; i++) {\n result[rowBegin][i] = num++;\n }\n rowBegin++;\n // Traverse Down\n for (int i = rowBegin; i <= rowEnd; i++) {\n result[i][colEnd] = num++;\n }\n colEnd--;\n // Traverse Left\n if (rowBegin <= rowEnd) {\n for (int i = colEnd; i >= colBegin; i--) {\n result[rowEnd][i] = num++;\n }\n rowEnd--;\n }\n // Traverse Up\n if (colBegin <= colEnd) {\n for (int i = rowEnd; i >= rowBegin; i--) {\n result[i][colBegin] = num++;\n }\n colBegin++;\n }\n }\n\n return result;\n }\n}\n```\n\n---\n**Using 2D Directions array to calculate the next valid position - Simulating the spiral traversal**\n\n```java\n/**\n * Using 2D Directions array to calculate the next valid position. Traverse\n * Right -> Down -> Left -> Up\n *\n * Time Complexity: O(N^2)\n *\n * Space Complexity: O(1) excluding the result space.\n */\nclass Solution {\n public int[][] generateMatrix(int n) {\n if (n < 0) {\n throw new IllegalArgumentException("Invalid input");\n }\n\n int[][] result = new int[n][n];\n if (n == 0) {\n return result;\n }\n\n int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n int row = 0;\n int col = 0;\n int dirIdx = 0;\n int num = 1;\n\n while (num <= n * n) {\n result[row][col] = num++;\n row += dirs[dirIdx][0];\n col += dirs[dirIdx][1];\n\n if (row < 0 || row >= n || col < 0 || col >= n || result[row][col] != 0) {\n // Moving back from invalid position\n row -= dirs[dirIdx][0];\n col -= dirs[dirIdx][1];\n // Going to next dir\n dirIdx = (dirIdx + 1) % 4;\n // Updating row and col to valid next position\n row += dirs[dirIdx][0];\n col += dirs[dirIdx][1];\n }\n }\n\n return result;\n }\n}\n```\n\n---\n\nSolutions to other parts of Spiral Matrix question on LeetCode:\n- [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/discuss/1511476/Java-or-TC:-O(M*N)-or-SC:-O(1)-or-Optimized-solution-using-Switch-Case)\n- [885. Spiral Matrix III](https://leetcode.com/problems/spiral-matrix-iii/discuss/1511489/Java-or-TC:-O(max(R-C)2)-or-SC:-O(1)-or-Simulating-a-Spiral-Walk)\n | 25 | 0 | ['Array', 'Matrix', 'Simulation', 'Java'] | 4 |
spiral-matrix-ii | [Runtime: 0 ms, faster than 100.00%] \(@^0^@)/ Easy-To-Understand | runtime-0-ms-faster-than-10000-0-easy-to-gjpo | Runtime: 0 ms, faster than 100.00% of Java online submissions for Spiral Matrix II.\n\nLOGIC=We have to keep insering the number while moving in a particular di | hi-ravi | NORMAL | 2022-04-13T02:32:05.743826+00:00 | 2022-04-13T11:34:53.315856+00:00 | 2,732 | false | ***Runtime: 0 ms, faster than 100.00% of Java online submissions for Spiral Matrix II.***\n\n***LOGIC***=We have to keep insering the number while moving in a particular direction and changing the direction when `certain condtion` occur:\n\n* next row index is -1\n* next col index is -1\n* next col index is n\n* next row index is n\n* next cell in current direction is already filled.\n\nIf `any one` of the following conditions arise, the direction should be changed\n\nThere is a `proper order` which we have to follow while `changing the direction`:\n\n* initial: right -> new: down\n* initial: down -> new: left\n* initial: left -> new: up\n* initial: up -> new: right\n\n\n\n```\nclass Solution {\n Integer rowDir = 0, colDir = 1;\n \n public int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n int num = 1;\n int row =0, col=0;\n \n \n while(num<= n*n) {\n matrix[row][col] = num;\n \n int tempRow = row+rowDir;\n int tempCol = col+colDir;\n\t\t\t\n\t\t\t//Condition to change direction \n if(tempRow < 0 || tempCol <0 || tempRow == n || tempCol == n || matrix[tempRow][tempCol] != 0) {\n changeDirection();\n }\n \n row += rowDir;\n col += colDir;\n \n num++;\n }\n \n return matrix;\n }\n \n public void changeDirection() {\n\t\t\n if(rowDir == 0 && colDir ==1) {\n\t\t\t// initial: right -> new: down\n colDir = 0;\n rowDir = 1;\n } else if (colDir == 0 && rowDir ==1) {\n\t\t\t// initial: down -> new: left\n rowDir = 0;\n colDir = -1;\n } else if (colDir == -1 && rowDir == 0) {\n\t\t\t// initial: left -> new: up\n rowDir = -1;\n colDir = 0;\n } else if (rowDir == -1 && colDir == 0) {\n\t\t\t// initial: up -> new: right\n colDir = 1;\n rowDir = 0;\n }\n }\n}\n```\n<hr>\n<hr>\n\n**Time Complexity =O(N*N)**\n**Space Complexity = O(N)**\n\n<hr>\n<hr>\n | 23 | 1 | ['Java'] | 5 |
spiral-matrix-ii | C++ concise solution. | c-concise-solution-by-oldcodingfarmer-hwz0 | \n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> res(n, vector<int> (n, 1));\n int left, right, top, down, index;\n | oldcodingfarmer | NORMAL | 2015-11-19T22:16:53+00:00 | 2015-11-19T22:16:53+00:00 | 3,279 | false | \n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> res(n, vector<int> (n, 1));\n int left, right, top, down, index;\n left = top = index = 0, right = down = n-1;\n while (left <= right && top <= down) {\n for (unsigned int j = left; j <= right; j++)\n res[top][j] = ++index;\n top++;\n for (unsigned int i = top; i <= down; i++)\n res[i][right] = ++index;\n right--;\n for (int j = right; j >= left; j--)\n res[down][j] = ++index;\n down--;\n for (int i = down; i >= top; i--)\n res[i][left] = ++index;\n left++;\n }\n return res;\n } | 21 | 0 | ['C++'] | 5 |
spiral-matrix-ii | C++ 0ms Fastest solution | c-0ms-fastest-solution-by-raghav_maskara-yj3q | \n\n```\nclass Solution {\npublic:\n vector> generateMatrix(int n) {\n vector>m(n,vector(n,0));\n int c=1;\n int left=0,right=n-1,top=0, | raghav_maskara | NORMAL | 2022-02-27T18:56:28.571568+00:00 | 2022-02-27T18:56:48.218561+00:00 | 783 | false | \n\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>>m(n,vector<int>(n,0));\n int c=1;\n int left=0,right=n-1,top=0,bottom=n-1;\n while(left<=right && top<=bottom){\n \n for(int i=left;i<=right;i++){\n m[top][i]=c;\n c++;\n }\n top++;\n \n for(int i=top;i<=bottom;i++){\n m[i][right]=c;\n c++; \n }\n right--;\n \n for(int i=right;i>=left;i--){\n m[bottom][i]=c;\n c++;\n }\n bottom--;\n \n \n for(int i=bottom;i>=top;i--){\n m[i][left]=c;\n c++; \n }\n left++;\n \n }\n return m;\n }\n}; | 20 | 0 | ['C'] | 0 |
spiral-matrix-ii | My AC solution with using direction variable | my-ac-solution-with-using-direction-vari-vd7b | \n vector<vector<int> > generateMatrix(int n) {\n int dir = 0;\n vector< vector<int> > matrix(n, vector<int> (n, 0));\n | d40a | NORMAL | 2014-08-13T16:54:24+00:00 | 2014-08-13T16:54:24+00:00 | 5,132 | false | \n vector<vector<int> > generateMatrix(int n) {\n int dir = 0;\n vector< vector<int> > matrix(n, vector<int> (n, 0));\n int i = 0, j = 0, k = 1;\n while (k <= n * n) {\n matrix[i][j] = k++;\n if (dir == 0){\n j++;\n if (j == n || matrix[i][j] != 0) dir = 1, j--, i++;\n } else\n if (dir == 1) {\n i++;\n if (i == n || matrix[i][j] != 0) dir = 2, i--, j--;\n } else\n if (dir == 2) {\n j--;\n if (j < 0 || matrix[i][j] != 0) dir = 3, j++, i--;\n } else\n if (dir == 3) {\n i--;\n if (i < 0 || matrix[i][j] != 0) dir = 0, i++, j++;\n }\n }\n return matrix;\n } | 20 | 0 | [] | 4 |
spiral-matrix-ii | Easy C++🔥 Java Code 🔥Beats 100%🔥🔥Step by step Explanattion 🏆🏆Begginers freindly | easy-c-java-code-beats-100step-by-step-e-0uss | \n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThe matrix is initialized with all elements set to 0.\n\nThe goal is to fill the m | Red-hawk | NORMAL | 2023-05-10T00:17:06.604261+00:00 | 2023-05-10T00:20:36.229355+00:00 | 5,756 | false | \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe matrix is initialized with all elements set to 0.\n\nThe goal is to fill the matrix with integers from 1 to n x n in a spiral order. \nFor example, for n = 3, the matrix should look like this:\n```\n1 2 3\n8 9 4\n7 6 5\n```\nInitialize the matrix with all elements set to 0.\n```\n0 0 0\n0 0 0\n0 0 0\n```\nInitialize variables to keep track of the starting and ending rows and columns. Initially, the starting row and column are both 0, and the ending row and column are both n - 1.\n```\nstartingrow = 0\nstartingcol = 0\nendingrow = 2\nendingcol = 2\n```\nStart filling the matrix in a clockwise spiral order. The first step is to fill the top row from left to right. The count variable keeps track of the current number being filled in the matrix. After each number is placed in the matrix, count is incremented.\n```\n1 2 3\n0 0 0\n0 0 0\ncount = 1\n```\nMove the starting row down by one, so that the next step will fill the right column from top to bottom.\n```\n0 0 0\n0 0 0\n0 0 0\ncount = 1\nstartingrow = 1\n```\nFill the right column from top to bottom.\n```\n1 2 3\n0 0 4\n0 0 5\ncount = 3\n```\nMove the ending column left by one, so that the next step will fill the bottom row from right to left.\n```\n1 2 3\n0 0 4\n0 0 5\ncount = 3\nendingcol = 1\n```\nFill the bottom row from right to left.\n```\n1 2 3\n0 0 4\n6 7 5\ncount = 6\n```\nMove the ending row up by one, so that the next step will fill the left column from bottom to top.\n```\n1 2 3\n0 0 4\n6 7 5\ncount = 6\nendingrow = 1\n```\nFill the left column from bottom to top.\n```\n1 2 3\n8 0 4\n6 7 5\ncount = 9\n```\nMove the starting column right by one, so that the next step will fill the top row from left to right again.\n```\n1 2 3\n8 0 4\n6 7 5\ncount = 9\nstartingcol = 1\n```\nRepeat steps 3 through 10 until the entire matrix is filled with numbers.\n```\n1 2 3\n8 9 4\n7 6 5\n```\nThe matrix filled with integers from 1 to n x n in a clockwise spiral order.\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# ---------------------------------------------------------\n# Please Upvote If It helps You\n# ---------------------------------------------------------\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n \n // creating a vector of n*n\n \n vector<vector<int>> ans(n, vector<int>(n, 0));\n \n //int row=matrix.size();\n //int col =matrix[0].size();\n int count =0;\n int total =n*n;\n \n //// all index \n \n int startingrow=0;\n int startingcol=0;\n int endingrow=n-1;\n int endingcol=n-1;\n \n while(count<total)\n {\n for(int i=startingcol;count<total && i<=endingcol; i++)\n {\n count++;\n ans[startingrow][i]=count;\n \n }\n startingrow++;\n \n for(int i=startingrow;count<total && i<=endingrow; i++)\n {\n \n count++;\n ans[i][endingcol]=count;\n }\n endingcol--;\n \n for(int i=endingcol;count<total && i>=startingcol; i--)\n {\n count++;\n ans[endingrow][i]=count;\n }\n endingrow--;\n \n for(int i=endingrow;count<total && i>=startingrow; i--)\n {\n count++;\n ans[i][startingcol]=count;\n \n }\n startingcol++;\n }\n \n \n return ans;\n \n \n }\n};\n```\n# java code \n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n \n // creating a matrix of n x n\n \n int[][] ans = new int[n][n];\n \n int count = 1;\n int total = n * n;\n \n // initialize variables for keeping track of starting and ending rows and columns\n int startingRow = 0;\n int endingRow = n - 1;\n int startingCol = 0;\n int endingCol = n - 1;\n \n while (count <= total) {\n \n // fill in the top row from left to right\n for (int i = startingCol; i <= endingCol; i++) {\n ans[startingRow][i] = count;\n count++;\n }\n startingRow++;\n \n // fill in the right column from top to bottom\n for (int i = startingRow; i <= endingRow; i++) {\n ans[i][endingCol] = count;\n count++;\n }\n endingCol--;\n \n // fill in the bottom row from right to left\n for (int i = endingCol; i >= startingCol; i--) {\n ans[endingRow][i] = count;\n count++;\n }\n endingRow--;\n \n // fill in the left column from bottom to top\n for (int i = endingRow; i >= startingRow; i--) {\n ans[i][startingCol] = count;\n count++;\n }\n startingCol++;\n }\n \n return ans;\n }\n}\n``` | 19 | 1 | ['Matrix', 'C++', 'Java'] | 0 |
spiral-matrix-ii | 0ms faster than 100 % | easy to understand solution | C++ | 0ms-faster-than-100-easy-to-understand-s-ofw1 | \nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> res(n,vector<int>(n));\n int top = 0, bottom = | rv237 | NORMAL | 2020-12-20T08:50:03.247004+00:00 | 2020-12-20T08:50:03.247042+00:00 | 999 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> res(n,vector<int>(n));\n int top = 0, bottom = n-1, left = 0, right = n-1;\n int val = 1,direction=1;\n while(left<=right && top<=bottom)\n {\n if(direction == 1) \n { \n for(int i=left;i<=right;i++)\n {\n res[top][i]=val++;\n }\n top++;\n direction=2;\n }\n else if(direction == 2)\n {\n for(int i = top;i<=bottom;i++)\n {\n res[i][right]=val++;\n }\n right--;\n direction = 3;\n }\n else if(direction == 3)\n {\n for(int i = right;i>=left;i--)\n {\n res[bottom][i]=val++;\n }\n bottom--;\n direction=4;\n }\n else if(direction == 4)\n {\n for(int i=bottom;i>=top;i--)\n {\n res[i][left]=val++;\n }\n left++;\n direction = 1;\n }\n }\n return res;\n }\n};\n``` | 18 | 2 | ['C'] | 1 |
spiral-matrix-ii | javascript simple | javascript-simple-by-cauld-entk | Runtime: 68 ms, faster than 90.62% of JavaScript online submissions for Spiral Matrix II.\nMemory Usage: 38.7 MB, less than 83.38% of JavaScript online submissi | cauld | NORMAL | 2021-09-19T02:05:28.034711+00:00 | 2021-09-19T02:08:01.656499+00:00 | 2,047 | false | Runtime: 68 ms, faster than 90.62% of JavaScript online submissions for Spiral Matrix II.\nMemory Usage: 38.7 MB, less than 83.38% of JavaScript online submissions for Spiral Matrix II.\n\n```\nvar generateMatrix = function(n) {\n \n let output = new Array(n).fill(0).map(() => new Array(n).fill(0))\n \n let count = 0;\n \n let size = n * n;\n \n let left = 0;\n \n let right = n - 1;\n \n let top = 0;\n \n let bottom = n -1;\n \n while(count < size){\n \n //going left\n for(let i = left; i <= right; i++){\n count++;\n output[top][i] = count;\n }\n top++;\n \n // going down\n for(let i = top; i <= bottom; i++){\n count++;\n output[i][right] = count;\n }\n right--;\n \n //going left\n for(let i = right; i >= left; i--){\n count++;\n output[bottom][i] = count;\n }\n bottom--;\n \n //going up\n for(let i = bottom; i >= top; i--){\n count++;\n output[i][left] = count;\n }\n left++;\n }\n \n return output;\n \n};\n \n};\n``` | 16 | 0 | ['JavaScript'] | 2 |
spiral-matrix-ii | 👏Beats 100.00% of users with Java🎉|| Matrix 💯||✅Simple & Easy Well Explained Solution 🔥💥 | beats-10000-of-users-with-java-matrix-si-zd9u | Intuition\nThis function generates a square matrix of size \'n\' in a spiral pattern, filling it with incrementing numbers. It iterates through each layer, adju | Rutvik_Jasani | NORMAL | 2024-04-27T09:10:49.919879+00:00 | 2024-04-27T10:28:21.050499+00:00 | 298 | false | # Intuition\nThis function generates a square matrix of size \'n\' in a spiral pattern, filling it with incrementing numbers. It iterates through each layer, adjusting positions to create the spiral effect.\n\n# I Think This Can Help You(For Proof Click on the Image)\n[](https://leetcode.com/problems/spiral-matrix-ii/submissions/1243103077/)\n\n# Approach\n1. Initialize variables:\n ```java\n int[][] ans = new int[n][n]; // Initialize a 2D array to store the matrix\n int cnt = 1; // Counter to keep track of the numbers to be filled\n int i = 0, j = 0; // Variables to track the current position in the matrix\n ```\n\n2. Spiral filling loop:\n ```java\n while (n > 1) {\n // Fill the top row from left to right\n for (int k = 1; k < n; k++) {\n ans[i][j] = cnt;\n j++;\n cnt++;\n }\n // Fill the rightmost column from top to bottom\n for (int k = 1; k < n; k++) {\n ans[i][j] = cnt;\n i++;\n cnt++;\n }\n // Fill the bottom row from right to left\n for (int k = 1; k < n; k++) {\n ans[i][j] = cnt;\n j--;\n cnt++;\n }\n // Fill the leftmost column from bottom to top\n for (int k = 1; k < n; k++) {\n ans[i][j] = cnt;\n i--;\n cnt++;\n }\n // Move to the next inner square\n n = n - 2; // Decrease the size of the square by 2\n i++; // Move to the next row\n j++; // Move to the next column\n }\n ```\n\n3. Fill the center element if `n` is odd:\n ```java\n if (n == 1) {\n ans[i][j] = cnt;\n }\n ```\n\n4. Return the filled matrix:\n ```java\n return ans;\n ```\n\n# Complexity\n- Time complexity:\nO(n*n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n int[][] ans = new int[n][n];\n int cnt=1;\n int i=0,j=0;\n while(n>1){\n for(int k=1;k<n;k++){\n ans[i][j] = cnt;\n j++;\n cnt++;\n }\n for(int k=1;k<n;k++){\n ans[i][j] = cnt;\n i++;\n cnt++;\n }\n for(int k=1;k<n;k++){\n ans[i][j] = cnt;\n j--;\n cnt++;\n }\n for(int k=1;k<n;k++){\n ans[i][j] = cnt;\n i--;\n cnt++;\n }\n n=n-2;\n i++;\n j++;\n }\n if(n==1){\n ans[i][j]=cnt;\n }\n return ans;\n }\n}\n```\n\n\n | 14 | 0 | ['Array', 'Matrix', 'Simulation', 'Java'] | 0 |
spiral-matrix-ii | Python3 Solution using Spiral traversal in O(n*n) time | python3-solution-using-spiral-traversal-fh1bx | I have seen some of the solutions to this problem in the discussion section which is mostly related to checking the matrix bounds or validating if the current c | constantine786 | NORMAL | 2022-04-13T01:11:03.261762+00:00 | 2022-04-13T09:45:20.851983+00:00 | 1,964 | false | I have seen some of the solutions to this problem in the discussion section which is mostly related to checking the matrix bounds or validating if the current cell is zero to determine the change of direction. \n\nI have actually solved a similar problem before -> https://leetcode.com/problems/spiral-matrix/ and I will try to explain the same approach that I used there as I think its easier to comprehend and seemed more intuitive.\n\nThe main idea here is that we initialize **bounds** for four directions: **up**, **down**, **left** and **right**. For each iteration, we **traverse the complete spiral** i.e in all 4 directions. At the end, we just need to **increment or decrement the bounds** accordingly. The code has an extra check after traversing right and down directions to determine if it has landed on same row or column. \n\n```\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n up, down, left, right = 0, n-1, 0, n-1\n \n num = 1\n while num <= (n * n):\n for idx in range(left, right + 1):\n matrix[up][idx] = num\n num+=1\n \n for idx in range(up + 1, down + 1):\n matrix[idx][right] = num\n num+=1\n \n # not the same row\n if up != down:\n for idx in range(right - 1, left - 1, -1):\n matrix[down][idx] = num\n num+=1\n #not the same column\n if left != right:\n for idx in range(down - 1, up, -1):\n matrix[idx][left] = num\n num+=1\n \n left+=1\n up+=1\n right-=1\n down-=1\n return matrix\n```\n\nPlease upvote if you find it useful\n | 14 | 0 | ['Python', 'Python3'] | 2 |
spiral-matrix-ii | Very Easy and Straight forward Approach. Beats 100% solution.matri Do Upvote. | very-easy-and-straight-forward-approach-0m7o1 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this solution is to simulate the process of filling the matrix in | Anmol_jais | NORMAL | 2024-02-14T10:30:39.407335+00:00 | 2024-02-14T10:30:39.407365+00:00 | 1,748 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is to simulate the process of filling the matrix in a spiral order. The approach involves defining four variables to keep track of the boundaries of the matrix: startingrow, startingcol, endingrow, and endingcol. These variables represent the row and column indices where the spiral starts and ends at each iteration.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe intuition behind this solution is to simulate the process of filling the matrix in a spiral order. The approach involves defining four variables to keep track of the boundaries of the matrix: startingrow, startingcol, endingrow, and endingcol. These variables represent the row and column indices where the spiral starts and ends at each iteration.\n\nHere\'s the step-by-step approach:\n\n1. Initialize count to 1, representing the current number to be filled in the matrix.\n2. Initialize total to n*n, representing the total number of elements in the matrix.\n3. Create a 2D vector matrix of size n x n to store the spiral matrix.\n4. Initialize startingrow, startingcol, endingrow, and endingcol to represent the boundaries of the matrix.\n5. Run a while loop until count reaches total.\n6. Inside the loop, perform four iterations:\n a. Traverse from startingcol to endingcol on the startingrow filling the matrix with incrementing values of count.\n b. Increment startingrow.\n c. Traverse from startingrow to endingrow on the endingcol, filling the matrix with incrementing values of count.\n d. Decrement endingcol.\n e. Traverse from endingcol to startingcol on the endingrow, filling the matrix with incrementing values of count.\n f. Decrement endingrow.\n g. Traverse from endingrow to startingrow on the startingcol, filling the matrix with incrementing values of count.\n h. Increment startingcol.\n7. Return the generated matrix.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n^2)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n int count=1;\n int total=n*n;\n vector<vector<int>>matrix(n,vector<int>(n));\n\n int startingrow=0;\n int startingcol=0;\n int endingrow=n-1;\n int endingcol=n-1;\n\n int k=1;\n\n while(count<=total)\n {\n for(int i=startingcol;count<=total && i<=endingcol;i++)\n {\n matrix[startingrow][i]=count;\n count++;\n }\n startingrow++;\n\n for(int i=startingrow;count<=total && i<=endingrow;i++)\n {\n matrix[i][endingcol]=count;\n count++;\n }\n endingcol--;\n\n for(int i=endingcol;count<=total && i>=startingcol;i--)\n {\n matrix[endingrow][i]=count;\n count++;\n }\n endingrow--;\n\n for(int i=endingrow;count<=total && i>=startingrow;i--)\n {\n matrix[i][startingcol]=count;\n count++;\n }\n startingcol++;\n\n }\n return matrix;\n }\n};\n``` | 13 | 0 | ['Array', 'Matrix', 'Simulation', 'C++'] | 0 |
spiral-matrix-ii | Java, simple and clear, easy understood | java-simple-and-clear-easy-understood-by-r5kd | ```\npublic class Solution {\n public int[][] generateMatrix(int n) {\n // similar to spiral matrix I,done by myself\n int[][] rs = new int[n][ | jim39 | NORMAL | 2016-07-27T07:59:12.316000+00:00 | 2016-07-27T07:59:12.316000+00:00 | 4,010 | false | ```\npublic class Solution {\n public int[][] generateMatrix(int n) {\n // similar to spiral matrix I,done by myself\n int[][] rs = new int[n][n];\n int top = 0,bottom = n-1,left = 0,right = n-1;\n int num = 1;\n \n while(left<=right && top <=bottom){\n for(int i=left;i<=right;i++){\n rs[top][i] = num++;\n }\n top++;\n for(int i= top;i<=bottom;i++){\n rs[i][right] = num++;\n }\n right--;\n for(int i= right;i>=left;i-- ){\n rs[bottom][i] = num++;\n }\n bottom--;\n for(int i = bottom;i>=top;i--){\n rs[i][left] = num++;\n }\n left++;\n }\n return rs;\n }\n} | 13 | 0 | ['Java'] | 3 |
spiral-matrix-ii | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-ilb0 | \nclass Solution {\n func generateMatrix(_ n: Int) -> [[Int]] {\n var matrix: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: n)\n | sergeyleschev | NORMAL | 2022-04-04T05:29:47.763556+00:00 | 2022-04-04T05:31:34.818010+00:00 | 283 | false | ```\nclass Solution {\n func generateMatrix(_ n: Int) -> [[Int]] {\n var matrix: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: n)\n let count = n / 2\n var num = 1\n \n for i in 0..<count {\n var index = 0\n for j in i..<(n - i - 1) {\n \n let i1 = i\n let j1 = j\n matrix[i1][j1] = num + j - i\n \n let i2 = j\n let j2 = n - i - 1\n matrix[i2][j2] = num + j + (n - i * 2 - 1) * 1 - i\n \n let i3 = n - i - 1\n let j3 = n - j - 1\n matrix[i3][j3] = num + j + (n - i * 2 - 1) * 2 - i\n \n let i4 = n - j - 1\n let j4 = i\n matrix[i4][j4] = num + j + (n - i * 2 - 1) * 3 - i\n index += 4\n }\n num += index\n }\n \n if n % 2 == 1 { matrix[(n - 1) / 2][(n - 1) / 2] = n * n }\n return matrix\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 12 | 0 | ['Swift'] | 0 |
spiral-matrix-ii | ✅ [Accepted] Solution for Swift | accepted-solution-for-swift-by-asahiocea-8lhb | swift\nclass Solution {\n func generateMatrix(_ n: Int) -> [[Int]] {\n let map = [Int](repeating: -1, count: n)\n var res = [[Int]](repeating: | AsahiOcean | NORMAL | 2022-02-02T08:49:19.634566+00:00 | 2022-04-13T13:14:10.447801+00:00 | 990 | false | ```swift\nclass Solution {\n func generateMatrix(_ n: Int) -> [[Int]] {\n let map = [Int](repeating: -1, count: n)\n var res = [[Int]](repeating: map, count: n)\n let grid = (n * n)\n var top = 0, btm = n - 1, lhs = 0, rhs = (n - 1)\n var elm = 1\n \n while elm <= grid {\n if lhs <= rhs && elm <= grid { // left -> right\n for i in lhs...rhs {\n res[top][i] = elm\n elm += 1\n }\n top += 1\n }\n if top <= btm && elm <= grid { // top -> bottom\n for i in top...btm {\n res[i][rhs] = elm\n elm += 1\n }\n rhs -= 1\n }\n if lhs <= rhs && elm <= grid { // right -> left\n for i in (lhs...rhs).reversed() {\n res[btm][i] = elm\n elm += 1\n }\n btm -= 1\n }\n if top <= btm && elm <= grid { // bottom -> top\n for i in (top...btm).reversed() {\n res[i][lhs] = elm\n elm += 1\n }\n lhs += 1\n }\n }\n return res\n }\n}\n```\n\n---\n\n<p>\n<details>\n<summary>\n<img src="https://git.io/JDblm" height="24">\n<b>TEST CASES</b>\n</summary>\n\n<p><pre>\n<b>Result:</b> Executed 2 tests, with 0 failures (0 unexpected) in 0.012 (0.014) seconds\n</pre></p>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n func test0() {\n let value = solution.generateMatrix(3)\n XCTAssertEqual(value, [[1,2,3],[8,9,4],[7,6,5]])\n }\n \n func test1() {\n let value = solution.generateMatrix(1)\n XCTAssertEqual(value, [[1]])\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details>\n</p> | 12 | 0 | ['Swift'] | 0 |
spiral-matrix-ii | C++ Easy to understand. Solved LIVE ON STREAM | c-easy-to-understand-solved-live-on-stre-9xqz | Pretty straight forward. No special algo. \nWe solve problems EVERYDAY 6pm PT. There are dozens of us.\nLink in profile\n\n\nclass Solution {\n \npublic:\ | midnightsimon | NORMAL | 2022-04-13T01:44:50.168918+00:00 | 2022-04-13T01:44:50.168947+00:00 | 854 | false | Pretty straight forward. No special algo. \nWe solve problems EVERYDAY 6pm PT. There are dozens of us.\n**Link in profile**\n\n```\nclass Solution {\n \npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n, 0));\n \n int top = 0;\n int bot = n - 1;\n int left = 0;\n int right = n - 1;\n int dir = 0; \n int num = 1;\n \n while(top <= bot && left <= right) {\n if(dir == 0) {\n for(int c = left; c <= right; c++) {\n matrix[top][c] = num++;\n }\n dir++;\n top++;\n } else if (dir == 1) {\n for(int r = top; r <= bot; r++) {\n matrix[r][right] = num++;\n }\n dir++;\n right--;\n } else if (dir == 2) {\n for(int c = right; c >= left; c--) {\n matrix[bot][c] = num++;\n }\n dir++;\n bot--;\n } else if (dir == 3) {\n for(int r = bot; r >= top; r--){\n matrix[r][left] = num++;\n }\n dir = 0;\n left++;\n }\n } \n return matrix;\n }\n};\n``` | 11 | 0 | [] | 0 |
spiral-matrix-ii | java dfs recursive | java-dfs-recursive-by-lastdoctor-agmw | \nclass Solution {\n public int[][] generateMatrix(int n) {\n var m = new int[n][n];\n dfs(m, 0, 0, false, 1);\n return m;\n }\n p | lastdoctor | NORMAL | 2022-01-20T21:35:27.170282+00:00 | 2022-01-20T21:35:27.170315+00:00 | 348 | false | ```\nclass Solution {\n public int[][] generateMatrix(int n) {\n var m = new int[n][n];\n dfs(m, 0, 0, false, 1);\n return m;\n }\n private void dfs(int[][] m, int row, int col, boolean goup,int count) {\n if (row < 0 || col < 0 || col >= m[0].length || row >= m.length || m[row][col] != 0) return;\n m[row][col] = count;\n count++;\n if (goup) dfs(m, row-1, col, true, count);\n dfs(m, row, col+1, false, count);\n dfs(m, row + 1, col, false, count);\n dfs(m, row, col-1, false, count);\n dfs(m, row-1, col, true, count);\n }\n}\n``` | 9 | 0 | ['Depth-First Search', 'Recursion', 'Java'] | 0 |
spiral-matrix-ii | Single Loop Java Solution | Easy to Understand | 0 ms | single-loop-java-solution-easy-to-unders-6gkw | Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n\nclass Solution {\n public int[][] generateMatrix(int n) {\n int x = | Divakar_26 | NORMAL | 2023-05-10T05:02:26.453332+00:00 | 2023-05-11T03:28:26.980685+00:00 | 1,240 | false | # Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n int x = 1,cnt = 0;\n int[][] ans = new int[n][n];\n int i = 0,j = 0,k = 0;\n while(cnt < (n * n)){\n i(ans[i][j] == 0){\n ans[i][j] = x++;\n if(i == k && j < n - 1 - k) j++;\n else if(j == n - 1 - k && i < n - 1 - k) i++;\n else if(i == n - 1 - k && j <= n - 1 - k && j != k) j--;\n else if(i <= n - 1 - k && j == k) i--;\n cnt++;\n }else{ \n k++;\n i++;\n j++;\n }\n }\n return ans;\n }\n}\n``` | 8 | 0 | ['Java'] | 1 |
spiral-matrix-ii | [JavaScript] Neat: 3 methods: elegant, math, no-if | javascript-neat-3-methods-elegant-math-n-qlh4 | 1. Elegant (optimized 2nd approach)\n\njs\nconst generateMatrix = (n) => {\n const M = [...Array(n)].map(() => Array(n).fill(0));\n let x = 0, y = 0, dx = 1, | mxn42 | NORMAL | 2022-04-13T00:18:34.010175+00:00 | 2022-04-13T22:27:35.741341+00:00 | 867 | false | ## 1. Elegant (optimized 2nd approach)\n\n```js\nconst generateMatrix = (n) => {\n const M = [...Array(n)].map(() => Array(n).fill(0));\n let x = 0, y = 0, dx = 1, dy = 0;\n for (let i = 1, nn = n**2; i <= nn; ++i) {\n M[y][x] = i;\n if (!M[y + dy] || M[y + dy][x + dx] !== 0)\n [dx, dy] = [-dy, dx];\n x += dx;\n y += dy;\n }\n return M;\n};\n```\n\n## 2. Math power\n\n```js\nconst generateMatrix = (n) => {\n const {max, abs, floor} = Math;\n const num = (x, y) => {\n x += x - n + 1;\n y += y - n + 1;\n const m = max(abs(x), abs(y));\n let p = floor((x + y) / 2);\n if (x < y) p = 2 * m - p;\n return n * n - m * m - m + p;\n }\n \n const M = [];\n for (let y = 0; y < n; ++y) {\n M[y] = [];\n for (let x = 0; x < n; ++x)\n M[y][x] = num(x, y);\n }\n return M;\n};\n```\n\n## 3. Without IF\n\nThere are the steps in each direction in the spiral for n = 5.\n`[0, 5, 4, 4, 3, 3, 2, 2, 1, 1]` and for any n `[0, n, n - 1, n - 1, ..., 3, 3, 2, 2, 1, 1]`\nUpdate signs of directions.\n`[0, 5, 4, -4, -3, 3, 2, -2, -1, 1]`\n\n```js\nconst generateMatrix = (n) => { \n const M = [...Array(n)].map(() => Array(n));\n let v = 0, x = -1, y = 0;\n for (let i = 0, m, s, dx, dy; i < 2*n; ++i) {\n m = i && (2*n - i + 1) / 2|0;\n s = (-1)**((i - 1)/2|0);\n dx = s * (i % 2);\n dy = s * ((i + 1) % 2);\n for (let j = 0; j < m; ++j) {\n x += dx;\n y += dy;\n M[y][x] = ++v;\n }\n }\n return M;\n};\n``` | 8 | 0 | ['JavaScript'] | 1 |
spiral-matrix-ii | [C++] 100% simple walk the spiral solution | c-100-simple-walk-the-spiral-solution-by-udmh | My C++ walk the spiral solution going clockwise from outside to inside\n\n\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n | bhaviksheth | NORMAL | 2020-12-07T13:25:10.891840+00:00 | 2020-12-07T16:26:43.681217+00:00 | 808 | false | My C++ walk the spiral solution going clockwise from outside to inside\n\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n // create n * n vector of vectors we will populate and return at the end\n vector<vector<int>> result(n, vector<int>(n));\n \n // calculate how many levels deep the spiral is and keep count of walking the spiral\n int level = ceil(n / 2), count = 1;\n \n // start from outside level moving inside\n for (int l = 0; l <= level; ++l) {\n // populate top row from left to right\n for (int a = l; a < n - l; ++a) result[l][a] = count++;\n \n // populate right column from top to bottom\n for (int b = l + 1; b < n - l; ++b) result[b][n - l - 1] = count++;\n \n // populate bottom row from right to left\n for (int c = l + 1; c < n - l; ++c) result[n - l - 1][n - c - 1] = count++;\n \n // populate left column from bottom to top\n for (int d = l + 1; d < n - l - 1; ++d) result[n - d - 1][l] = count++;\n }\n \n return result;\n }\n};\n``` | 8 | 0 | ['C'] | 1 |
spiral-matrix-ii | Share my simple solution with graphical explanation - Java | share-my-simple-solution-with-graphical-o2bf3 | If n is odd, only the first direction will cover it (top left -> right, shown as # in the graph), because the other three direction all start from the next posi | liwang | NORMAL | 2015-02-25T21:32:58+00:00 | 2015-02-25T21:32:58+00:00 | 1,541 | false | If n is odd, only the first direction will cover it (top left -> right, shown as # in the graph), because the other three direction all start from the next position( +1 or -1).\n\n /**\n \t * -> -> ->\n \t * ^ |\n \t * | |\n \t * <- <-- V\n \t * \n \t * # # # #\n \t * % $\n \t * % $\n \t * & & & $\n \t * \n \t */\n public static int[][] generateMatrix(int n) {\n \tint[][] res = new int[n][n];\n \t\n \tint num = 1;\n \tint level = (int) Math.ceil(n / 2.);\n \t\n \tfor(int i = 0; i < level; i++) {\n \t\t\n \t\t// top left -> right, shown as #\n \t\tfor(int j = i; j < n - i; j++)\n \t\t\tres[i][j] = num++;\n \t\t\n \t\t// top right + 1 -> bot, shown as $\n \t\tfor(int j = i + 1; j < n - i; j++)\n \t\t\tres[j][n - i - 1] = num++;\n \t\t\n \t\t// bot right - 1 -> left, shown as &\n \t\tfor(int j = n - i - 2; j >= i; j--)\n \t\t\tres[n - i - 1][j] = num++;\n \t\t\n \t\t// bot left -1 -> top + 1, shown as %\n \t\tfor(int j = n - i - 2; j > i; j--)\n \t\t\tres[j][i] = num++;\n \t}\n \treturn res;\n } | 8 | 0 | ['Java'] | 1 |
spiral-matrix-ii | Java. Spiral matrix 2 | java-spiral-matrix-2-by-red_planet-4xef | \n\nclass Solution {\n public static void spiralOrder(int[][] matrix) {\n int move[][] = {{0,1},{1,0},{0,-1},{-1,0}};\n int x = 0;\n int | red_planet | NORMAL | 2023-05-10T19:08:38.139279+00:00 | 2023-05-10T19:08:38.139309+00:00 | 318 | false | \n```\nclass Solution {\n public static void spiralOrder(int[][] matrix) {\n int move[][] = {{0,1},{1,0},{0,-1},{-1,0}};\n int x = 0;\n int y = -1;\n int i = 0;\n boolean finish = false;\n int ch = 1;\n while (!finish) {\n finish = true;\n while (true) {\n int tmpX = x;\n int tmpY = y;\n if (x + move[i % 4][0] < matrix.length && x + move[i % 4][0] > -1) x += move[i % 4][0];\n if (y + move[i % 4][1] < matrix[0].length && y + move[i % 4][1] > -1) y += move[i % 4][1];\n if (x < matrix.length && y < matrix[0].length && matrix[x][y] == 0) {\n matrix[x][y] = ch++;\n finish = false;\n }\n else {\n x = tmpX;\n y = tmpY;\n break;\n }\n }\n i++;\n }\n }\n\n public static int[][] generateMatrix(int n) {\n int matrix[][] = new int[n][n];\n spiralOrder(matrix);\n return matrix;\n }\n}\n``` | 7 | 0 | ['Java'] | 0 |
spiral-matrix-ii | Simple java solution | Beginner friendly | Easy to Understand | simple-java-solution-beginner-friendly-e-atid | Intuition\n Describe your first thoughts on how to solve this problem. \nStarting from the top left corner and moving clockwise. It traverse by filling the top | antovincent | NORMAL | 2023-05-10T04:38:57.477152+00:00 | 2023-05-10T04:38:57.477186+00:00 | 1,672 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStarting from the top left corner and moving clockwise. It traverse by filling the top row, right column, bottom row, and left column of the matrix in sequence until the entire matrix is filled.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize a 2D array of size n x n with all elements set to 0.\n- Use four variables l, t, b, and r to keep track of the boundaries of the matrix.\n- Use a while loop that continues until either t becomes greater than b or l becomes greater than r, indicating that the entire matrix has been filled.\n- Use four nested if statements, each of which generates a segment of the spiral by iterating through the appropriate row or column and assigning values to the matrix elements.\n- After each segment is generated, update the corresponding boundary variables to exclude the row or column that has been filled.\n- Return the resulting matrix.\n\n# Complexity\n- Time complexity:O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n int [][] a = new int[n][n];\n int l=0,t=0,b=n-1,r=n-1,v=1;\n while(t<=b||l<=r){\n if(t<=b){\n for(int i=l;i<=r;i++)\n a[t][i]=v++;\n t++;\n }\n if(l<=r){\n for(int i=t;i<=b;i++)\n a[i][r]=v++;\n r--;\n }\n if(t<=b){\n for(int i=r;i>=l;i--)\n a[b][i]=v++;\n b--;\n }\n if(t<=b){\n for(int i=b;i>=t;i--)\n a[i][l]=v++;\n }\n l++;\n }\n return a;\n }\n}\n``` | 7 | 0 | ['Java'] | 1 |
spiral-matrix-ii | C++✅✅||Beats 100% Solution||T.C=O(N*N)||Fully explained step by step. | cbeats-100-solutiontconnfully-explained-zcsuc | \n# Approach\n1.Here we have a sqare matrix of size n*n;\n2.declare variables like starting top=0, right= n-1, left=0, bottom= n-1 and a =1.\n3.declare count=0 | yashwant_yadav14 | NORMAL | 2023-05-09T22:42:00.927595+00:00 | 2023-05-09T22:42:00.927650+00:00 | 4,702 | false | \n# Approach\n1.Here we have a sqare matrix of size n*n;\n2.declare variables like starting top=0, right= n-1, left=0, bottom= n-1 and a =1.\n3.declare count=0 and check it at every moment that it is less than and equal to end.\nfirst we will print first row, by moving from left to right. and increase top by 1, so that we can print next row in second iteration and insert value in vector and increase by 1.\nThen, we will print last column, by moving from top to bottom and decrease right by 1 so that we can to next inner col and insert value in vector and increase by 1.\nthen we will print last row, by moving from right to left. and decrease bottom by 1, so that we can move to next inner row in next iteration and insert value in vector and increase by 1.\nthen we will print first col, by moving from bottom to top, and increase left by 1, so that we can move to next col in next iteration and insert value in vector and increase by 1.\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>>res(n,vector<int>(n));\n int top=0;int left=0;\n int right=n-1;int bottom=n-1;\n int a=1;\n while(top<=bottom && left<=right){\n for(int i=left;i<=right;i++){//top\n \n res[top][i]=a;\n a++;\n }\n top++;\n for(int i=top;i<=bottom;i++){//right\n res[i][right]=a;\n a++;\n }\n right--;\n if(top<=bottom){\n for(int i=right;i>=left;i--){//bottom in reverse\n res[bottom][i]=a;\n a++;\n }\n bottom--;\n }\n if(left<=right){\n for(int i=bottom;i>=top;i--){//left in reverse\n res[i][left]=a;\n a++;\n }\n left++;\n }\n }\n return res;\n \n }\n};\n``` | 7 | 0 | ['C++'] | 4 |
spiral-matrix-ii | 🧠 Spiral Matrix I, II, III, IV Solutions | spiral-matrix-i-ii-iii-iv-solutions-by-h-4dgc | Explaination\n- This is a very simple and easy to understand solution. I have traversed RIGHT and incremented TOP, then traverse DOWN and decrement RIGHT, then | hrishi13 | NORMAL | 2023-02-18T17:54:36.368121+00:00 | 2023-07-06T11:37:39.268537+00:00 | 198 | false | # Explaination\n- This is a very simple and easy to understand solution. I have traversed RIGHT and incremented TOP, then traverse DOWN and decrement RIGHT, then I traverse LEFT and decrement BOTTOM, and finally I have traversed UP and increment LEFT.\n\n- The only tricky part is that when I traverse left or up I have to check whether the row or col still exists to prevent duplicates. \nAny comments greatly appreciated.\n\n# Complexity\n- Time Complexity: O(m*n)\n- Space Complexity: O(1)\n\n# Spiral Matrix I\n```\nclass Solution {\npublic:\n vector<int> spiralOrder(vector<vector<int>>& matrix) {\n vector<int> v;\n if (matrix.size() == 0) \n return v;\n \n int left = 0, right = matrix[0].size() - 1, top = 0, bottom = matrix.size()- 1;\n \n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n v.push_back(matrix[top][i]);\n }\n top++;\n \n for (int i = top; i <= bottom; i++) {\n v.push_back(matrix[i][right]);\n }\n right--;\n \n for (int i = right; top <= bottom && i >= left; i--) {\n v.push_back(matrix[bottom][i]);\n }\n bottom--;\n \n for (int i = bottom; left <= right && i >= top; i--) {\n v.push_back(matrix[i][left]);\n }\n left++;\n }\n return v;\n }\n};\n```\n# Spiral Matrix II\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int> (n, 0));\n \n int left = 0, right = matrix[0].size() - 1, top = 0, bottom = matrix.size()- 1;\n int count = 1;\n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = count;\n count++;\n }\n top++;\n \n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = count;\n count++;\n }\n right--;\n \n for (int i = right; top <= bottom && i >= left; i--) {\n matrix[bottom][i] = count;\n count++;\n }\n bottom--;\n \n for (int i = bottom; left <= right && i >= top; i--) {\n matrix[i][left] = count;\n count++;\n }\n left++;\n }\n return matrix;\n }\n};\n```\n# Spiral Matrix III\n```\nclass Solution {\npublic:\n vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n vector<vector<int>> matrix;\n int count = 0, step = 1;\n \n while(count < rows*cols){\n\n for (int i=0; i<step; i++){\n if(rStart >= 0 and rStart < rows and cStart >= 0 and cStart < cols){\n matrix.push_back({rStart, cStart});\n count++;\n }\n cStart++;\n }\n\n for (int i=0; i<step; i++){\n if(rStart >= 0 and rStart < rows and cStart >= 0 and cStart < cols){\n matrix.push_back({rStart, cStart});\n count++;\n }\n rStart++;\n }\n step++;\n\n for (int i=0; i<step; i++){\n if(rStart >= 0 and rStart < rows and cStart >= 0 and cStart < cols){\n matrix.push_back({rStart, cStart});\n count++;\n }\n cStart--;\n }\n\n for (int i=0; i<step; i++){\n if(rStart >= 0 and rStart < rows and cStart >= 0 and cStart < cols){\n matrix.push_back({rStart, cStart});\n count++;\n }\n rStart--;\n }\n step++;\n }\n return matrix;\n }\n};\n```\n# Sprial Matrix IV\n```\nclass Solution {\npublic:\n vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {\n vector<vector<int>> matrix(m, vector<int> (n, -1));\n int left = 0, right = n-1, top = 0, bottom = m-1;\n while(left<=right and top<=bottom){\n for(int i = left; i<=right; i++){\n if(head){\n matrix[top][i] = head->val;\n head = head->next;\n }\n }\n top++;\n for(int i = top; i<=bottom; i++){\n if(head){\n matrix[i][right] = head->val;\n head = head->next;\n }\n }\n right--;\n for(int i = right; top<=bottom && i>=left; i--){ \n if(head){\n matrix[bottom][i] = head->val;\n head = head->next;\n }\n } \n bottom--;\n for(int i = bottom; left<=right && i>=top; i--){\n if(head){\n matrix[i][left] = head->val;\n head = head->next;\n }\n }\n left++;\n }\n return matrix;\n }\n};\n``` | 7 | 0 | ['C++'] | 1 |
spiral-matrix-ii | Easy Java Solution Beats:100% online Java Submissions: | easy-java-solution-beats100-online-java-loxwq | \nclass Solution {\n public int[][] generateMatrix(int n) {\n int[][] ans=new int[n][n];\n \n int rowBegin=0;\n int rowEnd=n-1;\n | om_shanti | NORMAL | 2022-07-20T16:25:04.997261+00:00 | 2022-07-20T16:25:04.997361+00:00 | 440 | false | ```\nclass Solution {\n public int[][] generateMatrix(int n) {\n int[][] ans=new int[n][n];\n \n int rowBegin=0;\n int rowEnd=n-1;\n int columnBegin=0;\n int columnEnd=n-1;\n int counter=0;\n \n while(rowBegin<=rowEnd && columnBegin<=columnEnd && counter<=n*n){\n \n for(int i=columnBegin;i<=columnEnd;i++){\n counter++;\n ans[rowBegin][i]=counter;\n }\n rowBegin++;\n for(int i=rowBegin;i<=rowEnd;i++){\n counter++;\n ans[i][columnEnd]=counter;\n }\n columnEnd--;\n if(rowBegin<=rowEnd){\n for(int i=columnEnd;i>=columnBegin;i--){\n counter++;\n ans[rowEnd][i]=counter;\n }\n \n }\n rowEnd--;\n if(columnBegin<=columnEnd){\n for(int i=rowEnd;i>=rowBegin;i--){\n counter++; \n ans[i][columnBegin]=counter;\n }\n \n }\n columnBegin++;\n \n }\n \n return ans;\n }\n}\n``` | 7 | 0 | ['Java'] | 0 |
spiral-matrix-ii | [C++]Two pointer approach | ctwo-pointer-approach-by-arsator-mj4g | \nAlgorithm\n---------\n* Step1: Initialize beg = 0 and end = n - 1\n* Step2: Repeat Step3 to Step7 while beg < end\n* Step3: Fill current first row(beg) from | arsator | NORMAL | 2022-04-13T01:46:56.086037+00:00 | 2022-04-13T07:12:39.760631+00:00 | 666 | false | ```\nAlgorithm\n---------\n* Step1: Initialize beg = 0 and end = n - 1\n* Step2: Repeat Step3 to Step7 while beg < end\n* Step3: Fill current first row(beg) from left-right\n* Step4: Fill current last column(end) from top-bottom\n* Step5: Fill current last row(end) from right-left\n* Step6: Fill current first column(beg) from bottom-top\n* Step7: Increment beg and decrement end\n* Step8: Go to Step2\n* Step9: Fill the cell[beg][end] if beg == end\n* Step10: Return matrix\n\nComplexities\n------------\n* Time: O(n*n)\n* Space: O(1)\n\nNote: Since, the matrix is square, we can traverse it spirally by using just 2 pointers.\n```\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n \n int beg = 0, end = n - 1, temp = -1, ptr = 1;\n while(beg < end) {\n // fill left to right\n temp = beg;\n while(temp < end) {\n matrix[beg][temp++] = ptr++;\n }\n \n // fill top to bottom\n temp = beg;\n while(temp < end) {\n matrix[temp++][end] = ptr++;\n }\n \n //fill right to left\n temp = end;\n while(temp > beg) {\n matrix[end][temp--] = ptr++;\n }\n \n //fill bottom to top\n temp = end;\n while(temp > beg) {\n matrix[temp--][beg] = ptr++;\n }\n beg++;\n end--;\n }\n \n // for odd n\n if(beg == end) matrix[beg][end] = ptr;\n return matrix;\n }\n};\n``` | 7 | 0 | [] | 1 |
spiral-matrix-ii | Python | Simple Logic | python-simple-logic-by-tanaypatil-87e2 | We can move in 4 directions:\nIf direction == 0: Move from left to right in top row\nIf direction == 1: Move from top to bottom in right column\nIf direction == | tanaypatil | NORMAL | 2020-08-14T14:12:07.174562+00:00 | 2020-08-14T14:12:07.176737+00:00 | 746 | false | We can move in 4 directions:\nIf direction == 0: Move from left to right in top row\nIf direction == 1: Move from top to bottom in right column\nIf direction == 2: Move from right to left in bottom row\nIf direction == 3: Move from bottom to top in left column\n\n```\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n if not n:\n return []\n if n == 1:\n return [[1]]\n \n ans = [[0]* n for _ in range(n)]\n \n left, right = 0, n-1\n top, bottom = 0, n-1\n \n k = 1\n direction = 0\n \n while left <= right and top <= bottom:\n # from left to right in top row\n if direction == 0:\n for j in range(left, right+1):\n ans[top][j] = k\n k += 1\n top += 1\n direction = 1\n elif direction == 1:\n # from top to bottom in right column\n for i in range(top, bottom+1):\n ans[i][right] = k\n k += 1\n right -= 1\n direction = 2\n elif direction == 2:\n # from right to left in bottom row\n for j in range(right, left-1, -1):\n ans[bottom][j] = k\n k += 1\n bottom -= 1\n direction = 3\n else:\n # bottom to top in left column\n for i in range(bottom, top-1, -1):\n ans[i][left] = k\n k += 1\n left += 1\n direction = 0\n return ans | 7 | 0 | ['Python3'] | 1 |
spiral-matrix-ii | 7-line Python solution, step pattern is n, n-1, n-1, n-2, n-2 ..., 2, 2, 1, 1 | 7-line-python-solution-step-pattern-is-n-zkkx | If n is 5, step list will be [5, 4, 4, 3, 3, 2, 2, 1, 1], it means move forward 5 steps, turn right, move forward 4 steps, turn right, move forward 4 steps, tur | kitt | NORMAL | 2016-03-22T08:58:20+00:00 | 2018-10-24T13:31:03.275330+00:00 | 1,505 | false | If `n` is 5, `step` list will be [5, 4, 4, 3, 3, 2, 2, 1, 1], it means move forward 5 steps, turn right, move forward 4 steps, turn right, move forward 4 steps, turn right and so on. `x` axis is from left to right, `y` axis is from top to bottom, we start from point `(-1, 0)`.\n\n def generateMatrix(self, n):\n mat, x, y, dx, dy, number = [[0] * n for i in xrange(n)], -1, 0, 1, 0, 0\n for step in [i / 2 for i in xrange(2 * n, 1, -1)]:\n for j in xrange(step):\n x, y, number = x + dx, y + dy, number + 1\n mat[y][x] = number\n dx, dy = -dy, dx # turn right\n return mat | 7 | 0 | ['Python'] | 2 |
spiral-matrix-ii | Spiral Matrix II [C++] | spiral-matrix-ii-c-by-moveeeax-zohj | IntuitionThe problem requires constructing a square matrix filled with integers from 1 to n^2 in a spiral order. A direct approach is to simulate the filling pr | moveeeax | NORMAL | 2025-01-18T09:29:41.438413+00:00 | 2025-01-18T09:29:41.438413+00:00 | 599 | false | # Intuition
The problem requires constructing a square matrix filled with integers from `1` to `n^2` in a spiral order. A direct approach is to simulate the filling process layer by layer, moving in the directions: right, down, left, and up.
# Approach
1. Initialize a matrix of size `n x n` with default values.
2. Use four boundaries (`top`, `bottom`, `left`, `right`) to track the current layer being filled.
3. Fill the matrix:
- Traverse from `left` to `right` along the `top` row and increment the `top` boundary.
- Traverse from `top` to `bottom` along the `right` column and decrement the `right` boundary.
- Traverse from `right` to `left` along the `bottom` row (if still within bounds) and decrement the `bottom` boundary.
- Traverse from `bottom` to `top` along the `left` column (if still within bounds) and increment the `left` boundary.
4. Repeat the process until all elements are filled.
# Complexity
- **Time Complexity:**
$$O(n^2)$$
Each cell in the matrix is visited exactly once during the filling process.
- **Space Complexity:**
$$O(1)$$ (excluding the output matrix)
The additional space used is constant, as we are only using variables to keep track of boundaries and the current number.
# Code
```cpp
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int num = 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; ++i) matrix[top][i] = num++;
++top;
for (int i = top; i <= bottom; ++i) matrix[i][right] = num++;
--right;
if (top <= bottom) {
for (int i = right; i >= left; --i) matrix[bottom][i] = num++;
--bottom;
}
if (left <= right) {
for (int i = bottom; i >= top; --i) matrix[i][left] = num++;
++left;
}
}
return matrix;
}
};
``` | 6 | 0 | ['C++'] | 0 |
spiral-matrix-ii | 🔥Easy 🔥Java 🔥Solution with Proper 🔥Explanation beats 🔥100% in TC. | easy-java-solution-with-proper-explanati-vtzx | \n\n\n\n# Intuition & Approach\n Describe your approach to solving the problem. \nThis code initializes an n x n matrix with all elements set to zero. It then u | shahscript | NORMAL | 2023-05-12T14:49:30.597677+00:00 | 2023-05-12T14:49:30.597705+00:00 | 647 | false | \n\n\n\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\nThis code initializes an n x n matrix with all elements set to zero. It then uses four variables t, b, l, and r to keep track of the boundaries of the current spiral. It starts filling the matrix by traversing from left to right along the top boundary, then from top to bottom along the right boundary, then from right to left along the bottom boundary, and finally from bottom to top along the left boundary. It repeats this process until all elements have been filled in the matrix. Finally, it returns the filled matrix.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N*N)\n\n# Code\n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n List<Integer> res = new ArrayList<>();\n int[][] arr = new int[n][n];\n int b = n, r = n;\n int t = 0, l = 0, size = b*r,s=1;\n while(t<=b && l<=r){\n for (int i = l; i < r; i++) {\n arr[t][i]=s++;\n }\n t++;\n for (int i = t; i < b; i++) {\n arr[i][r-1] = s++;\n }\n r--;\n\n for (int i = r-1; i >= l; i--) {\n arr[b-1][i] = s++;\n }\n b--;\n\n for (int i = b-1; i >= t; i--) {\n arr[i][l]=s++;\n }\n l++;\n\n\n }\n return arr;\n\n }\n}\n\n``` | 6 | 0 | ['Java'] | 0 |
spiral-matrix-ii | |C++| Spiral arrangement of the matrix | c-spiral-arrangement-of-the-matrix-by-jo-wyf0 | 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 | JoKeRooo7 | NORMAL | 2023-05-10T19:29:58.505894+00:00 | 2023-05-10T19:29:58.505940+00:00 | 1,270 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n int i, j, o, k, num;\n vector<vector<int>> vec(n, vector<int>(n));\n for (i = j = o = 0 , num = 1; num <= (n * n) && i < n - o; o++, i++, j++) {\n cout << vec[i][j] << endl;\n while (j < n - o) {\n if (num > n*n) break;\n vec[i][j++] = num++;\n }\n j--;\n for (k = i + 1; k < n - o; k++) {\n if (num > n*n) break;\n vec[k][j] = num++;\n }\n k--;\n while (j > o) {\n if (num > n*n) break;\n vec[k][--j] = num++;\n }\n while (k > i + 1) {\n if (num > n*n) break;\n vec[--k][o] = num++;\n }\n \n }\n return vec;\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
spiral-matrix-ii | SIMPLE || CLEAN || BEATS 100% | simple-clean-beats-100-by-zacrolydredlob-u2tt | Intuition\nSimple brute force\n\n# Approach\nWe use left , right , top , bottom pointers to represent the configuration of the matrix.\nSTEPS of traversal:\n\n1 | zacrolydRedlobster | NORMAL | 2023-05-10T01:23:57.347157+00:00 | 2023-05-10T01:30:34.641170+00:00 | 780 | false | # Intuition\nSimple brute force\n\n# Approach\nWe use left , right , top , bottom pointers to represent the configuration of the matrix.\nSTEPS of traversal:\n\n1. Traverse from left to right , then update top=top+1, AS topmost row is filled.\n\n2. Traverse from top to bottom, then update right=right-1, AS rightmost column is filled.\n\n3. Traverse from right to left, then update bottom= bottom-1 , AS \nbottomMost row is filled.\n\n 4. Traverse from bottom to top, then update left=left+1, \n AS leftmost column is filled.\n\n# Complexity\n- Time complexity:\n O(N*N) for traversing the matrix.\n\n- Space complexity:\n O(N*N) for storing the matrix.\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n int num=1,left=0,right=n-1,top=0,bottom=n-1;\n vector<vector<int>>matrix(n,vector<int>(n));\n\n while(left<=right && top<=bottom){\n for(int i=left; i<=right; i++){\n matrix[top][i]=num++;\n }\n top++;\n\n for(int i=top;i<=bottom;i++){\n matrix[i][right]=num++;\n }\n right--;\n\n for(int i=right;i>=left;i--){\n matrix[bottom][i]=num++;\n }\n bottom--;\n\n for(int i=bottom;i>=top;i--){\n matrix[i][left]=num++;\n }\n left++;\n }\n\n return matrix;\n }\n};\n\n\n```\n | 6 | 0 | ['Matrix', 'C++'] | 1 |
spiral-matrix-ii | Simple spiral traversing | C# | +98% efficient | simple-spiral-traversing-c-98-efficient-u53xo | Intuition & Approach\n Describe your first thoughts on how to solve this problem. \nAfter initializing a new 2-d Array, simply traverse the array from the outer | Baymax_ | NORMAL | 2023-05-10T00:59:42.574753+00:00 | 2023-05-10T00:59:42.574792+00:00 | 1,231 | false | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nAfter initializing a new 2-d Array, simply traverse the array from the outer spiral towards inner spiral and place the incrementing numbers\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2) - as we need to place (n^2) items in the array of size (n*n), given n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) - as we do not use any extra memory other than the resulting 2-d array\n\n## Please upvote if you like the simplicity of the approach\n\n# Code\n```\npublic class Solution {\n public int[][] GenerateMatrix(int n) {\n int[][] result = Initialize(n);\n int num = 1;\n for (int i = 0, j = n - 1; i <= j; i++, j--)\n {\n for (int x = i; x <= j; x++)\n {\n result[i][x] = num++;\n }\n \n for (int x = i + 1; x <= j; x++)\n {\n result[x][j] = num++;\n }\n \n for (int x = j - 1; x >= i; x--)\n {\n result[j][x] = num++;\n }\n \n for (int x = j - 1; x > i; x--)\n {\n result[x][i] = num++;\n }\n }\n \n return result;\n }\n \n private int[][] Initialize(int n)\n {\n int[][] result = new int[n][];\n for (int i = 0; i < n; i++)\n {\n result[i] = new int[n];\n }\n \n return result;\n }\n}\n```\n\n## Please upvote if you like the simplicity of the approach | 6 | 0 | ['Array', 'Matrix', 'C#'] | 1 |
spiral-matrix-ii | 99.6% javascript easy to understand | 996-javascript-easy-to-understand-by-rla-b3yt | Visit my youtube! Thank you!\nhttps://www.youtube.com/channel/UCkhEaNAOO8tig5NHqqxXIeg\n\n# Code\n\n/**\n * @param {number} n\n * @return {number[][]}\n */\nvar | rlawnsqja850 | NORMAL | 2023-05-10T00:34:20.692563+00:00 | 2023-05-10T05:16:02.863277+00:00 | 2,056 | false | Visit my youtube! Thank you!\nhttps://www.youtube.com/channel/UCkhEaNAOO8tig5NHqqxXIeg\n\n# Code\n```\n/**\n * @param {number} n\n * @return {number[][]}\n */\nvar generateMatrix = function(n) {\n let save = Array.from(Array(n),()=>new Array(n).fill(0))\n let count =1;\n let left =0;\n let right =n-1;\n let bottom = n-1;\n let top = 0;\n let dir = 0;\n\n while(count <= n*n){\n if(dir == 0){\n for(let i =left; i<=right; i++){\n save[top][i] = count;\n count++\n }\n top++\n dir++\n }\n if(dir == 1){\n for(let i =top; i<=bottom; i++){\n save[i][right] = count;\n count++\n }\n right--\n dir++ \n }\n if(dir == 2){\n for(let i =right; i>=left; i--){\n save[bottom][i] = count;\n count++\n }\n bottom--\n dir++ \n }\n if(dir == 3){\n for(let i =bottom; i>=top; i--){\n save[i][left] = count;\n count++\n }\n left++\n dir++ \n }\n dir = 0;\n }\n\n return save;\n};\n``` | 6 | 0 | ['JavaScript'] | 2 |
spiral-matrix-ii | CPP|| Easy | cpp-easy-by-kmowade-n1ez | class Solution {\npublic:\n\n vector> generateMatrix(int n) {\n vector> res(n,vector(n,0));\n int left=0,right=n-1,top=0,bottom=n-1;\n i | Kmowade | NORMAL | 2022-04-13T12:19:09.017134+00:00 | 2022-04-13T12:19:09.017174+00:00 | 465 | false | class Solution {\npublic:\n\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> res(n,vector<int>(n,0));\n int left=0,right=n-1,top=0,bottom=n-1;\n int x=1;\n while(x<=n*n){\n for(int i=left;i<=right;i++)\n res[top][i]=x++;\n top++;\n for(int i=top;i<=bottom;i++)\n res[i][right]=x++;\n right--;\n for(int i=right;i>=left;i--)\n res[bottom][i]=x++;\n bottom--;\n for(int i=bottom;i>=top;i--)\n res[i][left]=x++;\n left++;\n }\n return res;\n }\n}; | 6 | 0 | ['C', 'Matrix', 'C++'] | 0 |
spiral-matrix-ii | ✅ Simple C++ solution(with explanation) | Commented | Faster than 100.00% of C++ online submissions | simple-c-solutionwith-explanation-commen-woe3 | Algorithm:\n\n Enter value in starting row (horizonal, left to right)\n Enter value in ending column (vertical, top to bottom)\n Enter value in ending row (hori | Endeavourer | NORMAL | 2022-03-16T17:33:47.532635+00:00 | 2022-03-23T14:36:35.082515+00:00 | 349 | false | Algorithm:\n\n* Enter value in starting row (horizonal, left to right)\n* Enter value in ending column (vertical, top to bottom)\n* Enter value in ending row (horizonal, right to left)\n* Enter value in starting column (vertical, bottom to top)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> ans(n,vector<int>(n,1));\n //index intialisation\n int strow=0, stcol=0;\n int endrow=n-1,endcol=n-1;\n //counters\n int cnt=n*n;\n int a=1;\n \n while(a<=cnt){\n \n //enter value in starting row\n for(int i=stcol;i<=endcol&&a<=cnt;i++){\n ans[strow][i]=a;\n a++;\n }\n strow++;\n \n //enter value in ending col\n for(int i=strow;i<=endrow&&a<=cnt;i++){\n ans[i][endcol]=a;\n a++;\n }\n endcol--;\n \n //enter value in ending row\n for(int i=endcol;i>=stcol&&a<=cnt;i--){\n ans[endrow][i]=a;\n a++;\n }\n endrow--;\n \n //enter value in starting col\n for(int i=endrow;i>=strow&&a<=cnt;i--){\n ans[i][stcol]=a;\n a++;\n }\n stcol++;\n }\n return ans;\n }\n};\n```\n***Upvote ++ (if it helps)*** | 6 | 0 | ['C', 'Matrix', 'C++'] | 0 |
spiral-matrix-ii | python Simple and easy solution | python-simple-and-easy-solution-by-neutr-rh78 | The approach is inspired by "Stefan Pochmann"\n\nfirst we will push an element in the array\nthen, rotate the array.\n\n(We will start from the 9 upto 1)\ne.g. | neutron08 | NORMAL | 2021-01-03T07:12:19.324307+00:00 | 2021-01-03T07:12:19.324350+00:00 | 507 | false | The approach is inspired by [ "Stefan Pochmann"](https://leetcode.com/StefanPochmann/)\n\nfirst we will push an element in the array\nthen, rotate the array.\n\n(We will start from the 9 upto 1)\ne.g. for n = 3\n\n|9|\nrotate and push new element\n|8|\n|9|\n\nrotate and push new elements\n|6 7|\n|9 8|\n\nrotate and push new elements\n|4 5|\n|9 6|\n|8 7|\n\nrotate and push new elements\n\n|1 2 3|\n|8 9 4|\n|7 6 5|\n\n\n\n\n```\ndef generateMatrix(n):\n#n = 3 for example\n result = []\n current = n*n -1 # = 8, for n = 3 \n #current will hold the value for inserting\n result.append([current + 1]) # first case, Handling first element explicitly result = [[9]]\n while current > 1:\n result = list(zip(*result[::-1])) # will rotate the array\n temp = len(result[0])\n # temp will hold the length of the first element of the result i.e. len([9]) i.e. 1\n # from temp we would know how many elements we have to push\n \n result.insert(0,list(range(current-temp+1,current+1)))\n #inserting the values on the top of the array\n \n current = current -temp\n return result\n``` | 6 | 0 | ['Python3'] | 1 |
spiral-matrix-ii | Beat 100% Java Code | beat-100-java-code-by-fighternanreborn-iyg4 | Hi all, this code divides the whole construction into n/2 loops. In each loop, it finishes one spiral. If n is an odd number, add an extra number in the center | FighterNanReborn | NORMAL | 2018-04-14T09:19:54.871358+00:00 | 2018-04-14T09:19:54.871358+00:00 | 193 | false | Hi all, this code divides the whole construction into n/2 loops. In each loop, it finishes one spiral. If n is an odd number, add an extra number in the center before return.\n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n if (n==1)\n return new int [][] {{1}};\n int[][] result=new int[n][n];\n int col=0, row=0, min=0, max=n-1, i=1, loop=0;\n while(loop<n/2) {\n result[row][col]=i++;\n if (row==min && col!=max) \n col++;\n else if(col==max && row!=max)\n row++;\n else if(row==max && col!=min) \n col--;\n else if(col==min && row!=min+1)\n row--;\n else {\n min++;\n max--;\n col=min;\n row=min;\n loop++;\n }\n }\n if (n%2==1) \n result[n/2][n/2]=i;\n return result; \n }\n}\n``` | 6 | 1 | [] | 0 |
spiral-matrix-ii | Simplest c++ solution, easy and clear, have a look | simplest-c-solution-easy-and-clear-have-w4wql | comments will be highly appreciated . \n\n vector> generateMatrix(int n) {\n // 2d vector initialization vector> myvec(rowsize,vector(colsize,0)) | rakesh_joshi | NORMAL | 2016-06-21T14:20:38+00:00 | 2016-06-21T14:20:38+00:00 | 1,198 | false | comments will be highly appreciated . \n\n vector<vector<int>> generateMatrix(int n) {\n // 2d vector initialization vector<vector<int>> myvec(rowsize,vector<int>(colsize,0));\n vector<vector<int>> res(n,vector<int>(n,0));\n if(!n) return res;\n \n int l=0,r=n-1,t=0,b=n-1,limit=n*n+1; // l=left column , r=right column , t=top row, b=bottom row \n int count=1;\n \n while(count<limit){ // loop until count == n*n \n for(int i=l;i<=r;i++) res[t][i]=count++; // process top row\n t++;\n for(int i=t;i<=b;i++) res[i][r]=count++; // process right column\n r--;\n if(count==limit) break; // termination condition to avoid overwritting \n for(int i=r; i>=l;i--) res[b][i]=count++; // process bottom row\n b--;\n for(int i=b;i>=t;i--) res[i][l]=count++; //process left column\n l++;\n }\n \n return res;\n } | 6 | 0 | [] | 2 |
spiral-matrix-ii | BEST AND EASY APPROACH FOR SOLVING!!!!!COMPETITIVE PROGRAMMING | best-and-easy-approach-for-solvingcompet-yhv6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nsoc=starting of column\ | goswami_vineet1463 | NORMAL | 2023-05-10T13:54:03.470547+00:00 | 2023-05-10T14:23:34.185003+00:00 | 356 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsoc=starting of column\nsor=starting of row\neor=end of column\neoc=end of coloumn\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>>finaldata(n,vector<int>(n,0));\n int soc=0,sor=0,eor=n-1,eoc=n-1,count=1;\n while(soc<=eoc && sor<=eor)\n {\n for(int x=soc;x<=eoc;x++)\n {\n finaldata[sor][x]=count;\n count++;\n }\n sor++;\n for(int x=sor;x<=eor;x++)\n {\n finaldata[x][eoc]=count;\n count++;\n }\n eoc--;\n for(int x=eoc;x>=soc;x--)\n {\n finaldata[eor][x]=count;\n count++;\n }\n eor--;\n for(int x=eor;x>=sor;x--)\n {\n finaldata[x][soc]=count;\n count++;\n }\n soc++;\n }\n return finaldata;\n }\n};\nIF YOU LOVE YOUR MOTHER UPVOTE!!!\n``` | 5 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.