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
roman-to-integer
✅Beginner Friendly 🔥|| Step By Steps Solution ✅ || Beats 100% User in Each Solution of Me ✅🔥 ||
beginner-friendly-step-by-steps-solution-sz15
\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Intuition :\nThe main idea behind converting a Roman numeral to an integer is to l
Letssoumen
NORMAL
2024-11-10T01:44:27.779710+00:00
2024-11-10T01:44:27.779748+00:00
7,175
false
\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Intuition :\nThe main idea behind converting a Roman numeral to an integer is to look for specific patterns of subtraction. For instance, when a smaller numeral appears before a larger one (like IV for 4 or IX for 9), it implies a subtraction. Otherwise, the Roman numerals are simply added in descending order.\n\n### Approach :\n1. Define a mapping of Roman numerals to their integer values.\n2. Traverse each character in the string:\n - If the current numeral is less than the next one, subtract its value from the total.\n - Otherwise, add its value to the total.\n3. Return the accumulated total at the end.\n\n### Steps :\n1. Initialize a total variable to accumulate the result.\n2. Loop through each character of the input string:\n - If the value of the current character is less than the value of the next character, subtract it from the total.\n - Otherwise, add it to the total.\n3. Once the loop completes, return the total.\n\n### Time Complexity :\n- **Time Complexity**: \\( O(n) \\), where \\( n \\) is the length of the Roman numeral string. Each character is processed once.\n- **Space Complexity**: \\( O(1) \\), since we only store a few fixed mappings and use a constant amount of additional space.\n\n![WhatsApp Image 2024-10-25 at 11.38.29.jpeg](https://assets.leetcode.com/users/images/8e7a65d5-685d-4027-b78c-969f2dc7d863_1729836651.7045465.jpeg)\n\n### Solutions in Java, Python, and C++ :\n\n#### Python 3 :\n```python\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman_map={\'I\':1,\'V\':5,\'X\':10,\'L\':50,\'C\':100,\'D\':500,\'M\':1000}\n total=0\n length=len(s)\n for i in range(length):\n if i<length-1 and roman_map[s[i]]<roman_map[s[i+1]]:\n total-=roman_map[s[i]]\n else:\n total+=roman_map[s[i]]\n return total\n\n```\n\n#### Java :\n```java\nclass Solution {\nint romanToInt(String s) {\n Map<Character,Integer> romanMap=new HashMap<>();\n romanMap.put(\'I\',1);\n romanMap.put(\'V\',5);\n romanMap.put(\'X\',10);\n romanMap.put(\'L\',50);\n romanMap.put(\'C\',100);\n romanMap.put(\'D\',500);\n romanMap.put(\'M\',1000);\n int total=0;\n int length=s.length();\n for(int i=0;i<length;i++){\n if(i<length-1 && romanMap.get(s.charAt(i))<romanMap.get(s.charAt(i+1))){\n total-=romanMap.get(s.charAt(i));\n } else {\n total+=romanMap.get(s.charAt(i));\n }\n }\n return total;\n}\n}\n```\n\n#### C++ :\n```cpp \n#include <unordered_map>\n#include <string>\nusing namespace std;\nclass Solution {\npublic:\nint romanToInt(string s) {\n unordered_map<char,int> romanMap={{\'I\',1},{\'V\',5},{\'X\',10},{\'L\',50},{\'C\',100},{\'D\',500},{\'M\',1000}};\n int total=0;\n int length=s.size();\n for(int i=0;i<length;i++){\n if(i<length-1 && romanMap[s[i]]<romanMap[s[i+1]]){\n total-=romanMap[s[i]];\n } else {\n total+=romanMap[s[i]];\n }\n }\n return total;\n}\n};\n```\n\n\n
30
1
['Hash Table', 'Math', 'C++', 'Java', 'Python3']
2
roman-to-integer
💯✅HashMap Solution | JAVA | VERY EASY
hashmap-solution-java-very-easy-by-dipes-jdks
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
dipesh_12
NORMAL
2023-03-16T03:59:18.635899+00:00
2023-03-16T03:59:18.635931+00:00
8,228
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 romanToInt(String s) {\n Map<Character,Integer>map=new HashMap<>();\n map.put(\'I\',1);\n map.put(\'V\',5);\n map.put(\'X\',10);\n map.put(\'L\',50);\n map.put(\'C\',100);\n map.put(\'D\',500);\n map.put(\'M\',1000);\n int value=0;\n for(int i=0;i<s.length();i++){\n if(i<s.length()-1 && map.get(s.charAt(i))<map.get(s.charAt(i+1))){\n value-=map.get(s.charAt(i));\n }\n else{\n value+=map.get(s.charAt(i));\n }\n }\n return value;\n }\n}\n```
30
0
['Java']
3
roman-to-integer
Java solution Using HaspMap Faster than 100% (Easy to Understand)
java-solution-using-haspmap-faster-than-askjh
class Solution {\n public int romanToInt(String s) {\n Mapmap=new HashMap<>();\n map.put(\'I\', 1);\n map.put(\'V\', 5);\n map.pu
Abhishek_Mandge
NORMAL
2022-08-08T07:54:08.766581+00:00
2022-08-08T07:54:08.766609+00:00
1,534
false
class Solution {\n public int romanToInt(String s) {\n Map<Character,Integer>map=new HashMap<>();\n map.put(\'I\', 1);\n map.put(\'V\', 5);\n map.put(\'X\', 10);\n map.put(\'L\', 50);\n map.put(\'C\', 100);\n map.put(\'D\', 500);\n map.put(\'M\', 1000);\n \n \n int result=map.get(s.charAt(s.length()-1));\n \n for(int i=s.length()-2;i>=0;i--){\n if(map.get(s.charAt(i))<map.get(s.charAt(i+1))){\n result-=map.get(s.charAt(i));\n }else{\n result+=map.get(s.charAt(i));\n }\n }\n return result;\n }\n}\n\'\'\'\n.****Plz upvote if you find it USEFUL. May you will get all you deserve .Hard work will payOff
30
0
[]
0
roman-to-integer
Python Solution with explanantion
python-solution-with-explanantion-by-amc-32ti
The idea is to walk each letter of the roman integer in sequence and undo previous addition in the case the previous roman numeral is less than the current one.
amchoukir
NORMAL
2019-08-13T12:12:18.882484+00:00
2019-08-13T12:14:03.669516+00:00
4,655
false
The idea is to walk each letter of the roman integer in sequence and undo previous addition in the case the previous roman numeral is less than the current one.\n\n```python\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman_to_int = {\n \'I\' : 1,\n \'V\' : 5,\n \'X\' : 10,\n \'L\' : 50,\n \'C\' : 100,\n \'D\' : 500,\n \'M\' : 1000\n }\n \n result = 0\n prev_value = 0\n for letter in s:\n value = roman_to_int[letter]\n result += value\n if value > prev_value:\n # preceding roman nummber is smaller\n # we need to undo the previous addition\n # and substract the preceding roman char\n # from the current one, i.e. we need to\n # substract twice the previous roman char\n result -= 2 * prev_value\n prev_value = value\n return result\n```\n\nFor other solutions you can have a look at my other post\n\n[Other solutions](https://leetcode.com/problems/roman-to-integer/discuss/323556/Python-solution-based-on-dictionary-with-look-ahead)
30
0
['Python', 'Python3']
3
roman-to-integer
[Java] Without Map | 3ms
java-without-map-3ms-by-ieshagupta-g7r9
We don\'t need to use Extra memory. This problem can be solved easily without using any Map.\nHelper method:\n\n int getValue(char c){\n if(c==\'I\') ret
ieshagupta
NORMAL
2021-06-19T18:56:21.708060+00:00
2021-06-19T18:56:21.708089+00:00
2,529
false
We don\'t need to use Extra memory. This problem can be solved easily without using any Map.\nHelper method:\n```\n int getValue(char c){\n if(c==\'I\') return 1;\n else if(c==\'V\') return 5;\n else if(c==\'X\') return 10;\n else if(c==\'L\') return 50;\n else if(c==\'C\') return 100;\n else if(c==\'D\') return 500;\n else return 1000;\n }\n```\n\nMain logic \n```\nfor(int i=0;i<n-1;i++){\n int a = getValue(s.charAt(i));\n int b = getValue(s.charAt(i+1));\n if(a<b){\n res-=a;\n }else{\n res+=a;\n } \n }\n res += getValue(s.charAt(n-1)); \n```\n
29
0
['Java']
4
roman-to-integer
🗓️ Daily LeetCoding Challenge August, Day 15
daily-leetcoding-challenge-august-day-15-pxzf
This problem is the Daily LeetCoding Challenge for August, Day 15. Feel free to share anything related to this problem here! You can ask questions, discuss what
leetcode
OFFICIAL
2022-08-15T00:00:07.679480+00:00
2022-08-15T00:00:07.679525+00:00
24,015
false
This problem is the Daily LeetCoding Challenge for August, Day 15. Feel free to share anything related to this problem here! You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made! --- If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide - **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem. - **Images** that help explain the algorithm. - **Language and Code** you used to pass the problem. - **Time and Space complexity analysis**. --- **📌 Do you want to learn the problem thoroughly?** Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/roman-to-integer/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis. <details> <summary> Spoiler Alert! We'll explain these 3 approaches in the official solution</summary> **Approach 1:** Left-to-Right Pass **Approach 2:** Left-to-Right Pass Improved **Approach 3:** Right-to-Left Pass </details> If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)! --- <br> <p align="center"> <a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank"> <img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" /> </a> </p> <br>
28
0
[]
64
roman-to-integer
C Solution Using a Switch Statement
c-solution-using-a-switch-statement-by-i-68ar
\nint getValue(const char * s){\n switch(*s) {\n case \'I\': return (s[1] == \'V\' || s[1] == \'X\') ? -1 : 1;\n case \'X\': return (s[1] == \'
irenemp
NORMAL
2021-03-03T19:13:14.473827+00:00
2021-03-03T19:52:34.686144+00:00
2,136
false
```\nint getValue(const char * s){\n switch(*s) {\n case \'I\': return (s[1] == \'V\' || s[1] == \'X\') ? -1 : 1;\n case \'X\': return (s[1] == \'L\' || s[1] == \'C\') ? -10 : 10;\n case \'C\': return (s[1] == \'D\' || s[1] == \'M\') ? -100 : 100;\n case \'V\': return 5;\n case \'L\': return 50;\n case \'D\': return 500;\n case \'M\': return 1000;\n }\n return 0;\n}\n\nint romanToInt(char * s){\n int result = 0; \n \n for(;*s != \'\\0\'; ++s) {\n result += getValue(s);\n }\n return result;\n}\n```
28
0
['C']
0
roman-to-integer
Python solution
python-solution-by-santhosh2-kzka
def romanToInt(self, s):\n\n romans = {'M': 1000, 'D': 500 , 'C': 100, 'L': 50, 'X': 10,'V': 5,'I': 1}\n\n prev_value = running_total
santhosh2
NORMAL
2015-01-15T16:26:39+00:00
2018-09-11T04:15:39.404201+00:00
7,903
false
def romanToInt(self, s):\n\n romans = {'M': 1000, 'D': 500 , 'C': 100, 'L': 50, 'X': 10,'V': 5,'I': 1}\n\n prev_value = running_total =0\n \n for i in range(len(s)-1, -1, -1):\n int_val = romans[s[i]]\n if int_val < prev_value:\n running_total -= int_val\n else:\n running_total += int_val\n prev_value = int_val\n \n return running_total
28
1
[]
8
roman-to-integer
[Java] [Descriptive][Easy] 99% more efficient
java-descriptiveeasy-99-more-efficient-b-5ncv
Intuition\nFirstly I tried to implement "CORE LOGIC" of this problem then tried to enhance the solution with different approach. So I\'m sharing two solutions.\
sadriddin17
NORMAL
2023-05-22T05:05:59.568083+00:00
2023-05-25T12:48:38.924543+00:00
11,024
false
# Intuition\nFirstly I tried to implement "CORE LOGIC" of this problem then tried to enhance the solution with different approach. So I\'m sharing two solutions.\n\n# Approaches\n1. The solution iterates through the Roman numeral string from `right to left` and applies the necessary additions and subtractions based on the current symbol. The algorithm correctly handles the cases where subtraction is required, ensuring accurate conversion.\n\n2. The second approach utilizes map to store the symbol-value mappings for the seven Roman numeral symbols. The algorithm iterates through the input Roman numeral string from `left to right`, performing the necessary additions and subtractions based on the symbol values. By comparing each symbol with the next one, it accurately handles the subtraction cases.\n\n# Complexity\n- Time complexity:\nit is O(n) for both approaches \n\n- Space complexity:\nO(1) for both\n\n# Code for SOLUTION 1\n```\n int result = 0;\n for (int i = s.length() - 1; i >= 0; i--) {\n switch (s.charAt(i)) {\n case \'I\' -> {\n if (result >= 5)result-= 1;\n else result += 1;\n }case \'V\' -> {\n if (result >= 10)result-= 5;\n else result += 5;\n }case \'X\' -> {\n if (result >= 50)result-= 10;\n else result += 10;\n }case \'L\' -> {\n if (result > 100)result-= 50;\n else result += 50;\n }case \'C\' -> {\n if (result >= 500)result-= 100;\n else result += 100; \n }case \'D\' -> {\n if (result >= 1000)result-= 500;\n else result += 500;\n }case \'M\' -> {\n result += 1000;\n }\n }\n }\n return result;\n```\n\n# Code for SOLUTION 2\n\nWe iterate through each character of s using a for loop, checking if the current character is smaller than the next character. If so, it subtracts the corresponding value from the result. This is because in Roman numerals, when a smaller numeral appears before a larger one, it indicates subtraction. Otherwise, it adds the corresponding value to the result. eg: IX => 1(I) < 10(X) => result = -1 => result = -1 + 10 = 9\n\n```\n Map<Character, Integer> map = new HashMap<>() {{\n put(\'I\', 1);\n put(\'V\', 5);\n put(\'X\', 10);\n put(\'L\', 50);\n put(\'C\', 100);\n put(\'D\', 500);\n put(\'M\', 1000);\n }};\n int result = 0, n = s.length();\n\n for (int i = 0; i < n; i++) {\n if (i < n - 1 && map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {\n result -= map.get(s.charAt(i));\n } else {\n result += map.get(s.charAt(i));\n }\n }\n\n return result;\n```\n\n***Your upvote is appraciated if you like the solution!***
27
0
['Hash Table', 'Math', 'String', 'Java']
3
roman-to-integer
Simple and Clean Solution - typeScript | javaScript
simple-and-clean-solution-typescript-jav-bv7x
\nfunction romanToInt(s: string): number {\nconst map = {\n \'I\':1,\n \'V\':5,\n \'X\':10,\n \'L\':50,\n \'C\':100,\n \'D\':500,\n \'M\':1
saad189
NORMAL
2022-07-27T19:59:41.147543+00:00
2022-07-27T19:59:41.147590+00:00
3,646
false
```\nfunction romanToInt(s: string): number {\nconst map = {\n \'I\':1,\n \'V\':5,\n \'X\':10,\n \'L\':50,\n \'C\':100,\n \'D\':500,\n \'M\':1000,\n \'IV\':4,\n \'IX\':9,\n \'XL\':40,\n \'XC\':90,\n \'CD\':400,\n \'CM\':900\n}\n\n let sum = 0;\n for (let i = 0; i< s.length;){\n const index = s[i] + s[i+1];\n const word = map[index] ? index: s[i];\n sum += map[word];\n i+=word.length;\n }\n return sum;\n};\n```
27
0
['TypeScript', 'JavaScript']
4
roman-to-integer
👾C#, Java, Python3,JavaScript Solution (Easy-Understanding)
c-java-python3javascript-solution-easy-u-zhg9
C#,Java,Python3,JavaScript different solution with explanation\n\u2B50https://zyrastory.com/en/coding-en/leetcode-en/leetcode-13-roman-to-integer-solution-and-e
Daisy001
NORMAL
2022-10-20T23:33:07.178065+00:00
2022-10-20T23:33:07.178127+00:00
19,400
false
### C#,Java,Python3,JavaScript different solution with explanation\n**\u2B50[https://zyrastory.com/en/coding-en/leetcode-en/leetcode-13-roman-to-integer-solution-and-explanation-en/](https://zyrastory.com/en/coding-en/leetcode-en/leetcode-13-roman-to-integer-solution-and-explanation-en/)\u2B50**\n\n**\uD83E\uDDE1See next question solution - [Zyrastory-Longest Common Prefix](https://zyrastory.com/en/coding-en/leetcode-en/leetcode-14-longest-common-prefix-solution-and-explanation-en/)**\n\n\n#### **Example : C# Code ( You can also find an easier solution in the post )**\n```\npublic class Solution {\n private readonly Dictionary<char, int> dict = new Dictionary<char, int>{{\'I\',1},{\'V\',5},{\'X\',10},{\'L\',50},{\'C\',100},{\'D\',500},{\'M\',1000}};\n \n public int RomanToInt(string s) {\n \n char[] ch = s.ToCharArray();\n \n int result = 0;\n int intVal,nextIntVal;\n \n for(int i = 0; i <ch.Length ; i++){\n intVal = dict[ch[i]];\n \n if(i != ch.Length-1)\n {\n nextIntVal = dict[ch[i+1]];\n \n if(nextIntVal>intVal){\n intVal = nextIntVal-intVal;\n i = i+1;\n }\n }\n result = result + intVal;\n }\n return result;\n }\n}\n```\n**\u2B06To see other languages please click the link above\u2B06**\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to let me know (leave comment or messenger me).\n\n**Thanks!**
26
0
['Java', 'Python3', 'JavaScript']
3
roman-to-integer
[Rust] Simple and Fast
rust-simple-and-fast-by-mgrazianoc-51g5
Intuition\nWe replace all edge cases to a sequence of characters.\n\n# Approach\nTo avoid if else statements on current and next elements of an interable of cha
mgrazianoc
NORMAL
2023-03-27T19:23:02.964947+00:00
2023-03-27T19:23:56.366380+00:00
1,515
false
# Intuition\nWe replace all edge cases to a sequence of characters.\n\n# Approach\nTo avoid `if else` statements on current and next elements of an interable of characters, we map each character to a `i32` on the fly!\n\n# Code\n```\nimpl Solution {\n pub fn roman_to_int(s: String) -> i32 {\n let s_translated = s\n .replace("IV", "IIII")\n .replace("IX", "VIIII")\n .replace("XL", "XXXX")\n .replace("XC", "LXXXX")\n .replace("CD", "CCCC")\n .replace("CM", "DCCCC");\n\n s_translated.chars().map(|c| {\n match c {\n \'I\' => 1,\n \'V\' => 5,\n \'X\' => 10,\n \'L\' => 50,\n \'C\' => 100,\n \'D\' => 500,\n \'M\' => 1000,\n _ => 0,\n }\n }).sum()\n }\n}\n```
25
0
['Rust']
6
roman-to-integer
Easy Solution || HashMap || 10ms || JAVA
easy-solution-hashmap-10ms-java-by-rajbi-4ij4
\nclass Solution {\n public int romanToInt(String s) {\n HashMap<Character, Integer> map = new HashMap<>();\n map.put(\'I\',1);\n map.pu
rajbirsingh1233
NORMAL
2022-03-21T07:43:56.250248+00:00
2022-03-23T12:23:17.781442+00:00
1,860
false
```\nclass Solution {\n public int romanToInt(String s) {\n HashMap<Character, Integer> map = new HashMap<>();\n map.put(\'I\',1);\n map.put(\'V\',5);\n map.put(\'X\',10);\n map.put(\'L\',50);\n map.put(\'C\',100);\n map.put(\'D\',500);\n map.put(\'M\',1000);\n int sum = 0;\n for(int i=0; i<s.length(); i++)\n {\n if(i<s.length()-1 && map.get(s.charAt(i)) < map.get(s.charAt(i+1)))\n {\n sum -= map.get(s.charAt(i));\n }\n else{\n sum += map.get(s.charAt(i));\n }\n }\n return sum;\n \n }\n}\n```\n**If you liked my solution Please UPVOTE**\n
25
0
['Java']
1
roman-to-integer
My Java solution
my-java-solution-by-vvgusser-cma3
\nprivate static final Map<Character, Integer> NUMS = new HashMap<Character, Integer>(){{\n put(\'I\', 1);\n put(\'V\', 5);\n put(\'X\', 10);\n put(
vvgusser
NORMAL
2018-04-13T15:13:14.279378+00:00
2022-05-23T12:17:46.102588+00:00
5,233
false
```\nprivate static final Map<Character, Integer> NUMS = new HashMap<Character, Integer>(){{\n put(\'I\', 1);\n put(\'V\', 5);\n put(\'X\', 10);\n put(\'L\', 50);\n put(\'C\', 100);\n put(\'D\', 500);\n put(\'M\', 1000);\n}};\n\nprivate static int convertToInt(String s) {\n\tint r = 0;\n\tint prev = 0;\n\n\tfor (char c : s.toCharArray()) {\n\t\tint v = NUMS.get(c);\n r = ((v > prev) ? r - prev + (v - prev) : r + v);\n prev = v;\n\t}\n\n\treturn r;\n}\n```\n\nIt\'s full code
25
0
[]
4
roman-to-integer
[Java/Python] Short solution - Clean & Concise
javapython-short-solution-clean-concise-wtver
Intuitive\n- Roman numerals are usually written largest to smallest from left to right, for example: XII (7), XXVII (27), III (3)...\n- If a small value is pl
hiepit
NORMAL
2021-02-20T08:59:03.973154+00:00
2021-02-20T10:15:22.367556+00:00
1,093
false
**Intuitive**\n- Roman numerals are usually written largest to smallest from left to right, for example: `XII (7)`, `XXVII (27)`, `III (3)`...\n- If a small value is placed before a bigger value then it\'s a combine number, for exampe: `IV (4)`, `IX (9)`, `XIV (14)`...\n\n**Complexity**\n- Time: `O(N)`, where `N <= 15` is the length of string `s`\n- Space: `O(1)`\n\n**Java**\n```java\nclass Solution {\n static Map<Character, Integer> values = new HashMap<>();\n static {\n values.put(\'I\', 1);\n values.put(\'V\', 5);\n values.put(\'X\', 10);\n values.put(\'L\', 50);\n values.put(\'C\', 100);\n values.put(\'D\', 500);\n values.put(\'M\', 1000);\n }\n\n public int romanToInt(String s) {\n int ans = 0, n = s.length();\n for (int i = 0; i < n; i++) {\n if (i+1 < n && values.get(s.charAt(i)) < values.get(s.charAt(i+1))) {\n\t\t\t\t// If current is a small value and next is a bigger value -> It\'s a combine number\n ans -= values.get(s.charAt(i));\n } else {\n ans += values.get(s.charAt(i));\n }\n }\n return ans;\n }\n}\n```\n\n**Python**\n```python\nclass Solution(object):\n def romanToInt(self, s):\n values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}\n ans, n = 0, len(s)\n for i in range(n):\n if i+1 < n and values[s[i]] < values[s[i+1]]:\n # If current is a small value and next is a bigger value -> It\'s a combine number\n ans -= values[s[i]]\n else:\n ans += values[s[i]]\n return ans\n```
24
4
[]
1
roman-to-integer
✅Beats 100% | Explained Step by Step | List Most Common String Interview Problems✅
beats-100-explained-step-by-step-list-mo-zqd8
Aproach 1: pattern matching + calc_scale\npython3 []\nclass Solution:\n @staticmethod\n def calc_scale(c: str, a1: str, a2: str) -> int:\n return -
Piotr_Maminski
NORMAL
2024-11-07T23:13:12.727030+00:00
2024-11-08T14:12:07.634556+00:00
7,919
false
# Aproach 1: pattern matching + calc_scale\n```python3 []\nclass Solution:\n @staticmethod\n def calc_scale(c: str, a1: str, a2: str) -> int:\n return -1 if c == a1 or c == a2 else 1\n \n def romanToInt(self, s: str) -> int:\n result = 0\n \n for n in range(len(s)):\n match s[n]:\n case \'M\':\n result += 1000\n case \'D\':\n result += 500\n case \'C\':\n result += 100 * self.calc_scale(s[n+1] if n+1 < len(s) else \'\', \'M\', \'D\')\n case \'L\':\n result += 50\n case \'X\':\n result += 10 * self.calc_scale(s[n+1] if n+1 < len(s) else \'\', \'C\', \'L\')\n case \'V\':\n result += 5\n case \'I\':\n result += 1 * self.calc_scale(s[n+1] if n+1 < len(s) else \'\', \'X\', \'V\')\n \n return result\n\n```\n```cpp []\nclass Solution {\n static int calcScale( char c , char a1 , char a2 ) {\n return (c == a1 || c == a2) ? -1 : +1;\n }\npublic:\n int romanToInt(string s) {\n int result = 0;\n\n for( size_t n = 0 ; n < s.size() ; ++n )\n {\n switch( s[n] )\n {\n case \'M\': result += 1000; break;\n case \'D\': result += 500; break;\n case \'C\': result += 100 * calcScale( s[n+1] , \'M\' , \'D\' ); break;\n case \'L\': result += 50; break;\n case \'X\': result += 10 * calcScale( s[n+1] , \'C\' , \'L\' ); break;\n case \'V\': result += 5; break;\n case \'I\': result += 1 * calcScale( s[n+1] , \'X\' , \'V\' ); break;\n }\n }\n return result;\n }\n};\n```\n```java []\nclass Solution {\n private static int calcScale(char c, char a1, char a2) {\n return (c == a1 || c == a2) ? -1 : 1;\n }\n \n public int romanToInt(String s) {\n int result = 0;\n \n for (int n = 0; n < s.length(); n++) {\n char nextChar = (n + 1 < s.length()) ? s.charAt(n + 1) : \'\\0\';\n \n switch (s.charAt(n)) {\n case \'M\': result += 1000; break;\n case \'D\': result += 500; break;\n case \'C\': result += 100 * calcScale(nextChar, \'M\', \'D\'); break;\n case \'L\': result += 50; break;\n case \'X\': result += 10 * calcScale(nextChar, \'C\', \'L\'); break;\n case \'V\': result += 5; break;\n case \'I\': result += 1 * calcScale(nextChar, \'X\', \'V\'); break;\n }\n }\n return result;\n }\n}\n\n```\n```csharp []\npublic class Solution {\n private static int CalcScale(char c, char a1, char a2) {\n return (c == a1 || c == a2) ? -1 : 1;\n }\n \n public int RomanToInt(string s) {\n int result = 0;\n \n for (int n = 0; n < s.Length; n++) {\n char nextChar = (n + 1 < s.Length) ? s[n + 1] : \'\\0\';\n \n switch (s[n]) {\n case \'M\': result += 1000; break;\n case \'D\': result += 500; break;\n case \'C\': result += 100 * CalcScale(nextChar, \'M\', \'D\'); break;\n case \'L\': result += 50; break;\n case \'X\': result += 10 * CalcScale(nextChar, \'C\', \'L\'); break;\n case \'V\': result += 5; break;\n case \'I\': result += 1 * CalcScale(nextChar, \'X\', \'V\'); break;\n }\n }\n return result;\n }\n}\n\n```\n```golang []\nfunc calcScale(c byte, a1 byte, a2 byte) int {\n if c == a1 || c == a2 {\n return -1\n }\n return 1\n}\n\nfunc romanToInt(s string) int {\n result := 0\n \n for n := 0; n < len(s); n++ {\n var nextChar byte\n if n+1 < len(s) {\n nextChar = s[n+1]\n }\n \n switch s[n] {\n case \'M\':\n result += 1000\n case \'D\':\n result += 500\n case \'C\':\n result += 100 * calcScale(nextChar, \'M\', \'D\')\n case \'L\':\n result += 50\n case \'X\':\n result += 10 * calcScale(nextChar, \'C\', \'L\')\n case \'V\':\n result += 5\n case \'I\':\n result += 1 * calcScale(nextChar, \'X\', \'V\')\n }\n }\n return result\n}\n\n```\n```swift []\nclass Solution {\n static func calcScale(_ c: Character?, _ a1: Character, _ a2: Character) -> Int {\n guard let c = c else { return 1 }\n return (c == a1 || c == a2) ? -1 : 1\n }\n \n func romanToInt(_ s: String) -> Int {\n var result = 0\n let chars = Array(s)\n \n for n in 0..<chars.count {\n let nextChar = n + 1 < chars.count ? chars[n + 1] : nil\n \n switch chars[n] {\n case "M": result += 1000\n case "D": result += 500\n case "C": result += 100 * Solution.calcScale(nextChar, "M", "D")\n case "L": result += 50\n case "X": result += 10 * Solution.calcScale(nextChar, "C", "L")\n case "V": result += 5\n case "I": result += 1 * Solution.calcScale(nextChar, "X", "V")\n default: break\n }\n }\n return result\n }\n}\n\n```\n```javascript [JS]\n// JavaScript\n\nvar romanToInt = function(s) {\n const calcScale = (c, a1, a2) => {\n return (c === a1 || c === a2) ? -1 : 1;\n };\n \n let result = 0;\n \n for (let n = 0; n < s.length; n++) {\n const nextChar = s[n + 1] || \'\';\n \n switch (s[n]) {\n case \'M\': result += 1000; break;\n case \'D\': result += 500; break;\n case \'C\': result += 100 * calcScale(nextChar, \'M\', \'D\'); break;\n case \'L\': result += 50; break;\n case \'X\': result += 10 * calcScale(nextChar, \'C\', \'L\'); break;\n case \'V\': result += 5; break;\n case \'I\': result += 1 * calcScale(nextChar, \'X\', \'V\'); break;\n }\n }\n \n return result;\n};\n```\n```typescript [TS]\n// TypeScript\n\nfunction romanToInt(s: string): number {\n const calcScale = (c: string, a1: string, a2: string): number => {\n return (c === a1 || c === a2) ? -1 : 1;\n };\n \n let result: number = 0;\n \n for (let n: number = 0; n < s.length; n++) {\n const nextChar: string = s[n + 1] || \'\';\n \n switch (s[n]) {\n case \'M\': result += 1000; break;\n case \'D\': result += 500; break;\n case \'C\': result += 100 * calcScale(nextChar, \'M\', \'D\'); break;\n case \'L\': result += 50; break;\n case \'X\': result += 10 * calcScale(nextChar, \'C\', \'L\'); break;\n case \'V\': result += 5; break;\n case \'I\': result += 1 * calcScale(nextChar, \'X\', \'V\'); break;\n }\n }\n \n return result;\n}\n```\n```rust []\nimpl Solution {\n fn calc_scale(c: Option<char>, a1: char, a2: char) -> i32 {\n match c {\n Some(ch) if ch == a1 || ch == a2 => -1,\n _ => 1,\n }\n }\n\n pub fn roman_to_int(s: String) -> i32 {\n let chars: Vec<char> = s.chars().collect();\n let mut result = 0;\n\n for n in 0..chars.len() {\n let next_char = chars.get(n + 1).copied();\n \n match chars[n] {\n \'M\' => result += 1000,\n \'D\' => result += 500,\n \'C\' => result += 100 * Self::calc_scale(next_char, \'M\', \'D\'),\n \'L\' => result += 50,\n \'X\' => result += 10 * Self::calc_scale(next_char, \'C\', \'L\'),\n \'V\' => result += 5,\n \'I\' => result += 1 * Self::calc_scale(next_char, \'X\', \'V\'),\n _ => (),\n }\n }\n result\n }\n}\n```\n```ruby []\ndef roman_to_int(s)\n def calc_scale(c, a1, a2)\n (c == a1 || c == a2) ? -1 : 1\n end\n \n result = 0\n chars = s.chars\n \n (0...chars.length).each do |n|\n next_char = chars[n + 1]\n \n case chars[n]\n when \'M\'\n result += 1000\n when \'D\'\n result += 500\n when \'C\'\n result += 100 * calc_scale(next_char, \'M\', \'D\')\n when \'L\'\n result += 50\n when \'X\'\n result += 10 * calc_scale(next_char, \'C\', \'L\')\n when \'V\'\n result += 5\n when \'I\'\n result += 1 * calc_scale(next_char, \'X\', \'V\')\n end\n end\n \n result\nend\n```\n\n# Aproach 2: dictionary (better only in python,swift)\n\n```python3 []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n \n roman = {"I": 1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}\n \n n = len(s)\n result = roman[s[n-1]]\n \n for i in range(n-2, -1, -1):\n \n if roman[s[i]] < roman[s[i+1]]:\n result = result - roman[s[i]]\n else:\n result = result + roman[s[i]]\n \n return result\n```\n```cpp []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> roman = {\n {\'I\', 1}, {\'V\', 5}, {\'X\', 10},\n {\'L\', 50}, {\'C\', 100}, {\'D\', 500}, {\'M\', 1000}\n };\n \n int n = s.length();\n int result = roman[s[n-1]];\n \n for(int i = n-2; i >= 0; i--) {\n if(roman[s[i]] < roman[s[i+1]]) {\n result -= roman[s[i]];\n } else {\n result += roman[s[i]];\n }\n }\n \n return result;\n }\n};\n\n```\n```java []\nclass Solution {\n public int romanToInt(String s) {\n Map<Character, Integer> roman = new HashMap<>();\n roman.put(\'I\', 1);\n roman.put(\'V\', 5);\n roman.put(\'X\', 10);\n roman.put(\'L\', 50);\n roman.put(\'C\', 100);\n roman.put(\'D\', 500);\n roman.put(\'M\', 1000);\n \n int n = s.length();\n int result = roman.get(s.charAt(n-1));\n \n for(int i = n-2; i >= 0; i--) {\n if(roman.get(s.charAt(i)) < roman.get(s.charAt(i+1))) {\n result -= roman.get(s.charAt(i));\n } else {\n result += roman.get(s.charAt(i));\n }\n }\n \n return result;\n }\n}\n\n```\n```csharp []\npublic class Solution {\n public int RomanToInt(string s) {\n Dictionary<char, int> roman = new Dictionary<char, int> {\n {\'I\', 1}, {\'V\', 5}, {\'X\', 10},\n {\'L\', 50}, {\'C\', 100}, {\'D\', 500}, {\'M\', 1000}\n };\n \n int n = s.Length;\n int result = roman[s[n-1]];\n \n for(int i = n-2; i >= 0; i--) {\n if(roman[s[i]] < roman[s[i+1]]) {\n result -= roman[s[i]];\n } else {\n result += roman[s[i]];\n }\n }\n \n return result;\n }\n}\n\n```\n```golang []\nfunc romanToInt(s string) int {\n roman := map[byte]int{\n \'I\': 1, \'V\': 5, \'X\': 10,\n \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000,\n }\n \n n := len(s)\n result := roman[s[n-1]]\n \n for i := n-2; i >= 0; i-- {\n if roman[s[i]] < roman[s[i+1]] {\n result -= roman[s[i]]\n } else {\n result += roman[s[i]]\n }\n }\n \n return result\n}\n\n```\n```swift []\nclass Solution {\n func romanToInt(_ s: String) -> Int {\n let roman: [Character: Int] = [\n "I": 1, "V": 5, "X": 10,\n "L": 50, "C": 100, "D": 500, "M": 1000\n ]\n \n let chars = Array(s)\n let n = chars.count\n var result = roman[chars[n-1]]!\n \n for i in stride(from: n-2, through: 0, by: -1) {\n if roman[chars[i]]! < roman[chars[i+1]]! {\n result -= roman[chars[i]]!\n } else {\n result += roman[chars[i]]!\n }\n }\n \n return result\n }\n}\n```\n```javascript [JS]\n// JavaScript\n\nvar romanToInt = function(s) {\n const roman = {\n \'I\': 1, \'V\': 5, \'X\': 10,\n \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000\n };\n \n let n = s.length;\n let result = roman[s[n-1]];\n \n for(let i = n-2; i >= 0; i--) {\n if(roman[s[i]] < roman[s[i+1]]) {\n result -= roman[s[i]];\n } else {\n result += roman[s[i]];\n }\n }\n \n return result;\n};\n```\n```typescript [TS]\n// TypeScript\n\nfunction romanToInt(s: string): number {\n const roman: { [key: string]: number } = {\n \'I\': 1, \'V\': 5, \'X\': 10,\n \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000\n };\n \n const n: number = s.length;\n let result: number = roman[s[n-1]];\n \n for(let i = n-2; i >= 0; i--) {\n if(roman[s[i]] < roman[s[i+1]]) {\n result -= roman[s[i]];\n } else {\n result += roman[s[i]];\n }\n }\n \n return result;\n}\n```\n```rust []\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn roman_to_int(s: String) -> i32 {\n let mut roman = HashMap::new();\n roman.insert(\'I\', 1);\n roman.insert(\'V\', 5);\n roman.insert(\'X\', 10);\n roman.insert(\'L\', 50);\n roman.insert(\'C\', 100);\n roman.insert(\'D\', 500);\n roman.insert(\'M\', 1000);\n \n let chars: Vec<char> = s.chars().collect();\n let n = chars.len();\n let mut result = roman[&chars[n-1]];\n \n for i in (0..n-1).rev() {\n if roman[&chars[i]] < roman[&chars[i+1]] {\n result -= roman[&chars[i]];\n } else {\n result += roman[&chars[i]];\n }\n }\n \n result\n }\n}\n\n```\n```ruby []\ndef roman_to_int(s)\n roman = {\n \'I\' => 1, \'V\' => 5, \'X\' => 10,\n \'L\' => 50, \'C\' => 100, \'D\' => 500, \'M\' => 1000\n }\n \n n = s.length\n result = roman[s[n-1]]\n \n (n-2).downto(0) do |i|\n if roman[s[i]] < roman[s[i+1]]\n result -= roman[s[i]]\n else\n result += roman[s[i]]\n end\n end\n \n result\nend\n```\n\n### Complexity\n- Time complexity: O(n)\n\n\n- Space complexity: O(1)\n\n\n# Explanation\n\n \n\n---\n\n# Intuition\n\nThat Solution handles Roman numeral conversion by looking at pairs of characters to determine if we should add or subtract values.\n\n## Aproach 1\n\n1. The calcScale helper function:\n- It looks at the current character and the next character\n- If the next character is one of two specific larger values, it returns -1 (for subtraction)\n- Otherwise it returns +1 (for addition)\n2. The main conversion logic:\n- Goes through each character in the Roman numeral string\n- For each character (M, D, C, L, X, V, I), it:\n - M = 1000\n - D = 500\n - C = 100 (multiplied by +1 or -1 depending on if next letter is M or D)\n - L = 50\n - X = 10 (multiplied by +1 or -1 depending on if next letter is C or L)\n - V = 5\n - I = 1 (multiplied by +1 or -1 depending on if next letter is X or V)\n\n\n## Example\n\n- For "IV" (4): When it sees \'I\', it checks the next letter \'V\' and multiplies 1 by -1, then adds 5 = 4\n- For "VI" (6): When it sees \'V\', it adds 5, then for \'I\' it adds 1 = 6\n\n\n---\nI had variations this problem **twice** at interviews\nVariations: \nEasy: Roman to Integer (that problem)\nMedium: [12. Integer to Roman](https://leetcode.com/problems/integer-to-roman/solutions/6023402/solutions) (most common)\nHard: [273. Integer to English Words](https://leetcode.com/problems/integer-to-english-words/description/)\n\n![string.png](https://assets.leetcode.com/users/images/bf2b1f33-9164-4748-b5f4-802500c7561a_1731073630.9087918.png)\n\n\n# Most common String Interview Problems\nList based on my research (interviews, reddit, github) Probably not 100% accurate but very close to my recruitments. Leetcode Premium is probably more accurate [I don\'t have]\n\n\n\n**Easy:** [[20. Valid Parentheses]](https://leetcode.com/problems/valid-parentheses/solutions/6013115/solution) [[28. Find the Index of the First Occurrence in a String]](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string) [[13. Roman to Integer]](https://leetcode.com/problems/roman-to-integer/solutions/6021029/beats-100-explained-step-by-step-list-most-common-string-interview-problems/) [[125. Valid Palindrome]](https://leetcode.com/problems/valid-palindrome) [[680. Valid Palindrome II]](https://leetcode.com/problems/valid-palindrome-ii) [[67. Add Binary]](https://leetcode.com/problems/add-binary)\n\n\n**Medium/Hard:** [[8. String to Integer (atoi)]](https://leetcode.com/problems/string-to-integer-atoi/solutions/6013112/solution/) [[3. Longest Substring Without Repeating Characters]](https://leetcode.com/problems/longest-substring-without-repeating-characters/solutions/6013106/solutions/) [[5. Longest Palindromic Substring]](https://leetcode.com/problems/longest-palindromic-substring/solutions/6013111/solution/) [[937. Reorder Data in Log Files]](https://leetcode.com/problems/reorder-data-in-log-files) [[68. Text Justification]](https://leetcode.com/problems/text-justification) [[32. Longest Valid Parentheses]](https://leetcode.com/problems/longest-valid-parentheses) [[12. Integer to Roman]](https://leetcode.com/problems/integer-to-roman/solutions/6023402/solutions) [[22. Generate Parentheses]](https://leetcode.com/problems/generate-parentheses) [[65. Valid Number]](https://leetcode.com/problems/valid-number) [[49. Group Anagrams]](https://leetcode.com/problems/group-anagrams)\n\n\n\n\n\n\n\n#### [Interview Questions and Answers Repository](https://github.com/RooTinfinite/Interview-questions-and-answers)\n\n\n\n\n\n![image.png](https://assets.leetcode.com/users/images/9dc1b265-b175-4bf4-bc6c-4b188cb79220_1728176037.4402142.png)\n\n\n\n\n\n\n
23
0
['Swift', 'C', 'C++', 'Java', 'TypeScript', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#']
5
roman-to-integer
✅ Beats 100% 🔥Iterative Convertion Approach || Java || Rust || C++ || Python
beats-100-iterative-convertion-approach-s36u2
Intuition\nThe solution aims to convert a Roman numeral representation into its corresponding integer value. It utilizes the properties of Roman numerals, such
farhanzamanarnob
NORMAL
2024-03-18T09:09:33.988612+00:00
2024-03-18T09:09:33.988631+00:00
2,882
false
# Intuition\nThe solution aims to convert a Roman numeral representation into its corresponding integer value. It utilizes the properties of Roman numerals, such as the rules of addition. \n\n![image.png](https://assets.leetcode.com/users/images/fd366999-fb3b-450f-90c4-339e8f8e4cf3_1710752078.5683062.png)\n\n# Approach\n1. Iterate through each character of the Roman numeral string.\n2. Use a switch statement to handle each character case (\'I\', \'V\', \'X\', \'L\', \'C\', \'D\', \'M\').\n3. Based on the current character and the previous character, determine which value should be added.\n4. Update the total value accordingly and keep track of the previous character for future comparisons.\n5. Finally, return the calculated integer value.\n\n# Explanation of Logic\n- The `prev` variable is used to keep track of the previous character\'s value, initialized to `0`.\n- The loop iterates over each character of the input Roman numeral string.\n- For each character\n - If the character is `I`, add 1 to the total value and update `prev` to 1.\n - If the character is `V`\n - If the previous character was `I` `(value = 1)`, it means we encountered \'IV\', so add 3 to the total value `(1 + 3 = 4)`.\n - If the previous character was not \'I\', add 5 to the total value and update `prev` to `5`.\n - Similar logic is applied for `X`, `L`, `C`, `D`, and `M` cases, considering their respective values and the previous character.\n- After processing all characters, the total value is returned.\n\n# Complexity Analysis\n- Time Complexity The time complexity is `O(n)`, where n is the length of the input Roman numeral string. The algorithm iterates through each character once.\n- Space Complexity The space complexity is `O(1)` as the space usage remains constant irrespective of the input size.\n\n# Code\nPlease **Upvote** if you find it useful \uD83D\uDC4D\u2B06\uFE0F\n```java []\nclass Solution {\n public int romanToInt(String s) {\n int value=0,prev=0;\n for(char ch: s.toCharArray())\n {\n switch(ch)\n {\n case \'I\': value+=1;prev=1;break;\n case \'V\': value+=(prev==1)?3:5;prev=5;break;\n case \'X\': value+=(prev==1)?8:10;prev=10;break;\n case \'L\': value+=(prev==10)?30:50;prev=50;break;\n case \'C\': value+=(prev==10)?80:100;prev=100;break;\n case \'D\': value+=(prev==100)?300:500;prev=500;break;\n case \'M\': value+=(prev==100)?800:1000;prev=1000;break;\n }\n }\n return value;\n }\n}\n```\n```rust []\nimpl Solution {\n pub fn roman_to_int(s: String) -> i32 {\n let mut value = 0;\n let mut prev = 0;\n for ch in s.chars() {\n match ch {\n \'I\' => { value += 1; prev = 1; },\n \'V\' => { value += if prev == 1 { 3 } else { 5 }; prev = 5; },\n \'X\' => { value += if prev == 1 { 8 } else { 10 }; prev = 10; },\n \'L\' => { value += if prev == 10 { 30 } else { 50 }; prev = 50; },\n \'C\' => { value += if prev == 10 { 80 } else { 100 }; prev = 100; },\n \'D\' => { value += if prev == 100 { 300 } else { 500 }; prev = 500; },\n \'M\' => { value += if prev == 100 { 800 } else { 1000 }; prev = 1000; },\n _ => {}\n }\n }\n value\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int romanToInt(string s) {\n int value = 0, prev = 0;\n for (char ch : s) {\n switch (ch) {\n case \'I\': value += 1; prev = 1; break;\n case \'V\': value += (prev == 1) ? 3 : 5; prev = 5; break;\n case \'X\': value += (prev == 1) ? 8 : 10; prev = 10; break;\n case \'L\': value += (prev == 10) ? 30 : 50; prev = 50; break;\n case \'C\': value += (prev == 10) ? 80 : 100; prev = 100; break;\n case \'D\': value += (prev == 100) ? 300 : 500; prev = 500; break;\n case \'M\': value += (prev == 100) ? 800 : 1000; prev = 1000; break;\n }\n }\n return value;\n }\n};\n```\n```python []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n value = 0\n prev = 0\n for ch in s:\n if ch == \'I\':\n value += 1\n prev = 1\n elif ch == \'V\':\n value += 3 if prev == 1 else 5\n prev = 5\n elif ch == \'X\':\n value += 8 if prev == 1 else 10\n prev = 10\n elif ch == \'L\':\n value += 30 if prev == 10 else 50\n prev = 50\n elif ch == \'C\':\n value += 80 if prev == 10 else 100\n prev = 100\n elif ch == \'D\':\n value += 300 if prev == 100 else 500\n prev = 500\n elif ch == \'M\':\n value += 800 if prev == 100 else 1000\n prev = 1000\n return value\n```\n
23
0
['Java']
5
roman-to-integer
✅Short || C++ || Java || PYTHON || Explained Solution✔️ || Beginner Friendly ||🔥 🔥 BY MR CODER
short-c-java-python-explained-solution-b-upji
Please UPVOTE if you LIKE!!\nWatch this video \uD83E\uDC83 for the better explanation of the code.\n\nhttps://www.youtube.com/watch?v=Nc35iWWqT78\n\n\nAlso you
mrcoderrm
NORMAL
2022-08-15T10:16:04.843977+00:00
2022-08-15T10:31:48.736253+00:00
3,835
false
**Please UPVOTE if you LIKE!!**\n**Watch this video \uD83E\uDC83 for the better explanation of the code.**\n\nhttps://www.youtube.com/watch?v=Nc35iWWqT78\n\n\n**Also you can SUBSCRIBE \uD83E\uDC81 \uD83E\uDC81 \uD83E\uDC81 this channel for the daily leetcode challange solution.**\n**C++**\n```\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> um;\n um[\'I\']= 1;\n um[\'V\']= 5;\n um[\'X\']= 10;\n um[\'L\']=50;\n um[\'C\']= 100;\n um[\'D\']= 500;\n um[\'M\']= 1000;\n int ans=0;\n for(int i=s.size()-1; i>=0; i--){\n if(i!=0 && um[s[i-1]]<um[s[i]] ){\n ans= ans+ um[s[i]]-um[s[i-1]]; \n i--;\n continue;\n }\n ans=ans+ um[s[i]];\n }\n return ans;\n }\n};\n \n```\n**JAVA**(Copied)\n```\npublic int romanToInt(String s) {\n Map<Character, Integer> alphabet = initAlphabet();\n int result = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n if (alphabet.get(s.charAt(i)) < alphabet.get(s.charAt(i + 1)))\n result = result - alphabet.get(s.charAt(i));\n else \n result = result + alphabet.get(s.charAt(i));\n }\n return result + alphabet.get(s.charAt(s.length() - 1));\n }\n\n private Map<Character, Integer> initAlphabet() {\n return Map.of(\'I\', 1, \'V\', 5, \'X\', 10, \'L\', 50, \'C\', 100, \'D\', 500, \'M\', 1000);\n }\n```\n**PYTHON**((Copied)\n```\nclass Solution:\n\t\n\n\tROMAN_TO_INTEGER = {\n\t\t\'I\': 1,\n\t\t\'IV\': 4,\n\t\t\'V\': 5,\n\t\t\'IX\': 9,\n\t\t\'X\': 10,\n\t\t\'XL\': 40,\n\t\t\'L\': 50,\n\t\t\'XC\': 90,\n\t\t\'C\': 100,\n\t\t\'CD\': 400,\n\t\t\'D\': 500,\n\t\t\'CM\': 900,\n\t\t\'M\': 1000,\n\t}\n\n\tdef romanToInt(self, s: str) -> int:\n\t\tconverted = 0\n\n\t\tfor roman, integer in self.ROMAN_TO_INTEGER.items():\n\t\t\twhile s.endswith(roman):\n\t\t\t\ts = s.removesuffix(roman)\n\t\t\t\tconverted += integer\n\n\t\treturn converted\n```\n**Please do UPVOTE to motivate me to solve more daily challenges like this !!**
23
0
['C', 'Python', 'Java']
1
roman-to-integer
php (using str_tr)
php-using-str_tr-by-thepowerofcreation21-2d0p
so i did this and it worked :)\n\n\nclass Solution {\n\n /**\n * @param String $s\n * @return Integer\n */\n function romanToInt($s) {\n
thePowerOfCreation21
NORMAL
2022-06-26T14:56:32.532842+00:00
2022-06-26T14:56:32.532885+00:00
1,445
false
so i did this and it worked :)\n\n```\nclass Solution {\n\n /**\n * @param String $s\n * @return Integer\n */\n function romanToInt($s) {\n $s = strtr(\n $s,\n [\n \'M\' => \'1000,\',\n \'CM\' => \'900,\',\n \'D\' => \'500,\',\n \'CD\' => \'400,\',\n \'C\' => \'100,\',\n \'XC\' => \'90,\',\n \'L\' => \'50,\',\n \'XL\' => \'40,\',\n \'X\' => \'10,\',\n \'IX\' => \'9,\',\n \'V\' => \'5,\',\n \'IV\' => \'4\',\n \'I\' => \'1,\'\n ]\n );\n return array_sum(explode(\',\', $s));\n }\n}\n```
23
0
['PHP']
4
roman-to-integer
Easy to understand w/ explanation | 12 lines | Faster than 98%
easy-to-understand-w-explanation-12-line-3zbn
Approach:\n1. Scan the given roman numeral string from left to right character by character and add the corresponding integer value to ans.\n2. Record previous
v21
NORMAL
2021-03-28T11:44:48.491316+00:00
2021-05-13T11:28:50.501106+00:00
1,589
false
**Approach:**\n1. Scan the given roman numeral string from left to right character by character and add the corresponding integer value to `ans`.\n2. Record previous added value in `prev` so that it can be compared with another value in the next iteration. If `curr` value is greater than `prev`, it means we have numerals like \'IV\', \'IX\', \'XL\', \'CD\', \'CM\' etc. In that case, subtract previously added value from `ans` and add the difference between `curr` and `prev`.\n \n E.g. If we had \'XL\' then we\'d subtract \'X\' i.e. 10 from `ans` and add 40 (\'L\' i.e. 50 - \'X\' i.e. 10 = 40)\n\n```\ndef romanToInt(self, s: str) -> int:\n values = {\'I\': 1, \'V\': 5, \'X\': 10, \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000}\n prev, ans = -1, 0\n for c in s:\n curr = values[c]\n if prev != -1 and curr > prev:\n ans -= prev\n ans += curr - prev\n else:\n ans += curr\n prev = curr\n return ans\n```\n\n**P.S. If you found this approach helpful, consider upvoting it. :)**
23
0
['Python', 'Python3']
3
roman-to-integer
Easiest Map Solution C++
easiest-map-solution-c-by-schwjustin-wxor
\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map <char, int> dict {\n {\'I\', 1},\n {\'V\', 5},\n
schwjustin
NORMAL
2020-06-25T15:03:36.846941+00:00
2020-06-25T15:03:36.846990+00:00
2,999
false
```\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map <char, int> dict {\n {\'I\', 1},\n {\'V\', 5},\n {\'X\', 10},\n {\'L\', 50},\n {\'C\', 100},\n {\'D\', 500},\n {\'M\', 1000},\n };\n \n int result = 0;\n for (int i = 0; i < s.size(); i++) {\n if (dict[s[i]] < dict[s[i+1]]) result -= dict[s[i]];\n else { result += dict[s[i]]; }\n }\n \n return result;\n }\n};\n```
23
0
['C', 'C++']
4
roman-to-integer
C++: Fast & Easy to understand: 4ms (98%) 8.3MB (90%)
c-fast-easy-to-understand-4ms-98-83mb-90-jmb3
\nclass Solution {\npublic:\n int romanToInt(string s) {\n int ret = 0; // to store the return value\n int temp = 0; // to store t
kellyckj
NORMAL
2019-08-26T07:40:01.247117+00:00
2019-08-27T03:22:04.141640+00:00
4,099
false
```\nclass Solution {\npublic:\n int romanToInt(string s) {\n int ret = 0; // to store the return value\n int temp = 0; // to store the previous value\n \n for (size_t i = 0; i < s.size(); i++) {\n char curr = s[i];\n int pos = 0; // to store the current value\n \n switch(curr) {\n case \'I\': pos = 1; break;\n case \'V\': pos = 5; break;\n case \'X\': pos = 10; break;\n case \'L\': pos = 50; break;\n case \'C\': pos = 100; break;\n case \'D\': pos = 500; break;\n case \'M\': pos = 1000; break;\n default: return 0;\n }\n \n ret += pos;\n if (temp < pos)\n ret -= temp*2; // ex: IV, ret = 1 + 5 - 1*2 = 4\n temp = pos;\n }\n \n return ret;\n }\n};\n```
23
3
['C', 'C++']
1
roman-to-integer
C simple and easy solution..
c-simple-and-easy-solution-by-kaviyapriy-f7z9
\n\n# Code\n\n\nint DecimalNumericalPlace(char roman_np_value)\n {\n switch(roman_np_value)\n {\n case \'M\':\n return 10
kaviyapriya_03
NORMAL
2023-03-01T10:22:25.716415+00:00
2023-03-01T10:22:25.716460+00:00
8,381
false
\n\n# Code\n```\n\nint DecimalNumericalPlace(char roman_np_value)\n {\n switch(roman_np_value)\n {\n case \'M\':\n return 1000;\n break;\n\n case \'D\':\n return 500;\n break;\n\n case \'C\':\n return 100;\n break;\n\n case \'L\':\n return 50;\n break;\n\n case \'X\':\n return 10;\n break;\n\n case \'V\':\n return 5;\n break;\n\n case \'I\':\n return 1;\n break;\n default :\n return -1;\n }\n }\nint romanToInt(char * s)\n{\n int len=strlen(s);\n int sum=0;\n for(int i=0;s[i]!=\'\\0\';i++){\n if(DecimalNumericalPlace(s[i]) < DecimalNumericalPlace(s[i+1])){\n sum = sum-DecimalNumericalPlace(s[i]);\n }\n else{\n sum+=DecimalNumericalPlace(s[i]);\n }\n }\n return sum;\n}\n```
22
0
['C']
4
roman-to-integer
[PYTHON 3] BEATS 99.13% | EASY TO UNDERSTAND
python-3-beats-9913-easy-to-understand-b-9n4c
Runtime: 44 ms, faster than 99.13% of Python3 online submissions for Roman to Integer.\nMemory Usage: 13.9 MB, less than 76.17% of Python3 online submissions fo
omkarxpatel
NORMAL
2022-07-12T15:31:39.381550+00:00
2022-10-04T05:21:31.955047+00:00
2,981
false
Runtime: **44 ms, faster than 99.13%** of Python3 online submissions for Roman to Integer.\nMemory Usage: **13.9 MB, less than 76.17%** of Python3 online submissions for Roman to Integer.\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n a, r = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, "IV": -2, "IX": -2, "XL": -20, "XC": -20, "CD": -200, "CM": -200}, 0\n for d, e in a.items():\n r += s.count(d) * e\n return r\n\n```\n
22
0
['Python', 'Python3']
9
roman-to-integer
✔️ 100% Fastest Swift Solution
100-fastest-swift-solution-by-sergeylesc-kswk
\nclass Solution {\n func romanToInt(_ s: String) -> Int {\n\t\tvar num: Int = 0\n\t\tvar prev: Character = " "\n\t\tlet map: [Character : Int] = [\n\t\t\t"I
sergeyleschev
NORMAL
2022-03-31T05:39:35.389723+00:00
2022-03-31T05:39:35.389746+00:00
4,193
false
```\nclass Solution {\n func romanToInt(_ s: String) -> Int {\n\t\tvar num: Int = 0\n\t\tvar prev: Character = " "\n\t\tlet map: [Character : Int] = [\n\t\t\t"I": 1,\n\t\t\t"V": 5,\n\t\t\t"X": 10,\n\t\t\t"L": 50,\n\t\t\t"C": 100,\n\t\t\t"D": 500,\n\t\t\t"M": 1000,\n\t\t]\n\t\t \n\t\tfor c in s {\n\t\t\tif prev == "I" && (c == "V" || c == "X") {\n\t\t\t\tnum += (map[c]! - 2 * map[prev]!)\n\t\t\t} else if prev == "X" && (c == "L" || c == "C") {\n\t\t\t\tnum += (map[c]! - 2 * map[prev]!) \n\t\t\t} else if prev == "C" && (c == "D" || c == "M") {\n\t\t\t\tnum += (map[c]! - 2 * map[prev]!)\n\t\t\t} else {\n\t\t\t\tnum += map[c]!\n\t\t\t}\n\t\t\tprev = c\n\t\t}\n \n return num\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.
22
4
['Swift']
2
roman-to-integer
Kotlin simple
kotlin-simple-by-georgcantor-ktvz
\nfun romanToInt(s: String): Int {\n val map = mutableMapOf(\n \'I\' to 1, \'V\' to 5, \'X\' to 10, \'L\' to 50, \'C\' to 100, \'D\' to 500, \
GeorgCantor
NORMAL
2021-02-08T14:06:24.883589+00:00
2021-02-08T14:06:24.883620+00:00
2,892
false
```\nfun romanToInt(s: String): Int {\n val map = mutableMapOf(\n \'I\' to 1, \'V\' to 5, \'X\' to 10, \'L\' to 50, \'C\' to 100, \'D\' to 500, \'M\' to 1000\n )\n var number = 0\n var last = 1000\n s.forEach {\n val value = map[it] ?: 0\n if (value > last) number -= last * 2\n number += value\n last = value\n }\n\n return number\n }\n```
22
0
['Kotlin']
5
roman-to-integer
JavaScript simple decrementing while loop
javascript-simple-decrementing-while-loo-x6bk
\n/**\n * @param {string} s\n * @return {number}\n */\nvar romanToInt = function(s) {\n const map = {\n I: 1,\n V: 5,\n X: 10,\n
pdxandi
NORMAL
2018-08-19T16:45:52.962602+00:00
2018-10-18T21:47:22.214741+00:00
1,480
false
```\n/**\n * @param {string} s\n * @return {number}\n */\nvar romanToInt = function(s) {\n const map = {\n I: 1,\n V: 5,\n X: 10,\n L: 50,\n C: 100,\n D: 500,\n M: 1000\n };\n let i = s.length;\n let result = 0;\n \n while (i--) {\n const curr = map[s.charAt(i)];\n const prev = map[s.charAt(i - 1)];\n \n result += curr; \n \n if (prev < curr) {\n result -= prev; \n i -= 1;\n }\n }\n \n return result;\n};\n```
21
0
[]
2
roman-to-integer
[JAVA] 3-4 liner solution using switch case
java-3-4-liner-solution-using-switch-cas-kzha
\nclass Solution {\n public int romanToInt(String s) {\n int ans = 0, num = 0;\n for(int i = s.length() - 1; i >= 0; i --) {\n switch(s.char
Jugantar2020
NORMAL
2022-08-15T05:15:14.037678+00:00
2022-08-15T05:15:14.037723+00:00
1,669
false
```\nclass Solution {\n public int romanToInt(String s) {\n int ans = 0, num = 0;\n for(int i = s.length() - 1; i >= 0; i --) {\n switch(s.charAt(i)) {\n case \'I\' : num = 1; break;\n case \'V\' : num = 5; break;\n case \'X\' : num = 10; break;\n case \'L\' : num = 50; break;\n case \'C\' : num = 100; break;\n case \'D\' : num = 500; break;\n case \'M\' : num = 1000; break;\n }\n if(4 * num < ans) ans -= num;\n else ans += num;\n }\n return ans;\n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL
19
2
['Java']
3
roman-to-integer
Rust | "One-Liner" | With Comments
rust-one-liner-with-comments-by-wallicen-k2s8
EDIT 2022-08-15: Celebrating that this is the problem of the day by doing a more elegant and fully functional solution. As hinted below in the original solution
wallicent
NORMAL
2022-06-27T13:32:44.067734+00:00
2022-08-16T14:32:58.206111+00:00
2,163
false
EDIT 2022-08-15: Celebrating that this is the problem of the day by doing a more elegant and fully functional solution. As hinted below in the original solution, I use a state machine approach to avoid complicating things with having to look at pairs. My definition of a one-liner is that are no semicolons ending expressions in the solution. So I regard this as a one-liner, which always is its own reward. :)\n\n**Functional "One-Liner"**\n\n```\nimpl Solution {\n pub fn roman_to_int(s: String) -> i32 {\n s.as_bytes().iter().fold([0; 4], |[m, c, x, i], b| {\n match *b {\n b\'M\' => [m + 1000 - c, 0, x, i],\n b\'D\' => [m + 500 - c, 0, x, i],\n b\'C\' => [m, c + 100 - x, 0, i],\n b\'L\' => [m, c + 50 - x, 0, i],\n b\'X\' => [m, c, x + 10 - i, 0],\n b\'V\' => [m, c, x + 5 - i, 0],\n _ => [m, c, x, i + 1],\n }\n }).into_iter().sum::<i32>()\n }\n}\n```\n\n**Original Solution**\n\nQuite happy to note that I made a solution that is efficient, yet a bit different from the other ones posted. Instead of looking at pairs of characters in one way or another, I treat the accumulated "lower" digits as negative when I encounter a "higher" digit.\n\n```\nimpl Solution {\n pub fn roman_to_int(s: String) -> i32 {\n let (mut m, mut c, mut x, mut i) = (0, 0, 0, 0);\n for b in s.as_bytes() {\n match b {\n b\'M\' => { m += 1000 - c; c = 0; },\n b\'D\' => { m += 500 - c; c = 0; },\n b\'C\' => { c += 100 - x; x = 0; },\n b\'L\' => { c += 50 - x; x = 0; }\n b\'X\' => { x += 10 - i; i = 0; }\n b\'V\' => { x += 5 - i; i = 0; }\n _ => i += 1,\n }\n }\n m + c + x + i\n }\n}\n```
19
0
['Rust']
1
roman-to-integer
[Java/C++/Python]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022
javacpythonontimebeats-9997-memoryspeed-h0m3f
C++\n\nclass Solution {\npublic:\n int romanToInt(string S) {\n int ans = 0, num = 0;\n for (int i = S.size()-1; ~i; i--) {\n switch
darian-catalin-cucer
NORMAL
2022-04-24T20:40:28.998939+00:00
2022-04-24T20:40:28.998984+00:00
2,429
false
***C++***\n```\nclass Solution {\npublic:\n int romanToInt(string S) {\n int ans = 0, num = 0;\n for (int i = S.size()-1; ~i; i--) {\n switch(S[i]) {\n case \'I\': num = 1; break;\n case \'V\': num = 5; break;\n case \'X\': num = 10; break;\n case \'L\': num = 50; break;\n case \'C\': num = 100; break;\n case \'D\': num = 500; break;\n case \'M\': num = 1000; break;\n }\n if (4 * num < ans) ans -= num;\n else ans += num;\n }\n return ans; \n }\n};\n```\n\n***Java***\n```\nclass Solution {\n public int romanToInt(String S) {\n int ans = 0, num = 0;\n for (int i = S.length()-1; i >= 0; i--) {\n switch(S.charAt(i)) {\n case \'I\': num = 1; break;\n case \'V\': num = 5; break;\n case \'X\': num = 10; break;\n case \'L\': num = 50; break;\n case \'C\': num = 100; break;\n case \'D\': num = 500; break;\n case \'M\': num = 1000; break;\n }\n if (4 * num < ans) ans -= num;\n else ans += num;\n }\n return ans;\n }\n}\n```\n\n***Python***\n```\nroman = {\'I\':1,\'V\':5,\'X\':10,\'L\':50,\'C\':100,\'D\':500,\'M\':1000}\n\nclass Solution:\n def romanToInt(self, S: str) -> int:\n ans = 0\n for i in range(len(S)-1,-1,-1):\n num = roman[S[i]]\n if 4 * num < ans: ans -= num\n else: ans += num\n return ans\n```\n***Consider upvote if useful!***
19
0
['C', 'Combinatorics', 'Python', 'C++', 'Java']
4
roman-to-integer
Python3 - The way the Romans do it
python3-the-way-the-romans-do-it-by-ichb-e902
Here is my solution. Beat 99.43% of submissions.\n\n1. Iterate through the string from right to left. \n2. Whenever the current letter is larger than the previo
ichbinik
NORMAL
2017-11-28T05:08:50.733000+00:00
2017-11-28T05:08:50.733000+00:00
3,421
false
Here is my solution. Beat 99.43% of submissions.\n\n1. Iterate through the string from right to left. \n2. Whenever the current letter is larger than the previous letter, add it to the total. \n3. Whenever the current letter is smaller than the previous, subtract it from the total.\n\n```\nclass Solution:\n\n charToNum = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n }\n\n def romanToInt(self, s):\n """\n :type s: str\n :rtype: int\n """\n prev = 0\n total = 0\n for numeral in s[::-1]:\n cur = self.charToNum[numeral]\n total += cur if cur >= prev else -1*cur\n prev = cur\n return total\n```
19
0
[]
3
roman-to-integer
Straightforward Java Solution Using Recursion (139ms)
straightforward-java-solution-using-recu-yhft
\nclass Solution\n{\n public int romanToInt(String s)\n {\n if(s.length() == 0) return 0;\n \n if(s.length() > 1)\n {\n
aeriagloris
NORMAL
2017-12-22T20:47:32.234000+00:00
2017-12-22T20:47:32.234000+00:00
7,558
false
```\nclass Solution\n{\n public int romanToInt(String s)\n {\n if(s.length() == 0) return 0;\n \n if(s.length() > 1)\n {\n if(s.substring(0,2).equals("CM")) return 900 + romanToInt(s.substring(2));\n if(s.substring(0,2).equals("CD")) return 400 + romanToInt(s.substring(2));\n if(s.substring(0,2).equals("XC")) return 90 + romanToInt(s.substring(2));\n if(s.substring(0,2).equals("XL")) return 40 + romanToInt(s.substring(2));\n if(s.substring(0,2).equals("IX")) return 9 + romanToInt(s.substring(2));\n if(s.substring(0,2).equals("IV")) return 4 + romanToInt(s.substring(2));\n }\n \n if(s.charAt(0) == 'M') return 1000 + romanToInt(s.substring(1));\n if(s.charAt(0) == 'D') return 500 + romanToInt(s.substring(1));\n if(s.charAt(0) == 'C') return 100 + romanToInt(s.substring(1));\n if(s.charAt(0) == 'L') return 50 + romanToInt(s.substring(1));\n if(s.charAt(0) == 'X') return 10 + romanToInt(s.substring(1));\n if(s.charAt(0) == 'V') return 5 + romanToInt(s.substring(1));\n if(s.charAt(0) == 'I') return 1 + romanToInt(s.substring(1));\n \n return 0;\n }\n}\n```
19
0
[]
0
roman-to-integer
[VIDEO] Visualization of Two Different Approaches
video-visualization-of-two-different-app-jmnf
https://www.youtube.com/watch?v=tsmrUi5M1JU\n\nMethod 1:\nThis solution takes the approach incorporating the general logic of roman numerals into the algorithm.
AlgoEngine
NORMAL
2024-09-06T23:30:50.963594+00:00
2024-09-06T23:30:50.963624+00:00
1,439
false
https://www.youtube.com/watch?v=tsmrUi5M1JU\n\n<b>Method 1:</b>\nThis solution takes the approach incorporating the general logic of roman numerals into the algorithm. We first create a dictionary that maps each roman numeral to the corresponding integer. We also create a total variable set to 0.\n\nWe then loop over each numeral and check if the one <i>after</i> it is bigger or smaller. If it\'s bigger, we can just add it to our total. If it\'s smaller, that means we have to <i>subtract</i> it from our total instead.\n\nThe loop stops at the second to last numeral and returns the total + the last numeral (since the last numeral always has to be added)\n\n```\nclass Solution(object):\n def romanToInt(self, s):\n roman = {\n "I": 1,\n "V": 5,\n "X": 10,\n "L": 50,\n "C": 100,\n "D": 500,\n "M": 1000\n }\n total = 0\n for i in range(len(s) - 1):\n if roman[s[i]] < roman[s[i+1]]:\n total -= roman[s[i]]\n else:\n total += roman[s[i]]\n return total + roman[s[-1]]\n```\n\n<b>Method 2:</b>\nThis solution takes the approach of saying "The logic of roman numerals is too complicated. Let\'s make it easier by rewriting the numeral so that we only have to <i>add</i> and not worry about subtraction.\n\nIt starts off the same way by creating a dictionary and a total variable. It then performs substring replacement for each of the 6 possible cases that subtraction can be used and replaces it with a version that can just be added together. For example, IV is converted to IIII, so that all the digits can be added up to 4. Then we just loop through the string and add up the total.\n```\n roman = {\n "I": 1,\n "V": 5,\n "X": 10,\n "L": 50,\n "C": 100,\n "D": 500,\n "M": 1000\n }\n total = 0\n s = s.replace("IV", "IIII").replace("IX", "VIIII")\n s = s.replace("XL", "XXXX").replace("XC", "LXXXX")\n s = s.replace("CD", "CCCC").replace("CM", "DCCCC")\n for symbol in s:\n total += roman[symbol]\n return total\n```
18
0
['Hash Table', 'Math', 'String', 'Python', 'Python3']
2
roman-to-integer
Python, C++, Java Easy solution 87.30%
python-c-java-easy-solution-8730-by-naga-qudu
\u2705Below code is in python same approach for C++ and JAVA\nPlease UPVOTE if u like the CODE (^_^)\n\nTime Complexity O(n)\n\nPlease UPVOTE (^_^)\n\n\nclass S
Nagadinesh99
NORMAL
2022-08-29T18:04:50.885282+00:00
2022-08-29T18:05:18.937801+00:00
2,915
false
**\u2705Below code is in python same approach for C++ and JAVA\nPlease UPVOTE if u like the CODE (^_^)**\n\n**Time Complexity O(n)**\n\n**Please UPVOTE (^_^)**\n\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n d={\'I\':1,\'V\':5,\'X\':10,\'L\':50,\'C\':100,\'D\':500,\'M\':1000}\n c=0\n s = s.replace("IV", "IIII").replace("IX", "VIIII")\n s = s.replace("XL", "XXXX").replace("XC", "LXXXX")\n s = s.replace("CD", "CCCC").replace("CM", "DCCCC")\n for i in s:\n c=c+d[i]\n return c\n```\n\n\n**Runtime: 54 ms, faster than 87.04% of Python3 online submissions for Roman to Integer.\nMemory Usage: 13.8 MB, less than 76.15% of Python3 online submissions for Roman to Integer.**
18
0
['Hash Table', 'C', 'Python', 'Java']
1
roman-to-integer
✔️4 easy solution Explained | Beginner-friendly | Dictionary, Arithmetic logic
4-easy-solution-explained-beginner-frien-w2lv
\nBrutal force:\n In this solution, we just need a bunch of if statement.\n If we encounter I, we need to check if there are V and X after it.\n If we encounte
luluboy168
NORMAL
2022-08-15T01:32:57.726010+00:00
2022-08-15T15:11:21.133751+00:00
925
false
\n**Brutal force:**\n* In this solution, we just need a bunch of if statement.\n* If we encounter `I`, we need to check if there are `V` and `X` after it.\n* If we encounter `X`, we need to check if there are `L` and `C` after it.\n* If we encounter `C`, we need to check if there are `D` and `M` after it.\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n \n i, ans = 0, 0\n while i < len(s):\n if s[i] == \'I\':\n if i < len(s) - 1 and s[i + 1] == \'V\':\n ans += 4\n i += 1\n elif i < len(s) - 1 and s[i + 1] == \'X\':\n ans += 9\n i += 1\n else:\n ans += 1\n elif s[i] == \'V\':\n ans += 5\n elif s[i] == \'X\':\n if i < len(s) - 1 and s[i + 1] == \'L\':\n ans += 40\n i += 1\n elif i < len(s) - 1 and s[i + 1] == \'C\':\n ans += 90\n i += 1\n else:\n ans += 10\n elif s[i] == \'L\':\n ans += 50\n elif s[i] == \'C\':\n if i < len(s) - 1 and s[i + 1] == \'D\':\n ans += 400\n i += 1\n elif i < len(s) - 1 and s[i + 1] == \'M\':\n ans += 900\n i += 1\n else:\n ans += 100\n elif s[i] == \'D\':\n ans += 500\n elif s[i] == \'M\':\n ans += 1000\n i += 1\n \n return ans\n```\n\n**Dictionary solution:**\n* We add every possible numbers in the dictionary.\n* Then just use a while loop to calculate the sum.\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n \n res, i = 0, 0\n map = {\n \'I\': 1,\n \'IV\': 4,\n \'V\': 5, \n \'IX\': 9, \n \'X\': 10,\n \'XL\': 40,\n \'L\': 50, \n \'XC\': 90,\n \'C\': 100,\n \'CD\': 400,\n \'D\': 500,\n \'CM\': 900,\n \'M\': 1000\n }\n \n while i < len(s):\n if s[i:i+2] in map:\n res += map[s[i:i+2]]\n i += 2\n else:\n res += map[s[i]]\n i += 1\n \n return res\n```\n\n**Arithmetic logic solution:**\n* We build a dictionary, but without those need to subtract.\n* If the number in the back is 5 times or 10 times bigger than the front, we need to subtract the number.\n```\nclass Solution(object):\n def romanToInt(self, s):\n map = {"I":1, "V":5, "X":10, "L":50, "C":100, "D": 500, "M": 1000 }\n \n res, i = 0, 0\n while i < len(s)-1:\n if float(map[s[i]])/map[s[i+1]] == 0.2 or float(map[s[i]])/map[s[i+1]] == 0.1:\n res -= map[s[i]]\n else:\n res += map[s[i]]\n i += 1\n res += map[s[i]]\n\t\t\n return(res)\n```\n\n**String operation solution:**\n* Replace `IV`, `IX`, `XL`,`XC`,`CD`,`CM`, so we can just calculate the sum.\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n #create dictionary\n values = {\'I\': 1, \'V\': 5, \'X\': 10, \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000} \n\t\t\n s = s.replace("IV", "IIII").replace("IX", "VIIII").replace("XL", "XXXX").replace("XC", "LXXXX").replace("CD", "CCCC").replace("CM", "DCCCC")\n\t\t\n res = 0\n for c in s:\n res += values[c]\n \n return res\n```\n**Please UPVOTE if you LIKE!!**\n
18
0
[]
1
roman-to-integer
Easiest C++ code explained with comments|| HashMap approach
easiest-c-code-explained-with-comments-h-j2et
Here is my complete code, explained with comments at each step. Just go through the code and you will easily get this.\nAlso Upvote, if this helps.\n\n\nclass S
algoBreaker018
NORMAL
2022-03-21T17:59:40.759033+00:00
2022-03-21T17:59:40.759086+00:00
1,670
false
Here is my complete code, explained with comments at each step. Just go through the code and you will easily get this.\nAlso Upvote, if this helps.\n\n```\nclass Solution {\npublic:\n int romanToInt(string s) {\n // creating a map to store the character and its value\n unordered_map<char,int> m;\n m[\'I\']=1;\n m[\'V\']=5;\n m[\'X\']=10;\n m[\'L\']=50;\n m[\'C\']=100;\n m[\'D\']=500;\n m[\'M\']=1000;\n int n=s.length();\n int ans=0;\n for(int i=0;i<n;)\n {\n // if the value of the next element is greater than previous one \n // for example if we encounter IX , then basically we need to subtract the value of \'I\' from value of \'X\' and then add to answer and then also increment the iterator i by 2 , as we have already considered i+1 element\n // \'IX\'= 10-1=9\n // \'XL\'= 50-10=40\n // \'IV\'= 5-1=4\n if(i+1<n && m[s[i]]<m[s[i+1]])\n {\n ans=ans+m[s[i+1]]-m[s[i]];\n i=i+2;\n }\n // else we can simply add the value of s[i] to answer and increment i by 1\n // example- \'VIII\' = 5+1+1+1 = 8\n // \'LX\' = 50+10=60 \n else\n {\n ans=ans+m[s[i]];\n i++;\n }\n }\n return ans;\n \n }\n};\n```
18
0
['C']
2
roman-to-integer
[Python] short solution, explained
python-short-solution-explained-by-dbabi-qr2x
Let us calculate number in two steps:\n\n1. We know that I equal to 1, V equal to 5 and so on, so let us just iterate over string and add value to final answer.
dbabichev
NORMAL
2021-02-20T09:34:36.099375+00:00
2021-02-20T09:34:36.099429+00:00
528
false
Let us calculate number in two steps:\n\n1. We know that `I` equal to `1`, `V` equal to `5` and so on, so let us just iterate over string and add value to final answer.\n2. There is something we need to fix now, for example if we have `IX`, it is equal to `9`, but we added `11`, so we need to subtract `2`. Similar for `IV`, `XL, XC, CD, CM`.\n\n**Complexity**: time and space complexity is just `O(1)`, because string length is always no more than `10`. Imagine now, that we can have `k` different symbols for powers of `10` and `5` multiplied by power of `10`. Then first pass wil be `O(k)` and the second is also `O(k)`: we check all `O(k)` pairs of adjacent elements and check if they are in `fix` dictionary, so final time and space complexity in general case will be `O(k)`.\n\n```\nclass Solution:\n def romanToInt(self, s):\n dic = {"I":1, "V":5, "X":10, "L": 50, "C": 100, "D": 500, "M": 1000}\n fix = {"IX": 2, "IV": 2, "XL": 20, "XC": 20, "CD": 200, "CM": 200}\n ans = 0\n for elem in s: ans += dic[elem]\n for i, j in zip(s, s[1:]):\n if i + j in fix: ans -= fix[i + j]\n return ans \n```\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!**
18
6
[]
1
roman-to-integer
C++ // 100%
c-100-by-paulsepolia-vmhb
class Solution \n{\n private:\n \n int fun(const char a)\n {\n if(a == \'I\') return 1;\n if(a == \'V\') return 5;\n if(a == \'
paulsepolia
NORMAL
2020-01-21T16:10:19.984308+00:00
2020-01-21T16:10:19.984356+00:00
2,862
false
class Solution \n{\n private:\n \n int fun(const char a)\n {\n if(a == \'I\') return 1;\n if(a == \'V\') return 5;\n if(a == \'X\') return 10;\n if(a == \'L\') return 50;\n if(a == \'C\') return 100;\n if(a == \'D\') return 500;\n if(a == \'M\') return 1000;\n \n return 0;\n }\n \n public:\n \n int romanToInt(std::string s) \n {\n int res = 0;\n int dim = s.size();\n \n for(int i = 0; i < dim; i++)\n {\n if(i < (dim - 1) && \n fun(s[i]) < fun(s[i+1]))\n {\n res -= fun(s[i]);\n }\n else\n {\n res += fun(s[i]);\n }\n }\n \n return res;\n }\n};
18
0
['C', 'C++']
2
roman-to-integer
Simple 56ms C++ solution
simple-56ms-c-solution-by-deck-1b8k
Processing the roman number from right to left turns out to be a bit easier since we can easily tell when to add or subtract:\n\n class Solution {\n publi
deck
NORMAL
2015-06-01T19:11:56+00:00
2015-06-01T19:11:56+00:00
4,015
false
Processing the roman number from right to left turns out to be a bit easier since we can easily tell when to add or subtract:\n\n class Solution {\n public:\n int romanToInt(string s) {\n if (s.empty()) { return 0; }\n unordered_map<char, int> mp { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} };\n int sum = mp[s.back()];\n for (int i = s.size() - 2; i >= 0; --i) {\n sum += mp[s[i]] >= mp[s[i + 1]] ? mp[s[i]] : -mp[s[i]];\n }\n return sum;\n }\n };
18
2
['C++']
2
roman-to-integer
Easy to understand JAVA
easy-to-understand-java-by-junbo1226-4ehx
```\nclass Solution {\n public int romanToInt(String s) {\n HashMap m = new HashMap();\n m.put('I',1);\n m.put('V',5);\n m.put('X
junbo1226
NORMAL
2017-12-20T18:09:48.541000+00:00
2017-12-20T18:09:48.541000+00:00
7,636
false
```\nclass Solution {\n public int romanToInt(String s) {\n HashMap<Character, Integer> m = new HashMap<Character, Integer>();\n m.put('I',1);\n m.put('V',5);\n m.put('X',10);\n m.put('L',50);\n m.put('C',100);\n m.put('D',500);\n m.put('M',1000);\n char [] c = s.toCharArray();\n int [] n = new int[c.length];\n for(int i=0;i<n.length;i++)n[i]=m.get(c[i]);\n int sum=0;\n for(int i=0;i<n.length;i++)sum = i==c.length-1||n[i]>=n[i+1]?sum+n[i]:sum-n[i];\n return sum;\n \n }\n}
18
0
[]
0
roman-to-integer
✨ 0ms | 🏆 Beats 100% | C++ 🖥️ , Python 🐍, Java ☕, Go 🐹, JS 🚀 | Roman to Integer Conversion 🏅
0ms-beats-100-c-python-java-go-js-roman-27c1j
IntuitionThe Roman numeral system is based on additive and subtractive rules. To convert a Roman numeral to an integer, we can iterate through the string from l
Raza-Jaun
NORMAL
2024-12-18T15:43:43.939519+00:00
2024-12-18T15:43:43.939519+00:00
1,861
false
# Intuition\nThe Roman numeral system is based on additive and subtractive rules. To convert a Roman numeral to an integer, we can iterate through the string from left to right and apply the subtractive rule when a smaller value precedes a larger one, otherwise, we simply add the value.\n\n---\n\n\n# Approach\nWe use an unordered map to store the Roman numeral values. As we iterate through the string, for each character, we check if the current character represents a smaller value than the next one. If it does, we subtract the current value, otherwise, we add it to the sum. This ensures that subtractive combinations like "IV" or "IX" are handled correctly.\n\n---\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n---\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char,int> values;\n values.insert({{\'I\',1},{\'V\',5},{\'X\',10},{\'L\',50},{\'C\',100},{\'D\',500},{\'M\',1000}});\n int sum = 0;\n for(int i=0; i<s.length() ; i++){\n if(i+1 < s.length() && values[s[i]]<values[s[i+1]]) sum -= values[s[i]];\n else sum += values[s[i]];\n }\n return sum;\n }\n};\n```\n``` java []\nimport java.util.HashMap;\n\nclass Solution {\n public int romanToInt(String s) {\n HashMap<Character, Integer> values = new HashMap<>();\n values.put(\'I\', 1);\n values.put(\'V\', 5);\n values.put(\'X\', 10);\n values.put(\'L\', 50);\n values.put(\'C\', 100);\n values.put(\'D\', 500);\n values.put(\'M\', 1000);\n \n int sum = 0;\n for (int i = 0; i < s.length(); i++) {\n if (i + 1 < s.length() && values.get(s.charAt(i)) < values.get(s.charAt(i + 1))) {\n sum -= values.get(s.charAt(i));\n } else {\n sum += values.get(s.charAt(i));\n }\n }\n return sum;\n }\n}\n```\n``` python3 []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n values = {\'I\': 1, \'V\': 5, \'X\': 10, \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000}\n sum = 0\n for i in range(len(s)):\n if i + 1 < len(s) and values[s[i]] < values[s[i + 1]]:\n sum -= values[s[i]]\n else:\n sum += values[s[i]]\n return sum\n```\n``` javascript []\nvar romanToInt = function(s) {\n const values = {\'I\': 1, \'V\': 5, \'X\': 10, \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000};\n let sum = 0;\n for (let i = 0; i < s.length; i++) {\n if (i + 1 < s.length && values[s[i]] < values[s[i + 1]]) {\n sum -= values[s[i]];\n } else {\n sum += values[s[i]];\n }\n }\n return sum;\n};\n```\n``` Go []\nfunc romanToInt(s string) int {\n values := map[byte]int{\'I\': 1, \'V\': 5, \'X\': 10, \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000}\n sum := 0\n for i := 0; i < len(s); i++ {\n if i+1 < len(s) && values[s[i]] < values[s[i+1]] {\n sum -= values[s[i]]\n } else {\n sum += values[s[i]]\n }\n }\n return sum\n}\n```\n\n---\n\n![cat.jpg](https://assets.leetcode.com/users/images/eefefcb9-2bc7-465e-97f1-21de58697b87_1734536385.6706603.jpeg)\n
17
0
['Hash Table', 'Math', 'String', 'C++', 'Java', 'Go', 'Python3', 'JavaScript']
0
roman-to-integer
O(n) solution || Easy || String || HashMap
on-solution-easy-string-hashmap-by-tejas-dpqd
Intuition\n Describe your first thoughts on how to solve this problem. \nwe have to store roman values first at a place to calculate the value\n# Approach\n Des
tejasvi_18_08
NORMAL
2023-01-05T13:20:52.101730+00:00
2023-01-22T01:55:29.782877+00:00
6,181
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe have to store roman values first at a place to calculate the value\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStored elements in hashmap\ntraversed string from back,if current element is of less value than the prev(case:"IV") we subtract current number from are answer otherwise(case:"C") add it we also store the prev elements value in a prev to make decision\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\n public int romanToInt(String s) {\n if(s.length()==0)return 0;\n HashMap<Character, Integer> map = new HashMap<>();\n map.put(\'I\',1);\n map.put(\'V\',5);\n map.put(\'X\',10);\n map.put(\'L\',50);\n map.put(\'C\',100);\n map.put(\'D\',500);\n map.put(\'M\',1000);\n int prev=0;\n int x=0;\n for(int i=s.length()-1;i>=0;i--){\n if(prev>map.get(s.charAt(i))){\n x-=map.get(s.charAt(i));\n }\n else{\n x+=map.get(s.charAt(i));\n }\n prev=map.get(s.charAt(i));\n }\n return x;\n }\n}\n```
17
0
['Java']
1
roman-to-integer
Java || Explained || fastest || loops
java-explained-fastest-loops-by-sharad21-9vhv
\n\nclass Solution {\n public int romanToInt(String s) {\n \n int[] ar = new int[s.length()];\n \n\t\t//we store the value in array so it
Sharad21
NORMAL
2022-07-18T20:32:58.224408+00:00
2022-07-20T16:49:40.925765+00:00
804
false
```\n\n```class Solution {\n public int romanToInt(String s) {\n \n int[] ar = new int[s.length()];\n \n\t\t//we store the value in array so it easy for us to add numbers\n for(int i=0;i<ar.length;i++){\n char c = s.charAt(i);\n switch(c){\n case \'I\' : ar[i]=1;\n break;\n case \'V\': ar[i]=5;\n break;\n case \'X\': ar[i]=10;\n break;\n case \'L\' : ar[i]=50;\n break;\n case \'C\' : ar[i]=100;\n break;\n case \'D\' : ar[i]=500;\n break;\n case \'M\' : ar[i]=1000;\n break;\n }\n }\n int result =ar[ar.length-1];\n \n //we itirate from back bcoz roman number is written from right to left\n \n for(int i=ar.length-2;i>=0;i--){\n if(ar[i+1]>ar[i]){\n result-=ar[i];\n }else{\n result+=ar[i];\n }\n \n \n }\n return result;\n }\n}\n**KINDLY UPVOTE IF FIND HELPFUL**
17
0
[]
0
roman-to-integer
Python Super-Simple Easy-to-Understand Explained Solution
python-super-simple-easy-to-understand-e-yewm
\nclass Solution:\n def romanToInt(self, s: str) -> int:\n num_dict = { \'I\' : 1,\n \'V\' : 5,\n \'X\'
yehudisk
NORMAL
2021-02-20T18:04:30.590559+00:00
2021-02-20T18:04:30.590614+00:00
850
false
```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n num_dict = { \'I\' : 1,\n \'V\' : 5,\n \'X\' : 10,\n \'L\' : 50,\n \'C\' : 100,\n \'D\' : 500,\n \'M\' : 1000 }\n res=0\n i = 0\n \n while i < len(s)-1:\n if num_dict[s[i]] >= num_dict[s[i+1]]: # just add number to res\n res += num_dict[s[i]]\n i+=1\n else:\n res += num_dict[s[i+1]]-num_dict[s[i]] # if s[i]<s[i+1]: subtract from next number\n i+=2\n \n if i < len(s): # if last digit left\n res += num_dict[s[i]]\n \n return res\n```\n**Like it? please upvote...**
17
1
['Python3']
1
roman-to-integer
C Solution
c-solution-by-ianchen0119-laod
Runtime: 4 ms, faster than 87.28% of C online submissions for Roman to Integer.\nMemory Usage: 5.8 MB, less than 98.48% of C online submissions for Roman to Int
ianchen0119
NORMAL
2020-12-15T10:10:04.338483+00:00
2020-12-15T10:17:52.065378+00:00
2,651
false
Runtime: 4 ms, faster than 87.28% of C online submissions for Roman to Integer.\nMemory Usage: 5.8 MB, less than 98.48% of C online submissions for Roman to Integer.\n```c=\nint value(char opcode){\n switch(opcode){\n case \'I\': \n return 1;\n case \'V\': \n return 5;\n case \'X\': \n return 10;\n case \'L\': \n return 50;\n case \'C\': \n return 100;\n case \'D\': \n return 500;\n case \'M\': \n return 1000;\n }\n return 0;\n}\nint romanToInt(char * s){\n int sum = 0;\n for(int i = 0; s[i] !=\'\\0\'; i++){\n if(value(s[i]) < value(s[i + 1]))\n sum = sum - value(s[i]);\n else\n sum += value(s[i]);\n }\n return sum;\n}\n```
17
0
[]
1
roman-to-integer
Ruby solution 52ms
ruby-solution-52ms-by-ayamschikov-vovd
Ruby solution with\n\t- Runtime: 52 ms\n\t- Memory Usage: 9.3 MB\n\ndef roman_to_int(s)\n hash = {\n \'I\'=> 1,\n \'V\'=> 5,\n \'X\'=> 10,\n \'L\'=
ayamschikov
NORMAL
2019-11-07T17:08:38.736312+00:00
2019-11-07T17:08:38.736348+00:00
2,997
false
Ruby solution with\n\t- Runtime: 52 ms\n\t- Memory Usage: 9.3 MB\n```\ndef roman_to_int(s)\n hash = {\n \'I\'=> 1,\n \'V\'=> 5,\n \'X\'=> 10,\n \'L\'=> 50,\n \'C\'=> 100,\n \'D\'=> 500,\n \'M\'=> 1000\n }\n\n total = 0\n i = 0\n while i < s.length\n if i + 1 < s.length && hash[s[i]] < hash[s[i+1]]\n total += hash[s[i+1]] - hash[s[i]]\n i += 1\n else\n total += hash[s[i]]\n end\n\n i += 1\n end\n\n total\nend\n```
17
1
['Ruby']
4
roman-to-integer
Simple javascript solution
simple-javascript-solution-by-hadleyac-qc49
\nvar romanToInt = function(s) {\n let table = {\n I: 1,\n V: 5,\n X: 10,\n L: 50,\n C: 100,\n D: 500,\n M:
hadleyac
NORMAL
2019-09-02T22:15:32.525783+00:00
2019-09-02T22:15:32.525817+00:00
5,810
false
```\nvar romanToInt = function(s) {\n let table = {\n I: 1,\n V: 5,\n X: 10,\n L: 50,\n C: 100,\n D: 500,\n M: 1000\n }\n \n let result = 0;\n for (let i = 0; i < s.length; i++) {\n //if the next roman numeral is larger, then we know we have to subtract this number\n if (table[s[i]] < table[s[i+1]]) {\n result-=table[s[i]]\n } \n //otherwise, add like normal. \n else {\n result+=table[s[i]]\n }\n }\n return result\n \n};\n```
17
1
[]
5
roman-to-integer
✅Step By Steps Solution 🔥|| Best Method ✅ || Beats 100% User ✅ || Beginner Friendly🔥🔥🔥
step-by-steps-solution-best-method-beats-yzq8
Intuition :\nThe main idea behind converting a Roman numeral to an integer is to look for specific patterns of subtraction. For instance, when a smaller numeral
progammersoumen
NORMAL
2024-10-27T09:55:00.748244+00:00
2024-10-27T09:55:00.748266+00:00
2,960
false
### Intuition :\nThe main idea behind converting a Roman numeral to an integer is to look for specific patterns of subtraction. For instance, when a smaller numeral appears before a larger one (like IV for 4 or IX for 9), it implies a subtraction. Otherwise, the Roman numerals are simply added in descending order.\n\n### Approach :\n1. Define a mapping of Roman numerals to their integer values.\n2. Traverse each character in the string:\n - If the current numeral is less than the next one, subtract its value from the total.\n - Otherwise, add its value to the total.\n3. Return the accumulated total at the end.\n\n### Steps :\n1. Initialize a total variable to accumulate the result.\n2. Loop through each character of the input string:\n - If the value of the current character is less than the value of the next character, subtract it from the total.\n - Otherwise, add it to the total.\n3. Once the loop completes, return the total.\n\n### Time Complexity :\n- **Time Complexity**: \\( O(n) \\), where \\( n \\) is the length of the Roman numeral string. Each character is processed once.\n- **Space Complexity**: \\( O(1) \\), since we only store a few fixed mappings and use a constant amount of additional space.\n\n![WhatsApp Image 2024-10-25 at 11.38.29.jpeg](https://assets.leetcode.com/users/images/8e7a65d5-685d-4027-b78c-969f2dc7d863_1729836651.7045465.jpeg)\n\n### Solutions in Java, Python, and C++ :\n\n#### Python 3 :\n```python\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman_map={\'I\':1,\'V\':5,\'X\':10,\'L\':50,\'C\':100,\'D\':500,\'M\':1000}\n total=0\n length=len(s)\n for i in range(length):\n if i<length-1 and roman_map[s[i]]<roman_map[s[i+1]]:\n total-=roman_map[s[i]]\n else:\n total+=roman_map[s[i]]\n return total\n\n```\n\n#### Java :\n```java\nclass Solution {\nint romanToInt(String s) {\n Map<Character,Integer> romanMap=new HashMap<>();\n romanMap.put(\'I\',1);\n romanMap.put(\'V\',5);\n romanMap.put(\'X\',10);\n romanMap.put(\'L\',50);\n romanMap.put(\'C\',100);\n romanMap.put(\'D\',500);\n romanMap.put(\'M\',1000);\n int total=0;\n int length=s.length();\n for(int i=0;i<length;i++){\n if(i<length-1 && romanMap.get(s.charAt(i))<romanMap.get(s.charAt(i+1))){\n total-=romanMap.get(s.charAt(i));\n } else {\n total+=romanMap.get(s.charAt(i));\n }\n }\n return total;\n}\n}\n```\n\n#### C++ :\n```cpp \n#include <unordered_map>\n#include <string>\nusing namespace std;\nclass Solution {\npublic:\nint romanToInt(string s) {\n unordered_map<char,int> romanMap={{\'I\',1},{\'V\',5},{\'X\',10},{\'L\',50},{\'C\',100},{\'D\',500},{\'M\',1000}};\n int total=0;\n int length=s.size();\n for(int i=0;i<length;i++){\n if(i<length-1 && romanMap[s[i]]<romanMap[s[i+1]]){\n total-=romanMap[s[i]];\n } else {\n total+=romanMap[s[i]];\n }\n }\n return total;\n}\n};\n```\n\n\n
16
0
['Hash Table', 'Math', 'C++', 'Java', 'Python3']
0
roman-to-integer
✔️Python 99%🔥 Beginner-friendly 4 solution explained | easy to understand
python-99-beginner-friendly-4-solution-e-groa
Brutal force:\n In this solution, we just need a bunch of if statement.\n If we encounter I, we need to check if there are V and X after it.\n If we encounter
luluboy168
NORMAL
2022-08-15T15:05:22.624865+00:00
2022-08-15T15:05:22.624894+00:00
1,076
false
**Brutal force:**\n* In this solution, we just need a bunch of if statement.\n* If we encounter `I`, we need to check if there are `V` and `X` after it.\n* If we encounter `X`, we need to check if there are `L` and `C` after it.\n* If we encounter `C`, we need to check if there are `D` and `M` after it.\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n \n i, ans = 0, 0\n while i < len(s):\n if s[i] == \'I\':\n if i < len(s) - 1 and s[i + 1] == \'V\':\n ans += 4\n i += 1\n elif i < len(s) - 1 and s[i + 1] == \'X\':\n ans += 9\n i += 1\n else:\n ans += 1\n elif s[i] == \'V\':\n ans += 5\n elif s[i] == \'X\':\n if i < len(s) - 1 and s[i + 1] == \'L\':\n ans += 40\n i += 1\n elif i < len(s) - 1 and s[i + 1] == \'C\':\n ans += 90\n i += 1\n else:\n ans += 10\n elif s[i] == \'L\':\n ans += 50\n elif s[i] == \'C\':\n if i < len(s) - 1 and s[i + 1] == \'D\':\n ans += 400\n i += 1\n elif i < len(s) - 1 and s[i + 1] == \'M\':\n ans += 900\n i += 1\n else:\n ans += 100\n elif s[i] == \'D\':\n ans += 500\n elif s[i] == \'M\':\n ans += 1000\n i += 1\n \n return ans\n```\n\n**Dictionary solution:**\n* We add every possible numbers in the dictionary.\n* Then just use a while loop to calculate the sum.\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n \n res, i = 0, 0\n map = {\n \'I\': 1,\n \'IV\': 4,\n \'V\': 5, \n \'IX\': 9, \n \'X\': 10,\n \'XL\': 40,\n \'L\': 50, \n \'XC\': 90,\n \'C\': 100,\n \'CD\': 400,\n \'D\': 500,\n \'CM\': 900,\n \'M\': 1000\n }\n \n while i < len(s):\n if s[i:i+2] in map:\n res += map[s[i:i+2]]\n i += 2\n else:\n res += map[s[i]]\n i += 1\n \n return res\n```\n\n**Arithmetic logic solution:**\n* We build a dictionary, but without those need to subtract.\n* If the number in the back is 5 times or 10 times bigger than the front, we need to subtract the number.\n```\nclass Solution(object):\n def romanToInt(self, s):\n map = {"I":1, "V":5, "X":10, "L":50, "C":100, "D": 500, "M": 1000 }\n \n res, i = 0, 0\n while i < len(s)-1:\n if float(map[s[i]])/map[s[i+1]] == 0.2 or float(map[s[i]])/map[s[i+1]] == 0.1:\n res -= map[s[i]]\n else:\n res += map[s[i]]\n i += 1\n res += map[s[i]]\n\t\t\n return(res)\n```\n\n**String operation solution:**\n* Replace `IV`, `IX`, `XL`,`XC`,`CD`,`CM`, so we can just calculate the sum.\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n #create dictionary\n values = {\'I\': 1, \'V\': 5, \'X\': 10, \'L\': 50, \'C\': 100, \'D\': 500, \'M\': 1000} \n\t\t\n s = s.replace("IV", "IIII").replace("IX", "VIIII").replace("XL", "XXXX").replace("XC", "LXXXX").replace("CD", "CCCC").replace("CM", "DCCCC")\n\t\t\n res = 0\n for c in s:\n res += values[c]\n \n return res\n```\n**Please UPVOTE if you LIKE!!**\n
16
0
['Python']
0
diagonal-traverse-ii
[Clean, Simple] Easiest Explanation with a picture and code with comments
clean-simple-easiest-explanation-with-a-72abg
Key Idea\nIn a 2D matrix, elements in the same diagonal have same sum of their indices.\n\n\n\n\n\nSo if we have all elements with same sum of their indices tog
interviewrecipes
NORMAL
2020-04-26T04:03:10.830708+00:00
2020-08-08T05:22:49.226540+00:00
21,004
false
**Key Idea**\nIn a 2D matrix, elements in the same diagonal have same sum of their indices.\n\n![image](https://assets.leetcode.com/users/interviewrecipes/image_1591684927.png)\n\n\n\nSo if we have all elements with same sum of their indices together, then it\u2019s just a matter of printing those elements in order.\n\n**Algorithm**\n1. Insert all elements into an appropriate bucket i.e. nums[i][j] in (i+j)th bucket.\n2. For each bucket starting from 0 to max, print all elements in the bucket. \n**Note**: Here, diagonals are from bottom to top, but we traversed the input matrix from first row to last row. Hence we need to print the elements in reverse order.\n\nPlease upvote if you liked the idea, it would be encouraging. If you like this, checkout my blog/website for posts on coding interviews, programming, data structures and algorithms, problem solving.\n\n**C++**\n```\nvector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int> answer;\n unordered_map<int, vector<int>> m;\n int maxKey = 0; // maximum key inserted into the map i.e. max value of i+j indices.\n \n for (int i=0; i<nums.size(); i++) {\n for (int j=0; j<nums[i].size(); j++) {\n m[i+j].push_back(nums[i][j]); // insert nums[i][j] in bucket (i+j).\n maxKey = max(maxKey, i+j); // \n }\n }\n for (int i=0; i<= maxKey; i++) { // Each diagonal starting with sum 0 to sum maxKey.\n for (auto x = m[i].rbegin(); x != m[i].rend(); x++) { // print in reverse order.\n answer.push_back(*x); \n }\n }\n \n return answer;\n }\n\n```
581
0
[]
49
diagonal-traverse-ii
[Java/C++] HashMap with Picture - Clean code - O(N)
javac-hashmap-with-picture-clean-code-on-tr0o
Example:\n\n\nJava\njava\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int n = 0, i = 0, maxKey = 0;\n Map<I
hiepit
NORMAL
2020-04-26T04:01:24.287061+00:00
2020-04-26T07:41:49.736870+00:00
14,153
false
Example:\n![image](https://assets.leetcode.com/users/hiepit/image_1587879572.png)\n\n**Java**\n```java\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int n = 0, i = 0, maxKey = 0;\n Map<Integer, List<Integer>> map = new HashMap<>();\n for (int r = nums.size() - 1; r >= 0; --r) { // The values from the bottom rows are the starting values of the diagonals.\n for (int c = 0; c < nums.get(r).size(); ++c) {\n map.putIfAbsent(r + c, new ArrayList<>());\n map.get(r + c).add(nums.get(r).get(c));\n maxKey = Math.max(maxKey, r + c);\n n++;\n }\n }\n int[] ans = new int[n];\n for (int key = 0; key <= maxKey; ++key) {\n List<Integer> value = map.get(key);\n if (value == null) continue;\n for (int v : value) ans[i++] = v;\n }\n return ans;\n }\n}\n```\n**C++**\n```c++\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int maxKey = 0;\n unordered_map<int, vector<int>> map;\n for (int r = nums.size() - 1; r >= 0; --r) { // The values from the bottom rows are the starting values of the diagonals.\n for (int c = 0; c < nums[r].size(); ++c) {\n map[r + c].push_back(nums[r][c]);\n maxKey = max(maxKey, r + c);\n }\n }\n vector<int> ans;\n for (int key = 0; key <= maxKey; ++key)\n for (int v : map[key]) ans.push_back(v);\n return ans;\n }\n};\n```\nTime: `O(N)`, where `N` is the number of elements of `nums`\nSpace: `O(N)`
173
2
[]
23
diagonal-traverse-ii
[Python] Simple BFS solution with detailed explanation
python-simple-bfs-solution-with-detailed-5vgh
Explanation\nWe can think of the given matrix as a tree and use BFS to solve this problem.\n\nThe top-left number, nums[0][0], is the root node. nums[1][0] is
alanlzl
NORMAL
2020-04-26T04:00:51.115073+00:00
2020-04-26T04:00:51.115126+00:00
4,352
false
**Explanation**\nWe can think of the given matrix as a tree and use BFS to solve this problem.\n\nThe top-left number, `nums[0][0]`, is the root node. `nums[1][0]` is its left child and `nums[0][1]` is its right child. Same analogy applies to all nodes `nums[i][j]`.\n\nNote that `nums[i][j]` is both the left child of `nums[i-1][j]` and the right child of `nums[i][j-1]`. To avoid double counting, we only consider a number\'s left child when we are at the left-most column (`j == 0`).\n\n<br />\n\n**Python**\n```\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n ans = []\n m = len(nums)\n \n queue = collections.deque([(0, 0)])\n while queue:\n row, col = queue.popleft()\n ans.append(nums[row][col])\n # we only add the number at the bottom if we are at column 0\n if col == 0 and row + 1 < m:\n queue.append((row + 1, col))\n # add the number on the right\n if col + 1 < len(nums[row]):\n queue.append((row, col + 1))\n \n return ans\n```
146
0
[]
15
diagonal-traverse-ii
[Python] One pass
python-one-pass-by-lee215-p66y
Time O(A), Space O(A)\n\nPython:\npy\n def findDiagonalOrder(self, A):\n res = []\n for i, r in enumerate(A):\n for j, a in enumerat
lee215
NORMAL
2020-04-26T04:08:14.947205+00:00
2020-04-26T04:08:14.947251+00:00
10,993
false
Time `O(A)`, Space `O(A)`\n\n**Python:**\n```py\n def findDiagonalOrder(self, A):\n res = []\n for i, r in enumerate(A):\n for j, a in enumerate(r):\n if len(res) <= i + j:\n res.append([])\n res[i + j].append(a)\n return [a for r in res for a in reversed(r)]\n```\n
121
7
[]
20
diagonal-traverse-ii
Simple Solution || Beginner Friendly || Easy to Understand ✅
simple-solution-beginner-friendly-easy-t-vh30
Approach\n Describe your approach to solving the problem. \nInitialization:\n- Initialize a variable count to keep track of the total number of elements in the
Anirban_Pramanik10
NORMAL
2023-11-22T00:30:02.763669+00:00
2023-11-22T00:30:02.763693+00:00
15,011
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n$$Initialization:$$\n- Initialize a variable `count` to keep track of the total number of elements in the result array.\n- Create an ArrayList of ArrayLists called `lists` to store the elements diagonally.\n\n$$Traversing the Matrix Diagonally:$$\n- Use two nested loops to traverse each element in the matrix `(nums)`.\n- For each element at position `(i, j)`, calculate the diagonal index `idx` by adding `i` and `j`.\n- If the size of lists is less than `idx + 1`, it means we are encountering a new diagonal, so add a new ArrayList to lists.\n- Add the current element to the corresponding diagonal ArrayList in `lists`.\n- Increment the `count` to keep track of the total number of elements.\n\n$$Flattening Diagonal Lists to Result Array:$$\n- Create an array `res` of size `count` to store the final result.\n- Initialize an index `idx` to keep track of the position in the result array.\n\n$$Flatten Diagonals in Reverse Order:$$\n- Iterate over each diagonal ArrayList in `lists`.\n- For each diagonal, iterate in reverse order and add the elements to the result array `(res)`.\n- Increment the index `idx` for each added element.\n\n$$Return Result Array:$$\n- Return the final result array `res`.\n\n\n\n# Complexity\n- Time complexity: `O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int count = 0;\n\n List<List<Integer>> lists = new ArrayList<>();\n for (int i = 0; i < nums.size(); i++) {\n List<Integer> row = nums.get(i);\n\n for (int j = 0; j < row.size(); j++) {\n int idx = i + j;\n\n if (lists.size() < idx + 1) {\n lists.add(new ArrayList<>());\n }\n lists.get(idx).add(row.get(j));\n \n count ++;\n }\n }\n\n int[] res = new int[count];\n int idx = 0;\n for (List<Integer> list : lists) {\n for (int i = list.size() - 1; i >= 0; i--) {\n res[idx++] = list.get(i); \n }\n }\n return res;\n }\n}\n```\n```python []\nclass Solution:\n def findDiagonalOrder(self, nums):\n diagonals = [deque() for _ in range(len(nums) + max(len(row) for row in nums) - 1)]\n for row_id, row in enumerate(nums):\n for col_id in range(len(row)):\n diagonals[row_id + col_id].appendleft(row[col_id])\n return list(chain(*diagonals))\n```\n```python3 []\nclass Solution:\n def findDiagonalOrder(self, A: List[List[int]]) -> List[int]:\n d = defaultdict(list)\n for i in range(len(A)):\n for j in range(len(A[i])):\n d[i+j].append(A[i][j])\n return [v for k in d.keys() for v in reversed(d[k])]\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int m=nums.size(),n=0;\n \n //find max value and store in n;\n \n for(int i=0;i<m;i++){\n if(n<nums[i].size())\n n=nums[i].size();\n }\n vector<vector<int>>temp(m+n);\n vector<int>ans;\n \n // convert mat into adjacency list and keep value in temp\n \n for(int i=0;i<m;i++){\n for(int j=0;j<nums[i].size();j++){\n temp[i+j].push_back(nums[i][j]);\n }\n }\n \n // here we reverse matrix\n \n for(int i=0;i<m+n;i++){\n reverse(temp[i].begin(),temp[i].end());\n }\n \n // all value of temp in ans vector\n \n for(int i=0;i<m+n;i++){\n for(int j=0;j<temp[i].size();j++){\n ans.push_back(temp[i][j]);\n }\n }\n return ans;\n }\n};\n```\n```Javascript []\nvar findDiagonalOrder = function(nums) {\n const result = [];\n\n for (let row = 0; row < nums.length; row++) {\n for (let col = 0; col < nums[row].length; col++) {\n const num = nums[row][col];\n if (!num) continue;\n const current = result[row + col];\n\n current \n ? current.unshift(num)\n : result[row + col] = [num];\n }\n }\n return result.flat();\n};\n```\n```C []\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int m=nums.size(),n=0;\n \n //find max value and store in n;\n \n for(int i=0;i<m;i++){\n if(n<nums[i].size())\n n=nums[i].size();\n }\n vector<vector<int>>temp(m+n);\n vector<int>ans;\n \n // convert mat into adjacency list and keep value in temp\n \n for(int i=0;i<m;i++){\n for(int j=0;j<nums[i].size();j++){\n temp[i+j].push_back(nums[i][j]);\n }\n }\n \n // here we reverse matrix\n \n for(int i=0;i<m+n;i++){\n reverse(temp[i].begin(),temp[i].end());\n }\n \n // all value of temp in ans vector\n \n for(int i=0;i<m+n;i++){\n for(int j=0;j<temp[i].size();j++){\n ans.push_back(temp[i][j]);\n }\n }\n return ans;\n }\n};\n```\n# If you like the solution please UPVOTE !!\n\n![da69d522-8deb-4aa6-a4db-446363bf029f_1687283488.9528875.gif](https://assets.leetcode.com/users/images/763d842d-951c-454c-bde8-e1d60d1ff27f_1700612786.7402914.gif)\n\n\n\n\n
95
3
['Array', 'Linked List', 'Depth-First Search', 'Breadth-First Search', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
6
diagonal-traverse-ii
[C++] Single pass solution using BFS, 308ms (99.72%)
c-single-pass-solution-using-bfs-308ms-9-e71u
I couldn\'t find any truly single pass solution in the discussions. Here is my approach (using BFS).\nAlgorithm-\n1. In the queue for BFS, insert the index for
kunal_mohta
NORMAL
2020-04-27T03:41:54.324705+00:00
2020-04-27T03:41:54.324753+00:00
2,428
false
I couldn\'t find any truly single pass solution in the discussions. Here is my approach (using BFS).\nAlgorithm-\n1. In the queue for BFS, insert the index for first cell of first row, i.e. `{0,0}`\n2. For each iteration, for the `front` element in queue push the index for cell just below it only if the current cell is the first in its row.\n3. Then push the index for right neighbour cell (if exists)\n\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int m = nums.size();\n\t\tvector<int> ans;\n queue<pair<int, int>> q;\n q.push({0,0}); // first row, first cell\n\t\t\n\t\t// BFS\n while (!q.empty()) {\n pair<int, int> p = q.front();\n q.pop();\n ans.push_back(nums[p.first][p.second]);\n\t\t\t\n\t\t\t// insert the element below, if in first column\n if (p.second == 0 && p.first+1 < m) q.push({p.first+1, p.second});\n\t\t\t\n\t\t\t// insert the right neighbour, if exists\n if (p.second+1 < nums[p.first].size())\n q.push({p.first, p.second+1});\n }\n return ans;\n }\n};\n```
49
0
[]
6
diagonal-traverse-ii
【Video】Give me 9 minutes - How we think about a solution
video-give-me-9-minutes-how-we-think-abo-6m4v
Intuition\nUsing BFS\n\n---\n\n# Solution Video\n\nhttps://youtu.be/4wkt4kGip64\n\n\u25A0 Timeline of the video\n0:04 How we think about a solution\n1:08 How ca
niits
NORMAL
2023-11-22T09:22:16.755166+00:00
2023-11-23T17:47:37.638368+00:00
2,277
false
# Intuition\nUsing BFS\n\n---\n\n# Solution Video\n\nhttps://youtu.be/4wkt4kGip64\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`1:08` How can you put numbers into queue with right order?\n`2:34` Demonstrate how it works\n`6:24` Summary of main idea\n`6:47` Coding\n`8:40` Time Complexity and Space Complexity\n`8:57` Summary of the algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,180\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n## How we think about a solution\n\nWe know order of output, so problem is that how we can take target numbers with the right order.\n\nLet\'s use Example 2 and make input array small.\n\n```\nInput: nums = [[1,2,3],[4],[5,6]]\n\n1,2,3\n4, ,\n5,6,\n```\n```\nOutput:[1,4,2,5,3,6]\n```\nWe can see that by changing our perspective on the array, we can traverse it in a manner similar to BFS.\n\n```\n 1\n 4 2\n 5 3\n 6\n```\nThat\'s why we use `Queue` to solve the problem.\n\n- How we can put numbers into queue with right order?\n\n```\n1,2,3\n4, ,\n5,6,\n```\nAcutually, we keep row and col position of each number in `queue` to calculate neighbor positions.\n\nAs you may know typical BFS, we put left child and right child into queue from parent, so when we traverse `1`, we try to put next positions in the next line staring with `4` into `queue`.\n\nBasically, we put current `right` position into `queue`, because we know that right adjacent number is a number for next line. But how can we jump to the next line?\n\nIn the example above, we want to traverse `1,4,2,5,3,6`. In other words, how can you start new lines? For example, from `2` to `5`.\n\nMy answer is when we are `col = 0`, we put a `bottom` position first, then check `right` position, so that we can start new lines with numbers in `col \n= 0`.\n\nLet\'s see one by one.\n\n```\n1,2,3\n4, ,\n5,6,\n\nq = [(0,0)] (= (0,0) is start position)\n\n(0,0): 1\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 0\nq = []\nres = [1] \n\nNow col = 0, so add bottom position to queue\nq = [(1,0)]\n\nThen check right side, find 2. Add position to queue\nq = [(1,0),(0,1)]\n\n(1,0): 4\n(0,1): 2\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 1\ncol = 0\nq = [(0,1)]\nres = [1,4] \n\nNow col = 0, so add bottom position to queue\nq = [(0,1),(2,0)]\n\nThen check right side, there is no number, so skip\nq = [(0,1),(2,0)]\n\n(0,1): 2\n(2,0): 5\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 1\nq = [(2,0)]\nres = [1,4,2] \n\nNow col != 0, so skip\nq = [(2,0)]\n\nThen check right side, find 3. Add position to queue\nq = [(2,0),(0,2)]\n\n(2,0): 5\n(0,2): 3\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 2\ncol = 0\nq = [(0,2)]\nres = [1,4,2,5]\n\nNow col = 0, but next bottom(3,0) is out of bounds, so skip\nq = [(0,2)]\n\nThen check right side, Find 6. Add position to queue\nq = [(0,2),(2,1)]\n\n(0,2): 3\n(2,1): 6\n```\nAt bottom from row 2, col = 0, there is no number but there is 6 on the right side. so this 6 will be start number in the next line.\n\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 2\nq = [(2,1)]\nres = [1,4,2,5,3]\n\nNow col != 0, so skip\nq = [(2,1)]\n\nThen check right side, there is no number, so skip\nq = [(2,1)]\n\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 2\ncol = 1\nq = []\nres = [1,4,2,5,3,6]\n\nNow col != 0, so skip\nq = []\n\nThen check right side, there is no number, so skip\nq = []\n\n```\n\n```\nOutput: [1,4,2,5,3,6]\n```\n\n---\n\n\u2B50\uFE0F Points\n\n- When col is equal to 0, then check bottom position, so that we can start new lines with right order\n- Check right position from every position\n\n---\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm!\n\n\n### Algorithm Overview:\n1. Initialization\n2. BFS Traversal\n3. Return Result\n\n### Detailed Explanation:\n\n**Step 1: Initialization**\n```python\n# Create an empty list to store the result\nres = []\n\n# Initialize a queue with the starting point (0, 0)\nq = deque([(0, 0)])\n```\n\n**Explanation:** In this step, we set up the data structures needed for the algorithm. The `res` list will store the final result, and the `q` queue will be used for the breadth-first search (BFS) traversal. We start the traversal from the top-left corner, so the initial point `(0, 0)` is enqueued.\n\n**Step 2: BFS Traversal**\n```python\n# While the queue is not empty, perform the following steps\nwhile q:\n # Dequeue the front element\n row, col = q.popleft()\n\n # Append the current element to the result\n res.append(nums[row][col])\n\n # Enqueue the next element below if applicable\n if col == 0 and row + 1 < len(nums):\n q.append((row + 1, 0))\n\n # Enqueue the next element to the right if applicable\n if col + 1 < len(nums[row]):\n q.append((row, col + 1))\n```\n\n**Explanation:** This is the core of the algorithm, where the BFS traversal takes place. While the queue is not empty, we dequeue the front element, append the corresponding element from the input array `nums` to the result, and enqueue the next elements based on the conditions. If `col` is at the leftmost position (0), we enqueue the element below if there is a row below. Additionally, if there is a column to the right, we enqueue the element to the right.\n\n**Step 3: Return Result**\n```python\n# Return the final result list\nreturn res\n```\n\n**Explanation:** Once the BFS traversal is complete, the function returns the final result list containing the elements traversed diagonally in the 2D array.\n\nIn summary, the algorithm utilizes BFS to traverse the given 2D array diagonally, starting from the top-left corner and moving towards the bottom-right corner. The result is stored in the `res` list, which is then returned.\n\n\n# Complexity\n- Time complexity: $$O(N)$$\n`N` is number of position we visit.\n\n- Space complexity: $$O(N)$$\n\n\n```python []\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n res = []\n q = deque([(0, 0)])\n \n while q:\n row, col = q.popleft()\n res.append(nums[row][col])\n\n if col == 0 and row + 1 < len(nums):\n q.append((row + 1, 0))\n\n if col + 1 < len(nums[row]):\n q.append((row, col + 1))\n\n return res\n```\n```javascript []\nvar findDiagonalOrder = function(nums) {\n const res = [];\n const q = [[0, 0]];\n\n while (q.length > 0) {\n const [row, col] = q.shift();\n res.push(nums[row][col]);\n\n if (col === 0 && row + 1 < nums.length) {\n q.push([row + 1, 0]);\n }\n\n if (col + 1 < nums[row].length) {\n q.push([row, col + 1]);\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n List<Integer> resList = new ArrayList<>();\n LinkedList<int[]> q = new LinkedList<>();\n q.offer(new int[]{0, 0});\n\n while (!q.isEmpty()) {\n int[] p = q.poll();\n resList.add(nums.get(p[0]).get(p[1]));\n\n if (p[1] == 0 && p[0] + 1 < nums.size()) {\n q.offer(new int[]{p[0] + 1, 0});\n }\n\n if (p[1] + 1 < nums.get(p[0]).size()) {\n q.offer(new int[]{p[0], p[1] + 1});\n }\n }\n\n // Convert List<Integer> to int[]\n int[] res = new int[resList.size()];\n for (int i = 0; i < resList.size(); i++) {\n res[i] = resList.get(i);\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int> res;\n queue<pair<int, int>> q;\n q.push({0, 0});\n\n while (!q.empty()) {\n auto p = q.front();\n q.pop();\n res.push_back(nums[p.first][p.second]);\n\n if (p.second == 0 && p.first + 1 < nums.size()) {\n q.push({p.first + 1, 0});\n }\n\n if (p.second + 1 < nums[p.first].size()) {\n q.push({p.first, p.second + 1});\n }\n }\n\n return res; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/arithmetic-subarrays/solutions/4321453/video-give-me-6-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/bE6YT9q16K8\n\n\u25A0 Timeline of the video\n`0:04` What does the formula mean?\n`1:46` Demonstrate how it works\n`3:39` Coding\n`5:40` Time Complexity and Space Complexity\n`6:06` Summary of the algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/count-nice-pairs-in-an-array/solutions/4312501/video-give-me-6-minutes-hashmap-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/424EOdu4TeY\n\n\u25A0 Timeline of the video\n\n`0:04` Think about how we calculate the answer\n`0:58` Demonstrate how it works\n`3:58` Coding\n`5:53` Time Complexity and Space Complexity\n`6:11` Summary of the algorithm with my solution code\n
42
0
['C++', 'Java', 'Python3', 'JavaScript']
3
diagonal-traverse-ii
🍀 C++ || SIMPLE BFS 🍀
c-simple-bfs-by-datt_21-malz
Intuition\n- First element can be considered as root and the rest are just children of the root. \n\n# Code\n\nclass Solution {\npublic:\n vector<int> findDi
datt_21
NORMAL
2023-11-22T06:20:39.730413+00:00
2023-11-22T06:20:39.730437+00:00
2,376
false
# Intuition\n- First element can be considered as `root` and the rest are just children of the `root`. \n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& v) {\n int n = v.size();\n queue<pair<int, int>> q;\n vector<int> ans;\n\n q.push( {0, 0} );\n while (!q.empty()) {\n int i = q.front().first;\n int j = q.front().second;\n q.pop();\n\n ans.push_back(v[i][j]);\n if(!j && i + 1 < n) q.push( {i + 1, 0} );\n if(j + 1 < v[i].size()) q.push( {i, j + 1} );\n }\n\n return ans;\n }\n};\n```
27
0
['Array', 'Tree', 'Queue', 'Binary Tree', 'C++']
4
diagonal-traverse-ii
✅ One Line Solution
one-line-solution-by-mikposp-gv79
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)Code #1.1 - OnelinerTime complexity: O(n∗log(n)). Sp
MikPosp
NORMAL
2023-11-22T08:55:39.449347+00:00
2025-02-17T17:32:33.744678+00:00
717
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly) # Code #1.1 - Oneliner Time complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$. ``` class Solution: def findDiagonalOrder(self, a: List[List[int]]) -> List[int]: return [v for _,_,v in sorted((i+j,j,v) for i,r in enumerate(a) for j,v in enumerate(r))] ``` # Code #1.2 - Unwrapped ``` class Solution: def findDiagonalOrder(self, a: List[List[int]]) -> List[int]: result = [] for i,r in enumerate(a): for j,v in enumerate(r): result.append((i+j, j, v)) return [v for _, _, v in sorted(result)] ``` (Disclaimer 2: code above is just a product of fantasy packed into one line, it is not declared to be 'true' oneliners - please, remind about drawbacks only if you know how to make it better)
23
0
['Array', 'Sorting', 'Python', 'Python3']
1
diagonal-traverse-ii
C++ beat 99.9% BFS concise solution with explanation
c-beat-999-bfs-concise-solution-with-exp-x2uw
This problem is similar to "level order traverse of a tree". \n Recap:\n what matters is the order by which the "neighbor node" is added. The node in the first
veronicatt
NORMAL
2020-10-25T20:06:32.414673+00:00
2020-10-25T20:08:58.158769+00:00
1,266
false
This problem is similar to "level order traverse of a tree". \n Recap:\n* what matters is the order by which the "neighbor node" is added. The node in the first column is special, because it can generate two "neighbor nodes": the node below and the node to its right. For all other nodes, they can only generate the node immediately to its right. \n* we need to check if a neighbor node exists, b/c the given array is not exactly a M*N matrix.\n```c++\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n if (nums.empty() || nums[0].empty()) return {};\n vector<int> res;\n queue<pair<int,int>> q;\n q.push({0,0});\n while (!q.empty()) {\n auto [x,y] = q.front();\n res.push_back(nums[x][y]);\n if (x+1 < nums.size() && y == 0 ){ // node (x,y) is at the first column, add the new node below it.\n q.push({x+1,y});\n }\n if ( y+1 < nums[x].size() ){ // add the right neighbor node\n q.push({x,y+1});\n }\n q.pop();\n }\n return res;\n \n }\n};\n```
17
0
['C']
2
diagonal-traverse-ii
✅ Logic & Approach Explained through image | Very Easy and Short Code |
logic-approach-explained-through-image-v-d99e
\n\n\n# Please upvote if you understand the intuition well.\n\n# Complexity\n- Time complexity: O(n) Here, \'n\' will be total time, (row * column). Becuase the
yash_vish87
NORMAL
2023-11-22T02:29:32.652068+00:00
2023-11-22T02:32:27.799443+00:00
1,670
false
![IMG_0423.jpeg](https://assets.leetcode.com/users/images/a1445b5f-263c-4131-bf58-5c6887925b69_1700620074.96533.jpeg)\n\n\n# **Please upvote if you understand the intuition well.**\n\n# Complexity\n- Time complexity: $$O(n)$$ Here, \'n\' will be total time, (row * column). Becuase the input is jagged array, so included like this.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n List<List<Integer>> res = new ArrayList<>();\n int m = nums.size(), size = 0;\n\n for(int i = 0; i < m; i++) {\n int n = nums.get(i).size(), x = i;\n for(int j = 0; j < n; j++) {\n if(res.size() == x) {\n res.add(new ArrayList<>());\n }\n res.get(x).add(nums.get(i).get(j));\n x++; size++;\n }\n }\n int[] ans = new int[size];\n int idx = 0;\n\n for(int i = 0; i < res.size(); i++) {\n for(int j = res.get(i).size()-1; j >= 0; j--) {\n ans[idx] = res.get(i).get(j);\n idx++;\n }\n }\n return ans;\n }\n}\n```
16
0
['Array', 'Matrix', 'Simulation', 'Java']
4
diagonal-traverse-ii
[C++] Treemap O(n lg n) / Two-Passes O(n)
c-treemap-on-lg-n-two-passes-on-by-orang-yx9j
cpp\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n // Time Complexity: O(n log n)\n // Space Complex
orangezeit
NORMAL
2020-04-26T04:02:06.552842+00:00
2020-04-29T04:23:38.687839+00:00
1,304
false
```cpp\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n // Time Complexity: O(n log n)\n // Space Complexity: O(n)\n \n map<pair<int, int>, int> diagonals;\n\t\t\n // nums[i][j] is located at position j on the (i+j)-th diagonal\n for (int i = 0; i < nums.size(); ++i)\n for (int j = 0; j < nums[i].size(); ++j)\n diagonals[{i + j, j}] = nums[i][j];\n \n vector<int> ans;\n \n for (const auto& [k, v]: diagonals) ans.emplace_back(v);\n \n return ans;\n }\n};\n```\n\n```cpp\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n // Time Complexity: O(n)\n // Space Complexity: O(n)\n vector<vector<int>> diagnoals;\n \n for (int i = 0; i < nums.size(); ++i)\n for (int j = 0; j < nums[i].size(); ++j) {\n if (diagnoals.size() == i + j) diagnoals.emplace_back(vector<int>());\n diagnoals[i + j].emplace_back(nums[i][j]);\n }\n \n vector<int> ans;\n \n for (const vector<int>& d: diagnoals)\n\t\t\tans.insert(ans.end(), d.rbegin(), d.rend());\n \n return ans;\n }\n};\n```
16
1
[]
2
diagonal-traverse-ii
Java, list of stacks, explained
java-list-of-stacks-explained-by-gthor10-1xac
Catch 1 - for numbers on one diagonal sum of index of the list and index in the list is the same. This means we know the diagonal of the element when we travers
gthor10
NORMAL
2020-05-02T21:15:30.561414+00:00
2020-05-02T21:15:30.561450+00:00
1,387
false
Catch 1 - for numbers on one diagonal sum of index of the list and index in the list is the same. This means we know the diagonal of the element when we traverse lists.\n\nCatch 2 - if we swipe from top to bottom from left to right then elements are traversed in reversed order for each diagonal. This means if we use stack then poping from the stack will give us correct final order. Another thing - we are traversing diagonals in acs order so we can add stack for every diagonal as we go.\n \n O(n) time - we traverse every elemen of the list once, for each element we do constant work. Then we again traverse every element once to for resulting array\n O(n) space - need to put every element of the list to list of stacks.\n\n```\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int count = 0;\n List<Stack<Integer>> list = new ArrayList();\n for (int i = 0; i < nums.size(); i++) {\n List<Integer> oneList = nums.get(i);\n for (int j = 0; j < oneList.size(); j++) {\n\t //this is id of the diagonal\n int idx = i + j;\n\t\t//check if we haven\'t checked this diagonal before\n if (list.size() < idx + 1) {\n list.add(new Stack());\n }\n list.get(idx).push(oneList.get(j));\n ++count;\n }\n }\n\t//now traverse the list of stacks to form the final array\n int[] res = new int[count];\n int p = 0;\n for (Stack<Integer> stack : list) {\n while(!stack.isEmpty()) {\n res[p++] = stack.pop();\n }\n }\n return res;\n }\n```
13
0
['Java']
2
diagonal-traverse-ii
In-place BFS. Linear Time. No Separate Queues. C++ 68ms (100%), Java 13ms (100%).
in-place-bfs-linear-time-no-separate-que-qdep
Intuition\nWe need to flatten a 2D array and return the matrix in a diagonal order:\n\n\nThere can be up to $10^5$ rows consisting of up to $10^5$ elements each
sergei99
NORMAL
2023-11-22T13:49:11.299240+00:00
2023-11-22T20:13:55.671383+00:00
474
false
# Intuition\nWe need to flatten a 2D array and return the matrix in a diagonal order:\n![image.png](https://assets.leetcode.com/users/images/3d6dade3-38b9-41b7-8db5-016171c2e8a7_1700656054.786093.png)\n\nThere can be up to $10^5$ rows consisting of up to $10^5$ elements each, but no more than $10^5$ elements in total. Neither the matrix nor any row could be empty. Row lengths may vary within the matrix, e.g.:\n![image.png](https://assets.leetcode.com/users/images/6b201614-1967-42ae-bd70-66eaeae92779_1700656411.845924.png)\n\nTherefore we don\'t know the exact positions of elements in the resultant array until we process all the preceding elements.\n\nThe matrix can be represented as a binary tree where the leftmost column\'s elements can have up to 2 children (their neigbours to the bottom and to the right if any), and other elements can have up to 1 child (right neighbour) - thanks to @the_att_21 for this idea (https://leetcode.com/problems/diagonal-traverse-ii/solutions/4316028/c-simple-bfs/).\n\n![image.png](https://assets.leetcode.com/users/images/7b0300eb-119c-447b-a571-a461e6868b91_1700655748.0604572.png)\n\nIf we turn it by $45\\degree$, the tree becomes more obvious:\n\n![image.png](https://assets.leetcode.com/users/images/35280e5c-43e5-4eea-b736-70f2fa0d18e1_1700655918.6281843.png)\n\nNow all we need is traverse it using a BFS algorithm, so each level is completely scanned from left to right before moving on to the next level.\n\n# Approach\n\nFirst of all we turn down any recursion: $10^5$ levels of nested function calls would be an overkill. If we are not using recursion, then we should maintain a queue of elements to walk through. E.g. as we traverse the level 2 (elements `7 5 3`), we add positions of `8` and `6` to that queue to process them afterwards. The size of the queue would be limited by the size of the largest diagonal of the matrix, but the point is, do we actually need a separate container for the queue?\n\nLet\'s take a closer look at it. Consider element processing from the previous example step by step:\n| Step <td colspan=2> **Result** </td> |||<td colspan=2> **Queue** </td> |||||\n|-|-|-|-|-|-|-|-|\n| 1 | ||||| `(0, 0)` |<td> </td> <td> </td> <td> </td> <td> </td> |\n| 2 | `1` ||||| `(1, 0)` | `(0, 1)` <td> </td> <td> </td> <td> </td> <td> </td> |\n| 3 | `1` | `4` |||| `(0, 1)` <td> `(2, 0)` </td> <td> `(1, 1)` </td> <td> </td> <td> </td> |\n| 4 | `1` | `4` | `2` ||| `(2, 0)` <td> `(1, 1)` </td> <td> `(0, 2)`</td> <td> </td> <td> </td> |\n| 5 | `1` | `4` | `2` | `7` || `(1, 1)` | `(0, 2)` <td> `(2, 0)` </td> <td> `(2, 1)` </td> <td> </td> <td> </td> |\n\nAs we consume an index pair from the queue, we add element referenced by that pair to the output vector. Therefore, if we could store pairs right in the output vector, we could just replace them with values as we go. This way we would have a nice memory footprint and benefit from the data locality, e.g.:\nhttps://leetcode.com/problems/diagonal-traverse-ii/submissions/1104099614/\n\nCan we physically squeeze an index pair into a 32-bit quantity, which is the limitation of the return value type? There could be indexes up to $99999$, either for row or column, which require 17 bits of storage. But at the same time the total number of elements does not exceed $10^5$. It turns out that the present test suite does not actually have rows or columns longer than $65535$ elements. If we were not that lucky, then we would have to maintain a separate mini-queue to store those outfit 2 bits for some of the index pairs.\n\nFinally our processing looks like this:\n| Step <td colspan=7>**Result+Queue**</td> |||\n|-|-|-|\n| 1 | `(0, 0)` <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> |\n| 2 | `1` | `(1, 0)` <td> `(0, 1)` </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> |\n| 3 | `1` | `4` <td> `(0, 1)` </td> <td> `(2, 0)` </td> <td> `(1, 1)` </td> <td> </td> <td> </td> <td> </td> <td> </td> |\n| 4 | `1` | `4` <td> `2` </td> <td> `(2, 0)` </td> <td> `(1, 1)` </td> <td> `(0, 2)` </td> <td> </td> <td> </td> <td> </td> |\n| 5 | `1` | `4` <td> `2` </td> <td> `7` </td> <td> `(1, 1)` </td> <td> `(0, 2)` </td> <td> `(2, 0)` </td> <td> `(2, 1)` </td> <td> </td> |\n\nAs we go through the queued index pairs, we replace them with element values, and at the end our result array is fully populated with the elements in diagonal order.\n\n## Scala Solution\n\nAs a bonus track, we are providing a single pass solution for Scala. Kind LC question designers are giving the input parameter in the form of a singly linked list of singly linked lists. So we don\'t have random access capability here, and as such, there is no point in storing indexes in the array. So we have to go for a separate queue approach.\n\nWe introduce a mutable queue of lists, which might store either submatrices from the current row onwards, or subrows from the current element onwards. Initially it contains the reference to entire matrix. As we proceed, we remove the queue head, and if it has more than one element (be it submatrix or subrow), we add this remainder to the queue. And for submatrices we also add their first row to the queue. When the queue head is a [sub]row, then we add its head element to the result array.\n\nIt\'s a purely imperative algorithm, Java-style (except for pattern matching), not an idiomatic Scala.\n\n# Complexity\n- Time complexity: $O(m)$ where $m = \\sum\\limits_{i}length(nums[i])$\n\n- Space complexity: $O(m)$ for the result vector; $O(1)$ for intermediate storage\n\n# Micro-optimizations\n\nSome heuristic have been applied to calculate the result vector capacity in C++. An STL vector is a variable-length structure, so allocating slightly more than we need does not incur additional costs of storage reallocation and element movement.\n\nAs for Java, we have to return an array of the exact fixed size, so we probably won\'t evade movement of the elements except one case of precisely $95998$ elements, which is the maximum across the LC\'s test suite. All we can do is avoid double allocation: we accumulate the intermediate result in a temporary statically allocated array of the max size mentioned above and when we know the exact size, we create the result array and copy elements to it. We don\'t use `ArrayList` and such because they only operate boxed numbers. The same trick applies to Scala.\n\nAlso we run a full GC in Java and Scala if $n$ exceeds certain threshold (thanks to LC, `System.gc` call is not configured to do nothing). This helps maintaining a smaller memory footprint and does not cost any milliseconds of the execution time.\n\nC++ O3 optimization has been enabled and `stdio` sync disabled, as usually.\n\n# Measurements\n\n| Language | Time | Beating | Memory | Beating |\n|-|-|-|-|-|\n| C++ | 68 ms | 100% | 59.3 Mb | 100% |\n| Java | 13 ms | 100% | 58.52 Mb | 99.89% |\n| Scala | 1030 ms | 100% | 80.04 Mb | 100% |\n\nSubmission links:\n**C++**\nhttps://leetcode.com/problems/diagonal-traverse-ii/submissions/1104099614/\nhttps://leetcode.com/problems/diagonal-traverse-ii/submissions/1104147518/\nhttps://leetcode.com/problems/diagonal-traverse-ii/submissions/1104420367/\n**Java**\nhttps://leetcode.com/problems/diagonal-traverse-ii/submissions/1104210474/\n**Scala**\nhttps://leetcode.com/problems/diagonal-traverse-ii/submissions/1104353600/\nhttps://leetcode.com/problems/diagonal-traverse-ii/submissions/1104387778/\n(note that due to lack of competing solutions in Scala, our code wins 100%, but it might not actually be the optimal one)\n\nThere is another 13 ms Java submission from an author who was not using a queue, but implemented a BFS traversal directly on the input array using complicated index calculations, and did calculate the exact output array size up front. Yet they still use an $O(n)$ temporary storage to maintain row lengths and run a preprocessing loop to calculate them.\n\n# Code\n``` C++ []\nclass Solution {\nprivate:\n typedef unsigned short idx_t;\n\n static unsigned pack(const idx_t i, const idx_t j) __attribute__((always_inline)) {\n return (i << 16) + j;\n }\n\n static idx_t unpack_i(const unsigned p) __attribute__((always_inline)) {\n return p >> 16;\n }\n\n static idx_t unpack_j(const unsigned p) __attribute__((always_inline)) {\n return p & ((1u << 16) - 1u);\n }\n\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n constexpr unsigned MAXC = 95998u;\n const unsigned n = nums.size();\n vector<int> r;\n r.reserve(min(n * n, MAXC));\n unsigned q = 0;\n r.push_back(pack(0, 0));\n while (q < r.size()) {\n unsigned i = unpack_i(r[q]), j = unpack_j(r[q]);\n r[q] = nums[i][j];\n q++;\n if (!j && i + 1 < n) r.push_back(pack(i + 1u, 0u));\n if (j + 1 < nums[i].size()) r.push_back(pack(i, j + 1u));\n }\n return r;\n }\n};\n```\n``` Java []\nclass Solution {\n private static final int MAXC = 95998;\n private static int[] r = new int[MAXC];\n\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n final int n = nums.size();\n if (n > 1000) System.gc();\n int q = 0, t = 1;\n r[0] = 0;\n while (q < t) {\n final int i = r[q] >>> 16, j = r[q] & ((1 << 16) - 1);\n r[q] = nums.get(i).get(j);\n q++;\n if (j == 0 && i + 1 < n) r[t++] = (i + 1) << 16;\n if (j + 1 < nums.get(i).size()) r[t++] = (i << 16) + j + 1;\n }\n if (r.length == q) return r;\n final int[] u = new int[q];\n System.arraycopy(r, 0, u, 0, q);\n return u;\n }\n}\n```\n``` Scala []\nobject Solution {\n private[this] val MAXC = 95998\n private[this] val r = Array.fill[Int](MAXC)(0)\n\n def findDiagonalOrder(nums: List[List[Int]]): Array[Int] = {\n val n = nums.length\n if (n > 1000) System.gc()\n var t = 0\n val queue = new collection.mutable.Queue[List[Any]](n)\n queue += nums\n while (!queue.isEmpty) {\n val curr = queue.removeHead() match {\n case head :: Nil => head\n case head :: tail => queue += tail; head\n case Nil => // unreachable\n }\n curr match {\n case row : List[Any] => queue += row\n case elem : Int => r(t) = elem; t += 1\n }\n }\n if (r.length == t) r\n else r.slice(0, t)\n }\n}\n```
12
1
['Array', 'Bit Manipulation', 'Breadth-First Search', 'C++', 'Java', 'Scala']
4
diagonal-traverse-ii
(●'◡'●) Dicts are OP💕.py
dicts-are-oppy-by-jyot_150-z7l5
Intuition\nWe can definitely think on something like (i+j) elements are together\n# Code\njs\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[i
jyot_150
NORMAL
2023-11-22T05:01:01.891757+00:00
2023-11-22T05:01:01.891792+00:00
817
false
# Intuition\nWe can definitely think on something like (i+j) elements are together\n# Code\n```js\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n mp,ans={},[]\n for i in range(len(nums)):\n for j in range(len(nums[i])):\n if i+j not in mp:mp[i+j]=[nums[i][j]]\n else:mp[i+j].append(nums[i][j])\n for i in mp:ans.extend(mp[i][::-1])\n return ans\n```\n\n![](https://qph.cf2.quoracdn.net/main-qimg-85f77f4c2af9745fccf82cf54249e90d-lq)
12
2
['Python3']
5
diagonal-traverse-ii
[C++] Sort by sum of coordinates
c-sort-by-sum-of-coordinates-by-zhanghui-igmc
Given a list of list, return all elements of the nums in diagonal order.\n\n# Explanation\n\nIf the size of nums is small, we can directly walk on each diagonal
zhanghuimeng
NORMAL
2020-04-26T04:04:37.530324+00:00
2020-04-26T04:04:37.530376+00:00
699
false
Given a list of list, return all elements of the `nums` in diagonal order.\n\n# Explanation\n\nIf the size of `nums` is small, we can directly walk on each diagonal line to get the result. The time complexity is `O(n*m)`. However, `nums` is not a matrix but a list of list, and `n, m <= 10^5`, and doing so will cause TLE.\n\nTo avoid TLE, observe that the sum of x and y coordinates on each diagonal line is the same, and the x coordinate of each diagonal line from left-down corner to right-upper corner increases. \n\n![image](https://assets.leetcode.com/users/zhanghuimeng/image_1587873865.png)\n\nThen just perform a sort by the keywords of `(x+y, x, nums[x][y])`.\n\nThe time complexity is `O(N*logN)`, where `N` is the number of elements in `nums`.\n\n# C++ Solution\n\n```cpp\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<pair<pair<int, int>, int>> a;\n for (int x = 0; x < nums.size(); x++) {\n for (int y = 0; y < nums[x].size(); y++) {\n a.emplace_back(make_pair(x + y, y), nums[x][y]);\n }\n }\n sort(a.begin(), a.end());\n vector<int> ans;\n for (auto& p: a)\n ans.push_back(p.second);\n \n return ans;\n }\n};\n```\n
11
1
[]
3
diagonal-traverse-ii
[Python] Two simple solutions (dictionary or sort) - O(n)
python-two-simple-solutions-dictionary-o-3q04
The first solution is to use dictionary. Complexity O(n)\nRecord the (r+c) as the key, then reverse list for each (r+c) and append it to the result.\n\n\tclass
lichuan199010
NORMAL
2020-04-26T05:05:22.714611+00:00
2020-04-26T15:51:37.569323+00:00
1,183
false
The first solution is to use dictionary. Complexity O(n)\nRecord the (r+c) as the key, then reverse list for each (r+c) and append it to the result.\n\n\tclass Solution:\n\t\tdef findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n\t\t\tD = collections.defaultdict(list)\n\t\t\tR = len(nums)\n\n\t\t\tfor r in range(R):\n\t\t\t\tfor c in range(len(nums[r])):\n\t\t\t\t\tD[r+c].append(nums[r][c])\n\n\t\t\tres = []\n\t\t\tfor k in sorted(D.keys()):\n\t\t\t\tres.extend(D[k][::-1])\n\t\t\treturn res\n\t\t\t\nIn turns of passing leetcode OJ, a quicker way to write the code is to sort by r+c, and -r. \nThe complexity will be O(nlogn).\n\n\tclass Solution:\n\t\tdef findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n\t\t\tres = []\n\t\t\tR = len(nums)\n\t\t\tfor r in range(len(nums)):\n\t\t\t\tfor c in range(len(nums[r])):\n\t\t\t\t\tres.append((r+c, -r, nums[r][c]))\n\t\t\tres.sort()\n\t\t\treturn [x[2] for x in res]
10
0
[]
3
diagonal-traverse-ii
C++ array of deque->2D array
c-array-of-deque-2d-array-by-anwendeng-xo9v
Intuition\n Describe your first thoughts on how to solve this problem. \nUse array of deque diag to store the numbers on diagonal.\n\n2nd approach uses just 2D
anwendeng
NORMAL
2023-11-22T00:34:37.936066+00:00
2023-11-22T01:56:13.082880+00:00
1,632
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse array of deque `diag` to store the numbers on diagonal.\n\n2nd approach uses just 2D array( vector) which is more efficient. Then when using `copy` function adding to `ans`, use reverse iterator for `diag[i]`.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIterate the `nums`. Push front `nums[i][j]` on the deque `diag[i+j]`.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(sz)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(sz)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums.size(), M=0, sz;\n \n for(int i=0; i<n; i++){\n M=max(M, i+(int)nums[i].size());// Find max index for diag\n sz+=nums[i].size();// Compute the real size sz for nums\n }\n vector<deque<int>> diag(M+1);\n\n \n for(int i=0; i<n; i++){\n int col=nums[i].size();\n \n for(int j=0; j<col; j++){\n //Push front keeps the order\n diag[i+j].push_front(nums[i][j]); \n }\n }\n vector<int> ans(sz);\n int idx=0;\n \n for(int i=0; i<=M; i++){\n for(int x: diag[i])\n ans[idx++]=x; // Put into ans array\n }\n return ans;\n }\n};\n\n```\n# 2nd Approach using 2D array\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int n=nums.size(), M=0, sz;\n \n for(int i=0; i<n; i++){\n M=max(M, i+(int)nums[i].size());\n sz+=nums[i].size();\n }\n vector<vector<int>> diag(M+1);\n\n \n for(int i=0; i<n; i++){\n int col=nums[i].size();\n \n for(int j=0; j<col; j++){\n diag[i+j].push_back(nums[i][j]);\n }\n }\n vector<int> ans(sz);\n int idx=0;\n \n for(int i=0; i<=M; i++){\n copy(diag[i].rbegin(), diag[i].rend(), ans.begin()+idx);\n idx+=diag[i].size();\n }\n return ans;\n }\n};\n\n```
9
1
['Array', 'Queue', 'C++']
1
diagonal-traverse-ii
USING PRIORITY_QUEUE || 50%+ ||EASY TO UNDER STAND
using-priority_queue-50-easy-to-under-st-ud1c
\n#define pi pair<pair<int,int>,int>\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n priority_queue<pi,vecto
charadiyahardip
NORMAL
2022-07-24T17:53:45.840470+00:00
2022-07-24T17:53:45.840517+00:00
788
false
```\n#define pi pair<pair<int,int>,int>\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n priority_queue<pi,vector<pi>,greater<pi>>q;\n \n for(int i=0; i<nums.size(); i++)\n {\n for(int j=0; j<nums[i].size(); j++)\n {\n q.push({{i+j,j},nums[i][j]});\n }\n }\n \n vector<int> ans;\n while(!q.empty())\n {\n ans.push_back(q.top().second);\n q.pop();\n }\n return ans;\n }\n};\n```
9
0
['C', 'Heap (Priority Queue)', 'C++']
0
diagonal-traverse-ii
[Python3] 5-lines really simple solution
python3-5-lines-really-simple-solution-b-18mv
\nclass Solution:\n def findDiagonalOrder(self, A: List[List[int]]) -> List[int]:\n d = defaultdict(list)\n for i in range(len(A)):\n
edtsoi430
NORMAL
2020-07-12T22:48:34.020664+00:00
2020-07-15T20:00:28.236230+00:00
941
false
```\nclass Solution:\n def findDiagonalOrder(self, A: List[List[int]]) -> List[int]:\n d = defaultdict(list)\n for i in range(len(A)):\n for j in range(len(A[i])):\n d[i+j].append(A[i][j])\n return [v for k in d.keys() for v in reversed(d[k])]\n```
9
1
['Python3']
3
diagonal-traverse-ii
Map Solution | CPP Solution | Intuition explained
map-solution-cpp-solution-intuition-expl-20tj
Intuition\nFor each diagonal (According to Que) sum of rowInd+colInd is same. \nEx. For given test case \n 0 1 2\n 0 [[1,2,3],\n 1 [4,5,6],\n 2 [7,8,9]]\n\n
saurav_1928
NORMAL
2023-11-22T00:52:42.190186+00:00
2023-11-22T00:52:42.190204+00:00
599
false
# Intuition\nFor each diagonal (According to Que) sum of rowInd+colInd is same. \nEx. For given test case \n 0 1 2\n 0 [[1,2,3],\n 1 [4,5,6],\n 2 [7,8,9]]\n\nfor i=0,j=0 sum=0+0=0 so for sum=0 I stored all values whose rowInd+ColInd is 0 so i create vector as there may be multiple values,\n\nfor diagonal [8, 6] sum of ind is 2+1 and 1+2 so sum is same for both, so they both will come in order\n\n# **Why I have traversed from last row?**\nThis is because diagonal is started from downside so I need to traversed it from bottomside only.\n\n\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int row=nums.size();\n vector<int>ans;\n map<int, vector<int>>mp;\n for(int i=row-1;i>=0;i--){\n int col=nums[i].size();\n for(int j=0;j<col;j++)\n mp[i+j].push_back(nums[i][j]); \n }\n for(auto &it:mp)\n {\n for(auto &val:it.second)\n ans.push_back(val);\n }\n return ans;\n }\n};\n```
8
0
['Array', 'Sorting', 'Heap (Priority Queue)', 'C++']
0
diagonal-traverse-ii
My solution in C# and some thought process
my-solution-in-c-and-some-thought-proces-y3h9
My thought process:\nWith BFS, you always add the first element in the next row(if there is a next row) if the current element is the first of the row. For each
adaoverflow
NORMAL
2020-04-26T04:18:22.252118+00:00
2020-04-26T04:22:14.563369+00:00
353
false
My thought process:\nWith BFS, you always add the first element in the next row(if there is a next row) if the current element is the first of the row. For each element, add the next element in the same row if the current element is not the last of its row.\n\n\n var res = new List<int>();\n var q = new Queue<int[]>();\n q.Enqueue(new int[]{0,0});\n \n while(q.Count>0){\n var count = q.Count;\n for(int i = 0; i<count; i++){\n var curr = q.Dequeue();\n res.Add(nums[curr[0]][curr[1]]); \n if(curr[1] == 0 && curr[0] < nums.Count() -1){\n q.Enqueue(new int[]{curr[0]+1,0});\n }\n if(nums[curr[0]].Count()-1 > curr[1]){\n q.Enqueue(new int[]{curr[0], curr[1]+1});\n }\n }\n }\n \n return res.ToArray();\n
8
0
[]
2
diagonal-traverse-ii
【Video】BFS & Queue
video-bfs-queue-by-niits-9ixo
Intuition\nUsing BFS\n\n---\n\n# Solution Video\n\nhttps://youtu.be/4wkt4kGip64\n\n\u25A0 Timeline of the video\n0:04 How we think about a solution\n1:08 How ca
niits
NORMAL
2024-03-27T04:01:47.209337+00:00
2024-03-27T04:01:47.209368+00:00
205
false
# Intuition\nUsing BFS\n\n---\n\n# Solution Video\n\nhttps://youtu.be/4wkt4kGip64\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`1:08` How can you put numbers into queue with right order?\n`2:34` Demonstrate how it works\n`6:24` Summary of main idea\n`6:47` Coding\n`8:40` Time Complexity and Space Complexity\n`8:57` Summary of the algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,180\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n## How we think about a solution\n\nWe know order of output, so problem is that how we can take target numbers with the right order.\n\nLet\'s use Example 2 and make input array small.\n\n```\nInput: nums = [[1,2,3],[4],[5,6]]\n\n1,2,3\n4, ,\n5,6,\n```\n```\nOutput:[1,4,2,5,3,6]\n```\nWe can see that by changing our perspective on the array, we can traverse it in a manner similar to BFS.\n\n```\n 1\n 4 2\n 5 3\n 6\n```\nThat\'s why we use `Queue` to solve the problem.\n\n- How we can put numbers into queue with right order?\n\n```\n1,2,3\n4, ,\n5,6,\n```\nAcutually, we keep row and col position of each number in `queue` to calculate neighbor positions.\n\nAs you may know typical BFS, we put left child and right child into queue from parent, so when we traverse `1`, we try to put next positions in the next line staring with `4` into `queue`.\n\nBasically, we put current `right` position into `queue`, because we know that right adjacent number is a number for next line. But how can we jump to the next line?\n\nIn the example above, we want to traverse `1,4,2,5,3,6`. In other words, how can you start new lines? For example, from `2` to `5`.\n\nMy answer is when we are `col = 0`, we put a `bottom` position first, then check `right` position, so that we can start new lines with numbers in `col \n= 0`.\n\nLet\'s see one by one.\n\n```\n1,2,3\n4, ,\n5,6,\n\nq = [(0,0)] (= (0,0) is start position)\n\n(0,0): 1\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 0\nq = []\nres = [1] \n\nNow col = 0, so add bottom position to queue\nq = [(1,0)]\n\nThen check right side, find 2. Add position to queue\nq = [(1,0),(0,1)]\n\n(1,0): 4\n(0,1): 2\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 1\ncol = 0\nq = [(0,1)]\nres = [1,4] \n\nNow col = 0, so add bottom position to queue\nq = [(0,1),(2,0)]\n\nThen check right side, there is no number, so skip\nq = [(0,1),(2,0)]\n\n(0,1): 2\n(2,0): 5\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 1\nq = [(2,0)]\nres = [1,4,2] \n\nNow col != 0, so skip\nq = [(2,0)]\n\nThen check right side, find 3. Add position to queue\nq = [(2,0),(0,2)]\n\n(2,0): 5\n(0,2): 3\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 2\ncol = 0\nq = [(0,2)]\nres = [1,4,2,5]\n\nNow col = 0, but next bottom(3,0) is out of bounds, so skip\nq = [(0,2)]\n\nThen check right side, Find 6. Add position to queue\nq = [(0,2),(2,1)]\n\n(0,2): 3\n(2,1): 6\n```\nAt bottom from row 2, col = 0, there is no number but there is 6 on the right side. so this 6 will be start number in the next line.\n\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 2\nq = [(2,1)]\nres = [1,4,2,5,3]\n\nNow col != 0, so skip\nq = [(2,1)]\n\nThen check right side, there is no number, so skip\nq = [(2,1)]\n\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 2\ncol = 1\nq = []\nres = [1,4,2,5,3,6]\n\nNow col != 0, so skip\nq = []\n\nThen check right side, there is no number, so skip\nq = []\n\n```\n\n```\nOutput: [1,4,2,5,3,6]\n```\n\n---\n\n\u2B50\uFE0F Points\n\n- When col is equal to 0, then check bottom position, so that we can start new lines with right order\n- Check right position from every position\n\n---\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm!\n\n\n### Algorithm Overview:\n1. Initialization\n2. BFS Traversal\n3. Return Result\n\n### Detailed Explanation:\n\n**Step 1: Initialization**\n```python\n# Create an empty list to store the result\nres = []\n\n# Initialize a queue with the starting point (0, 0)\nq = deque([(0, 0)])\n```\n\n**Explanation:** In this step, we set up the data structures needed for the algorithm. The `res` list will store the final result, and the `q` queue will be used for the breadth-first search (BFS) traversal. We start the traversal from the top-left corner, so the initial point `(0, 0)` is enqueued.\n\n**Step 2: BFS Traversal**\n```python\n# While the queue is not empty, perform the following steps\nwhile q:\n # Dequeue the front element\n row, col = q.popleft()\n\n # Append the current element to the result\n res.append(nums[row][col])\n\n # Enqueue the next element below if applicable\n if col == 0 and row + 1 < len(nums):\n q.append((row + 1, 0))\n\n # Enqueue the next element to the right if applicable\n if col + 1 < len(nums[row]):\n q.append((row, col + 1))\n```\n\n**Explanation:** This is the core of the algorithm, where the BFS traversal takes place. While the queue is not empty, we dequeue the front element, append the corresponding element from the input array `nums` to the result, and enqueue the next elements based on the conditions. If `col` is at the leftmost position (0), we enqueue the element below if there is a row below. Additionally, if there is a column to the right, we enqueue the element to the right.\n\n**Step 3: Return Result**\n```python\n# Return the final result list\nreturn res\n```\n\n**Explanation:** Once the BFS traversal is complete, the function returns the final result list containing the elements traversed diagonally in the 2D array.\n\nIn summary, the algorithm utilizes BFS to traverse the given 2D array diagonally, starting from the top-left corner and moving towards the bottom-right corner. The result is stored in the `res` list, which is then returned.\n\n\n# Complexity\n- Time complexity: $$O(N)$$\n`N` is number of position we visit.\n\n- Space complexity: $$O(N)$$\n\n\n```python []\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n res = []\n q = deque([(0, 0)])\n \n while q:\n row, col = q.popleft()\n res.append(nums[row][col])\n\n if col == 0 and row + 1 < len(nums):\n q.append((row + 1, 0))\n\n if col + 1 < len(nums[row]):\n q.append((row, col + 1))\n\n return res\n```\n```javascript []\nvar findDiagonalOrder = function(nums) {\n const res = [];\n const q = [[0, 0]];\n\n while (q.length > 0) {\n const [row, col] = q.shift();\n res.push(nums[row][col]);\n\n if (col === 0 && row + 1 < nums.length) {\n q.push([row + 1, 0]);\n }\n\n if (col + 1 < nums[row].length) {\n q.push([row, col + 1]);\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n List<Integer> resList = new ArrayList<>();\n LinkedList<int[]> q = new LinkedList<>();\n q.offer(new int[]{0, 0});\n\n while (!q.isEmpty()) {\n int[] p = q.poll();\n resList.add(nums.get(p[0]).get(p[1]));\n\n if (p[1] == 0 && p[0] + 1 < nums.size()) {\n q.offer(new int[]{p[0] + 1, 0});\n }\n\n if (p[1] + 1 < nums.get(p[0]).size()) {\n q.offer(new int[]{p[0], p[1] + 1});\n }\n }\n\n // Convert List<Integer> to int[]\n int[] res = new int[resList.size()];\n for (int i = 0; i < resList.size(); i++) {\n res[i] = resList.get(i);\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int> res;\n queue<pair<int, int>> q;\n q.push({0, 0});\n\n while (!q.empty()) {\n auto p = q.front();\n q.pop();\n res.push_back(nums[p.first][p.second]);\n\n if (p.second == 0 && p.first + 1 < nums.size()) {\n q.push({p.first + 1, 0});\n }\n\n if (p.second + 1 < nums[p.first].size()) {\n q.push({p.first, p.second + 1});\n }\n }\n\n return res; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/arithmetic-subarrays/solutions/4321453/video-give-me-6-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/bE6YT9q16K8\n\n\u25A0 Timeline of the video\n`0:04` What does the formula mean?\n`1:46` Demonstrate how it works\n`3:39` Coding\n`5:40` Time Complexity and Space Complexity\n`6:06` Summary of the algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/count-nice-pairs-in-an-array/solutions/4312501/video-give-me-6-minutes-hashmap-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/424EOdu4TeY\n\n\u25A0 Timeline of the video\n\n`0:04` Think about how we calculate the answer\n`0:58` Demonstrate how it works\n`3:58` Coding\n`5:53` Time Complexity and Space Complexity\n`6:11` Summary of the algorithm with my solution code\n
7
0
['C++', 'Java', 'Python3', 'JavaScript']
0
diagonal-traverse-ii
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
cjavapythonjavascript-2-approaches-expla-imi8
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n\n#### Approach 1(Group Elements by the Sum of Row and Column Indices)\n1.
MarkSPhilip31
NORMAL
2023-11-22T10:12:26.041988+00:00
2023-12-10T18:59:48.337775+00:00
565
false
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n\n#### ***Approach 1(Group Elements by the Sum of Row and Column Indices)***\n1. **Initialization:**\n\n - **vector<int> ans;:** Initializes an empty vector to store the elements in diagonal order.\n - **unordered_map<int, vector<int>> m;:** Creates an unordered map where keys represent diagonal positions (`i + j`), and values are vectors to store elements corresponding to each diagonal.\n1. **Populating the Map:**\n\n - The nested loops iterate through the `nums` 2D vector.\n - **for(int i = nums.size() - 1; i >= 0; i--):** This loop starts from the bottom row and moves upwards.\n - **for(int j = 0; j < nums[i].size(); j++):** Iterates through the elements of each row i.\n - **m[i + j].push_back(nums[i][j]);:** Adds each element of `nums` to the corresponding diagonal in the map `m` based on the sum of row `i` and column `j`.\n1. **Creating the Diagonal Order:**\n\n - **int curr = 0;:** Initializes a variable `curr` to track the current diagonal position.\n - **while(m.find(curr) != m.end()) { ... }:** Loops until all diagonals are traversed. The existence of the key `curr` in the map `m` determines if there are elements for the current diagonal.\n - **for(auto a : m[curr]) { ans.push_back(a); }:** Retrieves elements from the `curr` diagonal in the map `m` and appends them to the `ans` vector.\n - **curr++;:** Moves to the next diagonal position.\n1. **Returning the Result:**\n\n - **return ans;:** Returns the vector `ans` containing elements in diagonal order.\n\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int> ans; // Resultant vector to store diagonal traversal\n unordered_map<int, vector<int>> m; // Map to store elements in diagonal fashion\n\n // Loop through the 2D vector to arrange elements in the map by diagonals\n for (int i = nums.size() - 1; i >= 0; i--) {\n for (int j = 0; j < nums[i].size(); j++) {\n // Store elements in the map using the sum of indices as the key\n // The sum of indices (i+j) represents each diagonal\n m[i + j].push_back(nums[i][j]);\n }\n }\n\n int curr = 0; // Current diagonal index\n\n // Traverse the map diagonally from the lowest index\n while (m.find(curr) != m.end()) {\n for (auto a : m[curr]) {\n ans.push_back(a); // Append elements to the result vector in diagonal order\n }\n curr++; // Move to the next diagonal\n }\n \n return ans; // Return the resultant diagonal traversal\n }\n};\n\n\n```\n\n```C []\nstruct Node {\n int value;\n struct Node* next;\n};\n\nstruct Node* newNode(int val) {\n struct Node* node = (struct Node*)malloc(sizeof(struct Node));\n node->value = val;\n node->next = NULL;\n return node;\n}\n\nvoid findDiagonalOrder(int** nums, int m, int* numsSizes) {\n struct Node* map[20005] = { NULL };\n\n for (int i = m - 1; i >= 0; i--) {\n for (int j = 0; j < numsSizes[i]; j++) {\n int key = i + j;\n struct Node* newNode = createNode(nums[i][j]);\n newNode->next = map[key];\n map[key] = newNode;\n }\n }\n\n for (int i = 0; i < 20005; i++) {\n struct Node* temp = map[i];\n while (temp) {\n printf("%d ", temp->value);\n temp = temp->next;\n }\n }\n}\n\n\n\n```\n```Java []\n\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n Map<Integer, List<Integer>> groups = new HashMap();\n int n = 0;\n for (int row = nums.size() - 1; row >= 0; row--) {\n for (int col = 0; col < nums.get(row).size(); col++) {\n int diagonal = row + col;\n if (!groups.containsKey(diagonal)) {\n groups.put(diagonal, new ArrayList<Integer>());\n }\n \n groups.get(diagonal).add(nums.get(row).get(col));\n n++;\n }\n }\n \n int[] ans = new int[n];\n int i = 0;\n int curr = 0;\n \n while (groups.containsKey(curr)) {\n for (int num : groups.get(curr)) {\n ans[i] = num;\n i++;\n }\n \n curr++;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n groups = defaultdict(list)\n for row in range(len(nums) - 1, -1, -1):\n for col in range(len(nums[row])):\n diagonal = row + col\n groups[diagonal].append(nums[row][col])\n \n ans = []\n curr = 0\n \n while curr in groups:\n ans.extend(groups[curr])\n curr += 1\n\n return ans\n\n\n```\n```javascript []\nfunction findDiagonalOrder(nums) {\n const map = {};\n\n for (let i = nums.length - 1; i >= 0; i--) {\n for (let j = 0; j < nums[i].length; j++) {\n const key = i + j;\n if (!(key in map)) {\n map[key] = [];\n }\n map[key].push(nums[i][j]);\n }\n }\n\n const result = [];\n for (let key in map) {\n result.push(...map[key]);\n }\n\n return result;\n}\n\n```\n\n---\n\n#### ***Approach 2(BFS)***\n\n1. **Initialization:**\n\n - **queue<pair<int, int>> queue:** Initialize a queue of pairs to store indices for the traversal.\n - **queue.push({0, 0}):** Start the traversal from the top-left corner by adding the indices (0, 0) to the queue.\n - **vector<int> ans:** Create a vector to store the elements in diagonal order.\n1. **Diagonal Traversal:**\n\n - The code utilizes a queue to traverse the 2D vector `nums` diagonally.\n - It pops elements from the queue and adds corresponding elements to the `ans` vector.\n - At each step:\n - Extract the current indices (`row, col`) from the front of the queue.\n - Push the corresponding element into the `ans` vector (`nums[row][col]`).\n1. **Determining Next Elements:**\n\n - Check conditions to determine the next indices for the queue:\n - If `col` is at the start of a row and there are rows below (`row + 1 < nums.size()`), move to the next row by pushing {`row + 1, col`} into the queue.\n - If there are more elements to the right in the current row (`col + 1 < nums[row].size()`), move to the next column by pushing {`row, col + 1`} into the queue.\n1. **Result:**\n\n- The function returns the `ans` vector, which contains the elements traversed in diagonal order.\n\n**Example:**\n00 \u2192 01 \u2192 02 \u2192 03\n\u2193\n10 \u2192 11 \u2192 12 \u2192 13\n\u2193\n20 \u2192 21 \u2192 22 \u2192 23\n\nWhen column is 0 then hit row + 1\n\nHow queue is changing ->\n00\n10 01\n20 11 02\n21 12 03\n22 13\n23\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(\u221An)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n queue<pair<int, int>> queue;\n queue.push({0, 0}); // Starting from the top-left corner\n vector<int> ans; // To store the diagonal elements\n \n while (!queue.empty()) {\n auto [row, col] = queue.front(); // Extract the current indices\n queue.pop(); // Remove the processed entry\n ans.push_back(nums[row][col]); // Store the current element\n \n if (col == 0 && row + 1 < nums.size()) {\n // If the column index is at the beginning and there are rows below, move to the next row\n queue.push({row + 1, col});\n }\n \n if (col + 1 < nums[row].size()) {\n // If there are elements to the right in the same row, move to the next column\n queue.push({row, col + 1});\n }\n }\n \n return ans; // Return the diagonal traversal\n }\n};\n\n```\n\n```C []\nstruct Pair {\n int row;\n int col;\n};\n\nstruct Node {\n struct Pair data;\n struct Node* next;\n};\n\nstruct Queue {\n struct Node *front, *rear;\n};\n\nstruct Node* newNode(int row, int col) {\n struct Node* temp = (struct Node*)malloc(sizeof(struct Node));\n temp->data.row = row;\n temp->data.col = col;\n temp->next = NULL;\n return temp;\n}\n\nstruct Queue* createQueue() {\n struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));\n q->front = q->rear = NULL;\n return q;\n}\n\nvoid enqueue(struct Queue* q, int row, int col) {\n struct Node* temp = newNode(row, col);\n\n if (q->rear == NULL) {\n q->front = q->rear = temp;\n return;\n }\n\n q->rear->next = temp;\n q->rear = temp;\n}\n\nvoid dequeue(struct Queue* q) {\n if (q->front == NULL) {\n return;\n }\n\n struct Node* temp = q->front;\n q->front = q->front->next;\n\n if (q->front == NULL) {\n q->rear = NULL;\n }\n\n free(temp);\n}\n\nint* findDiagonalOrder(int** nums, int numsSize, int* numsColSize, int* returnSize) {\n struct Queue* q = createQueue();\n enqueue(q, 0, 0);\n int* ans = (int*)malloc(sizeof(int) * 1000); // Assuming a maximum of 1000 elements\n int ansIdx = 0;\n\n while (q->front != NULL) {\n struct Pair current = q->front->data;\n dequeue(q);\n ans[ansIdx++] = nums[current.row][current.col];\n\n if (current.col == 0 && current.row + 1 < numsSize) {\n enqueue(q, current.row + 1, current.col);\n }\n\n if (current.col + 1 < numsColSize[current.row]) {\n enqueue(q, current.row, current.col + 1);\n }\n }\n\n *returnSize = ansIdx;\n return ans;\n}\n\n\n\n```\n```Java []\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n Queue<Pair<Integer, Integer>> queue = new LinkedList();\n queue.offer(new Pair(0, 0));\n List<Integer> ans = new ArrayList();\n \n while (!queue.isEmpty()) {\n Pair<Integer, Integer> p = queue.poll();\n int row = p.getKey();\n int col = p.getValue();\n ans.add(nums.get(row).get(col));\n \n if (col == 0 && row + 1 < nums.size()) {\n queue.offer(new Pair(row + 1, col));\n }\n \n if (col + 1 < nums.get(row).size()) {\n queue.offer(new Pair(row, col + 1));\n }\n }\n \n // Java needs conversion\n int[] result = new int[ans.size()];\n int i = 0;\n for (int num : ans) {\n result[i] = num;\n i++;\n }\n \n return result;\n }\n}\n\n\n```\n```python3 []\n\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n queue = deque([(0, 0)])\n ans = []\n \n while queue:\n row, col = queue.popleft()\n ans.append(nums[row][col])\n \n if col == 0 and row + 1 < len(nums):\n queue.append((row + 1, col))\n \n if col + 1 < len(nums[row]):\n queue.append((row, col + 1))\n \n return ans\n\n```\n```javascript []\nfunction findDiagonalOrder(nums) {\n const queue = [];\n queue.push([0, 0]);\n const ans = [];\n\n while (queue.length > 0) {\n const [row, col] = queue.shift();\n ans.push(nums[row][col]);\n\n if (col === 0 && row + 1 < nums.length) {\n queue.push([row + 1, col]);\n }\n\n if (col + 1 < nums[row].length) {\n queue.push([row, col + 1]);\n }\n }\n\n return ans;\n}\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
6
0
['Array', 'Breadth-First Search', 'C', 'Sorting', 'Heap (Priority Queue)', 'C++', 'Java', 'Python3', 'JavaScript']
1
diagonal-traverse-ii
Beats 100% || O(N) || EASY 🔥|| LINKED LIST || HASHMAP || BEGINNER FRIENDLY
beats-100-on-easy-linked-list-hashmap-be-xfsc
Intuition\n\nLINKED LIST || HASH MAP\n\n\n- Using linked list we can add the values to first or any position in a list.\n\n- We create a hash map then we add th
dineshd7
NORMAL
2023-11-22T03:34:51.917320+00:00
2023-11-22T03:38:47.863728+00:00
134
false
# Intuition\n\nLINKED LIST || HASH MAP\n\n\n- Using linked list we can add the values to first or any position in a list.\n\n- We create a hash map then we add the values to it from starting.\n\n- The list traversal is row wise.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) Auxiliary space (used for map).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Java Code\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n HashMap<Integer, LinkedList<Integer>> map = new HashMap<>(); \n int size = 0 ;\n for(int i = 0; i<nums.size(); i++){\n for(int j = 0; j<nums.get(i).size(); j++){\n size++;\n int level = i + j;\n if(!map.containsKey(level))\n map.put(level, map.getOrDefault(level,new LinkedList<>()));\n map.get(level).addFirst(nums.get(i).get(j));\n }\n }\n int[] an = new int[size];\n int J = 0;\n for(int i = 0; i<map.size(); i++){\n for(int j = 0; j<map.get(i).size(); j++){\n an[J++] = map.get(i).get(j);\n }\n }\n return an;\n }\n}\n```\n# C++ Code\n```\n\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n unordered_map<int, list<int>> map;\n int size = 0;\n for (int i = 0; i < nums.size(); i++) {\n for (int j = 0; j < nums[i].size(); j++) {\n size++;\n int level = i + j;\n if (map.find(level) == map.end()) {\n map[level] = list<int>();\n }\n map[level].push_front(nums[i][j]);\n }\n }\n vector<int> an(size);\n int J = 0;\n for (int i = 0; i < map.size(); i++) {\n for (int j : map[i]) {\n an[J++] = j;\n }\n }\n return an;\n }\n};\n\n```\n# Python Code\n```\nclass Solution:\n def findDiagonalOrder(self, nums):\n map = {} \n size = 0\n for i in range(len(nums)):\n for j in range(len(nums[i])):\n size += 1\n level = i + j\n if level not in map:\n map[level] = map.get(level, [])\n map[level].insert(0, nums[i][j])\n an = [0] * size\n J = 0\n for i in range(len(map)):\n for j in range(len(map[i])):\n an[J] = map[i][j]\n J += 1\n return an\n```\n\n![upvote.jpeg](https://assets.leetcode.com/users/images/0da044d7-94ef-4870-8cf1-8a394465b331_1700624261.059164.jpeg)
6
0
['Hash Table', 'Linked List', 'C', 'Python', 'C++', 'Java', 'Python3']
0
diagonal-traverse-ii
Python - dict, deque, and chain star
python-dict-deque-and-chain-star-by-hong-vtbj
\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n res = defaultdict(deque)\n for i, row in enumerate(nums)
hong_zhao
NORMAL
2023-11-22T00:35:51.812236+00:00
2023-11-22T00:40:41.295155+00:00
732
false
```\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n res = defaultdict(deque)\n for i, row in enumerate(nums):\n for j, x in enumerate(row):\n res[i + j].appendleft(x)\n return chain(*res.values())\n```
6
1
['Python3']
1
diagonal-traverse-ii
Simple java bfs solution
simple-java-bfs-solution-by-raghu6306766-gccj
class Solution {\n \n\tpublic class Coordinate{\n int x , y;\n Coordinate(int x , int y){\n this.x = x;\n this.y = y;\n
raghu6306766
NORMAL
2021-11-05T10:22:24.787710+00:00
2021-11-05T10:22:24.787742+00:00
852
false
class Solution {\n \n\tpublic class Coordinate{\n int x , y;\n Coordinate(int x , int y){\n this.x = x;\n this.y = y;\n }\n }\n \n public boolean isValidCoordinate(int x , int y , List<List<Boolean>> visited){\n return x < visited.size() && y < visited.get(x).size() && !visited.get(x).get(y);\n }\n \n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n Queue<Coordinate> queue = new LinkedList<>();\n List<List<Boolean>> visited = new ArrayList<>();\n List<Integer> res = new ArrayList<>();\n \n for(int i = 0 ; i < nums.size() ; i++){\n List<Boolean> row = new ArrayList<>();\n \n for(int j = 0 ; j < nums.get(i).size() ; j++) row.add(false);\n \n visited.add(row);\n }\n \n queue.add(new Coordinate(0,0));\n visited.get(0).set(0 , true);\n \n while(!queue.isEmpty()){\n Coordinate curr = queue.poll();\n \n res.add(nums.get(curr.x).get(curr.y));\n \n if(isValidCoordinate(curr.x + 1 , curr.y , visited)){\n queue.add(new Coordinate(curr.x + 1 , curr.y));\n visited.get(curr.x + 1).set(curr.y , true);\n }\n \n if(isValidCoordinate(curr.x , curr.y + 1 , visited)){\n queue.add(new Coordinate(curr.x , curr.y + 1));\n visited.get(curr.x).set(curr.y + 1 , true);\n }\n }\n \n \n return res.stream().mapToInt(i -> i).toArray();\n }\n}
6
0
['Breadth-First Search', 'Java']
0
diagonal-traverse-ii
【Video】BFS & Queue
video-bfs-queue-by-niits-djan
Intuition\nUsing BFS\n\n---\n\n# Solution Video\n\nhttps://youtu.be/4wkt4kGip64\n\n\u25A0 Timeline of the video\n0:04 How we think about a solution\n1:08 How ca
niits
NORMAL
2024-04-25T00:39:19.107536+00:00
2024-04-25T00:39:19.107557+00:00
107
false
# Intuition\nUsing BFS\n\n---\n\n# Solution Video\n\nhttps://youtu.be/4wkt4kGip64\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`1:08` How can you put numbers into queue with right order?\n`2:34` Demonstrate how it works\n`6:24` Summary of main idea\n`6:47` Coding\n`8:40` Time Complexity and Space Complexity\n`8:57` Summary of the algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,180\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n## How we think about a solution\n\nWe know order of output, so problem is that how we can take target numbers with the right order.\n\nLet\'s use Example 2 and make input array small.\n\n```\nInput: nums = [[1,2,3],[4],[5,6]]\n\n1,2,3\n4, ,\n5,6,\n```\n```\nOutput:[1,4,2,5,3,6]\n```\nWe can see that by changing our perspective on the array, we can traverse it in a manner similar to BFS.\n\n```\n 1\n 4 2\n 5 3\n 6\n```\nThat\'s why we use `Queue` to solve the problem.\n\n- How we can put numbers into queue with right order?\n\n```\n1,2,3\n4, ,\n5,6,\n```\nAcutually, we keep row and col position of each number in `queue` to calculate neighbor positions.\n\nAs you may know typical BFS, we put left child and right child into queue from parent, so when we traverse `1`, we try to put next positions in the next line staring with `4` into `queue`.\n\nBasically, we put current `right` position into `queue`, because we know that right adjacent number is a number for next line. But how can we jump to the next line?\n\nIn the example above, we want to traverse `1,4,2,5,3,6`. In other words, how can you start new lines? For example, from `2` to `5`.\n\nMy answer is when we are `col = 0`, we put a `bottom` position first, then check `right` position, so that we can start new lines with numbers in `col \n= 0`.\n\nLet\'s see one by one.\n\n```\n1,2,3\n4, ,\n5,6,\n\nq = [(0,0)] (= (0,0) is start position)\n\n(0,0): 1\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 0\nq = []\nres = [1] \n\nNow col = 0, so add bottom position to queue\nq = [(1,0)]\n\nThen check right side, find 2. Add position to queue\nq = [(1,0),(0,1)]\n\n(1,0): 4\n(0,1): 2\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 1\ncol = 0\nq = [(0,1)]\nres = [1,4] \n\nNow col = 0, so add bottom position to queue\nq = [(0,1),(2,0)]\n\nThen check right side, there is no number, so skip\nq = [(0,1),(2,0)]\n\n(0,1): 2\n(2,0): 5\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 1\nq = [(2,0)]\nres = [1,4,2] \n\nNow col != 0, so skip\nq = [(2,0)]\n\nThen check right side, find 3. Add position to queue\nq = [(2,0),(0,2)]\n\n(2,0): 5\n(0,2): 3\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 2\ncol = 0\nq = [(0,2)]\nres = [1,4,2,5]\n\nNow col = 0, but next bottom(3,0) is out of bounds, so skip\nq = [(0,2)]\n\nThen check right side, Find 6. Add position to queue\nq = [(0,2),(2,1)]\n\n(0,2): 3\n(2,1): 6\n```\nAt bottom from row 2, col = 0, there is no number but there is 6 on the right side. so this 6 will be start number in the next line.\n\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 0\ncol = 2\nq = [(2,1)]\nres = [1,4,2,5,3]\n\nNow col != 0, so skip\nq = [(2,1)]\n\nThen check right side, there is no number, so skip\nq = [(2,1)]\n\n```\nTake the most left data in `queue`.\n```\n1,2,3\n4, ,\n5,6,\n\nrow = 2\ncol = 1\nq = []\nres = [1,4,2,5,3,6]\n\nNow col != 0, so skip\nq = []\n\nThen check right side, there is no number, so skip\nq = []\n\n```\n\n```\nOutput: [1,4,2,5,3,6]\n```\n\n---\n\n\u2B50\uFE0F Points\n\n- When col is equal to 0, then check bottom position, so that we can start new lines with right order\n- Check right position from every position\n\n---\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm!\n\n\n### Algorithm Overview:\n1. Initialization\n2. BFS Traversal\n3. Return Result\n\n### Detailed Explanation:\n\n**Step 1: Initialization**\n```python\n# Create an empty list to store the result\nres = []\n\n# Initialize a queue with the starting point (0, 0)\nq = deque([(0, 0)])\n```\n\n**Explanation:** In this step, we set up the data structures needed for the algorithm. The `res` list will store the final result, and the `q` queue will be used for the breadth-first search (BFS) traversal. We start the traversal from the top-left corner, so the initial point `(0, 0)` is enqueued.\n\n**Step 2: BFS Traversal**\n```python\n# While the queue is not empty, perform the following steps\nwhile q:\n # Dequeue the front element\n row, col = q.popleft()\n\n # Append the current element to the result\n res.append(nums[row][col])\n\n # Enqueue the next element below if applicable\n if col == 0 and row + 1 < len(nums):\n q.append((row + 1, 0))\n\n # Enqueue the next element to the right if applicable\n if col + 1 < len(nums[row]):\n q.append((row, col + 1))\n```\n\n**Explanation:** This is the core of the algorithm, where the BFS traversal takes place. While the queue is not empty, we dequeue the front element, append the corresponding element from the input array `nums` to the result, and enqueue the next elements based on the conditions. If `col` is at the leftmost position (0), we enqueue the element below if there is a row below. Additionally, if there is a column to the right, we enqueue the element to the right.\n\n**Step 3: Return Result**\n```python\n# Return the final result list\nreturn res\n```\n\n**Explanation:** Once the BFS traversal is complete, the function returns the final result list containing the elements traversed diagonally in the 2D array.\n\nIn summary, the algorithm utilizes BFS to traverse the given 2D array diagonally, starting from the top-left corner and moving towards the bottom-right corner. The result is stored in the `res` list, which is then returned.\n\n\n# Complexity\n- Time complexity: $$O(N)$$\n`N` is number of position we visit.\n\n- Space complexity: $$O(N)$$\n\n\n```python []\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n res = []\n q = deque([(0, 0)])\n \n while q:\n row, col = q.popleft()\n res.append(nums[row][col])\n\n if col == 0 and row + 1 < len(nums):\n q.append((row + 1, 0))\n\n if col + 1 < len(nums[row]):\n q.append((row, col + 1))\n\n return res\n```\n```javascript []\nvar findDiagonalOrder = function(nums) {\n const res = [];\n const q = [[0, 0]];\n\n while (q.length > 0) {\n const [row, col] = q.shift();\n res.push(nums[row][col]);\n\n if (col === 0 && row + 1 < nums.length) {\n q.push([row + 1, 0]);\n }\n\n if (col + 1 < nums[row].length) {\n q.push([row, col + 1]);\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n List<Integer> resList = new ArrayList<>();\n LinkedList<int[]> q = new LinkedList<>();\n q.offer(new int[]{0, 0});\n\n while (!q.isEmpty()) {\n int[] p = q.poll();\n resList.add(nums.get(p[0]).get(p[1]));\n\n if (p[1] == 0 && p[0] + 1 < nums.size()) {\n q.offer(new int[]{p[0] + 1, 0});\n }\n\n if (p[1] + 1 < nums.get(p[0]).size()) {\n q.offer(new int[]{p[0], p[1] + 1});\n }\n }\n\n // Convert List<Integer> to int[]\n int[] res = new int[resList.size()];\n for (int i = 0; i < resList.size(); i++) {\n res[i] = resList.get(i);\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int> res;\n queue<pair<int, int>> q;\n q.push({0, 0});\n\n while (!q.empty()) {\n auto p = q.front();\n q.pop();\n res.push_back(nums[p.first][p.second]);\n\n if (p.second == 0 && p.first + 1 < nums.size()) {\n q.push({p.first + 1, 0});\n }\n\n if (p.second + 1 < nums[p.first].size()) {\n q.push({p.first, p.second + 1});\n }\n }\n\n return res; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/arithmetic-subarrays/solutions/4321453/video-give-me-6-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/bE6YT9q16K8\n\n\u25A0 Timeline of the video\n`0:04` What does the formula mean?\n`1:46` Demonstrate how it works\n`3:39` Coding\n`5:40` Time Complexity and Space Complexity\n`6:06` Summary of the algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/count-nice-pairs-in-an-array/solutions/4312501/video-give-me-6-minutes-hashmap-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/424EOdu4TeY\n\n\u25A0 Timeline of the video\n\n`0:04` Think about how we calculate the answer\n`0:58` Demonstrate how it works\n`3:58` Coding\n`5:53` Time Complexity and Space Complexity\n`6:11` Summary of the algorithm with my solution code\n
5
0
['C++', 'Java', 'Python3', 'JavaScript']
0
diagonal-traverse-ii
👨‍🎤🤕👨‍🦽Beats 100% 🤜 VS 🤛 Clean Code 🧹🧼🛀
beats-100-vs-clean-code-by-navid-7aka
\n\n\n\n\n# Why does this beat 100% (or sometimes 99% depending on LeetCode Mode)?\n\nWe don\'t waste any time more than necessary and use the proper data struc
navid
NORMAL
2023-11-22T09:28:00.916130+00:00
2023-11-22T09:29:02.792013+00:00
319
false
\n![dont understand.gif](https://assets.leetcode.com/users/images/eee22bf8-c02f-48a7-9fd9-7656f75a2b07_1700638758.1678243.gif)\n\n\n\n# Why does this beat 100% (or sometimes 99% depending on LeetCode Mode)?\n\nWe don\'t waste any time more than necessary and use the proper data structure\n\n# Can you be more concrete than that?\nWe read all the elements of the input with the good old 2 for loops:\n```\n for (int i = 0; i < nums.size(); ++i) {\n List<Integer> list = nums.get(i);\n int size = list.size()\n for (int j = 0; j < size; ++j) \n```\n\n# That\'s it?\nWe find the sum of `i `and `j`. \n\n```\nint sum = i + j;\n\n```\n# So what?\nLet me ask you a question: What do elements that are in the same diagonal have in common?\n\n# What do you mean?\nLet\'s look at the first example of the description. What are the sum of i and j for elements in blue [7, 5, 3]\n\n\n\n![image.png](https://assets.leetcode.com/users/images/4477c4de-ef16-4b4c-a319-c3db756c004b_1700635411.1813872.png)\n\n# 2 + 0 = 1 + 1 = 2 + 0 = 2\nSo what\'s the relationship between them?\n\n\n# The sum of i and j is the same?\n\nExactly! Now we just need to store those pieces of information.\n\n# How can we store them?\nWe can store them in a `Map<Integer, List<Integer>>` \n\n# What\'s the key in that Map?\nIt\'s the sum\n\n# And what\'s that `List<Integer>` in the value?\nList of all elements whose i+j was equal to the key\n\n# Wait, I see `Map<Integer, List<Integer>>` in your Clean Code; but where is the Map in the fast version?\nGood catch! And that\'s the trick: `List<List<Integer>>` in practice is faster than `Map<Integer, List<Integer>>` although, on paper, the time complexity is the same.\n\n# So how do you figure out what is the sum in `List<List<Integer>>`?\nIn `List<List<Integer>>` the index of the first list is the sum.\n\n# Can you give an example?\n\nOf course: Let\'s assume our input is:\n```\n[\n [7,8]\n [9]\n]\n```\nfor 7 `i` is 0 and `j` is 0 so the sum is 0.\nfor 8 `i` is 0 and `j` is 1 so the sum is 1.\nfor 9 `i` is 1 and `j` is 0 so the sum is 1.\n\nConsequently, we move 7 to the bucket with index 0 and move 9 and 8 to the bucket with index 1. So the resulting buckets will look like:\n`[7][9,8]`\n\n# What\'s the Time Complexity?\n- O(n)\nLet\'s assume we have n elements in total. In the first round (for building the bucketedLists (which is called `sumToElements` in the clean code and `sums` in the fast version)), we check each of the `n` elements once. During the second round (moving the elements from the bucketedLists we created previously, to the result array) we check each element once again. So in total we spent 2*n = O(n) time.\n\n# What\'s the Space Complexity?\n- O(n)\nWe stored the n elements in our bucketedLists.\n\n\n# In the fast version, why are most variables one character?\nI tried with both long and short variable names and based on my limited experience, the code with shorter variable names tends to run faster.\n\n\n# So during the interview we should use the faster version instead of Clean Code?\n\n![NO.gif](https://assets.leetcode.com/users/images/6ab008a3-1014-4e33-b86c-a973ab177f3e_1700638147.2348614.gif)\n\nAs someone who got job offers from giant tech companies and worked there as the interviewer my biggest request is: **PLEASE** make your code as readable as possible!\n\n\n# Clean Code:\n<!-- Describe your first thoughts on how to solve this problem. -->\n```\nint numberOfElements = 0;\n\npublic int[] findDiagonalOrder(List<List<Integer>> nums) {\n Map<Integer, List<Integer>> sumToElements = getListOfSums(nums);\n return getResult(sumToElements);\n}\n\nprivate Map<Integer, List<Integer>> getListOfSums(List<List<Integer>> nums) {\n Map<Integer, List<Integer>> sumToElements = new HashMap<>();\n for (int i = 0; i < nums.size(); ++i) {\n List<Integer> row = nums.get(i);\n int size = row.size();\n numberOfElements += size;\n for (int j = 0; j < size; ++j) {\n updateMap(sumToElements, row, i, j);\n }\n }\n return sumToElements;\n}\n\nprivate void updateMap(Map<Integer, List<Integer>> sumToElements, List<Integer> row, int i, int j) {\n int sum = i + j;\n if (!sumToElements.containsKey(sum)) {\n sumToElements.put(sum, new ArrayList<>());\n }\n sumToElements.get(sum).add(row.get(j));\n}\n\nprivate int[] getResult(Map<Integer, List<Integer>> sumToElements) {\n int[] result = new int[numberOfElements];\n int count = 0;\n for (int i = 0; count < numberOfElements; i++) {\n if (sumToElements.containsKey(i)) {\n List<Integer> elements = sumToElements.get(i);\n for (int j = elements.size() - 1; j >= 0; j--) {\n result[count++] = elements.get(j);\n }\n }\n }\n return result;\n}\n\n```\n# Beats 100% (and sometimes 99% depending on LeetCode\'s Mood):\n![image.png](https://assets.leetcode.com/users/images/895e67f0-2c81-4e10-85b2-bef555516ffd_1700640747.910576.png)\n\n```\npublic int[] findDiagonalOrder(List<List<Integer>> nums) {\n int n = 0;\n List<List<Integer>> sums = new ArrayList<>();\n for (int i = 0; i < nums.size(); ++i) {\n List<Integer> l = nums.get(i);\n int size = l.size();\n n += size;\n for (int j = 0; j < size; ++j) {\n int sum = i + j;\n if (sums.size() == sum)\n sums.add(new ArrayList<>());\n sums.get(sum).add(l.get(j));\n }\n }\n int[] res = new int[n];\n int k = -1;\n for (List<Integer> l : sums)\n for (int j = l.size() - 1; j >= 0; --j)\n res[++k] = l.get(j);\n return res;\n}\n```\n\n# Please comment below and let me know if you have any questions or positive or negative feedback. Is there anything I can do to make your life better?
5
0
['Java']
0
diagonal-traverse-ii
C++/Python, bucket solution with explanation
cpython-bucket-solution-with-explanation-p6xf
bucket\n\nFor each diagonal line, sum of each coordinate on the same line are the same.\nSo, create m + n - 1 buckets, where m is number of row, n is max length
shun6096tw
NORMAL
2023-11-22T05:57:30.589954+00:00
2023-11-24T00:40:12.889767+00:00
183
false
### bucket\n![image](https://assets.leetcode.com/users/images/b90e1113-c256-472a-8f9c-74fe2d88fdb7_1700631634.3053236.png)\nFor each diagonal line, sum of each coordinate on the same line are the same.\nSo, create m + n - 1 buckets, where m is number of row, n is max length of a column,\nwhen we traverse array, put an element to a bucket whose index is sum of coordinate of the element.\n\nTo keep element order, traverse array from bottom to top and left to right.\ntc is O(total element in array), sc is O(total element in array)\n\n### python\n```python\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n m = len(nums)\n n = max(len(x) for x in nums)\n bucket = [[] for _ in range(m+n-1)]\n for i in range(m-1, -1, -1):\n for j, x in enumerate(nums[i]):\n bucket[i+j].append(x)\n ans = []\n for x in bucket: ans += x\n return ans\n```\n\n### c++\n```cpp\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int m = nums.size();\n int n = 0;\n for (auto& x: nums) n = max(n, (int) x.size());\n \n vector<vector<int>> bucket (m+n-1);\n for (int i = m-1; i >= 0; i-=1) {\n for (int j = 0; j < nums[i].size(); j+=1)\n bucket[i+j].emplace_back(nums[i][j]);\n }\n \n vector<int> ans;\n for (auto& x: bucket) {\n for (int& y: x) ans.emplace_back(y);\n }\n return ans;\n }\n};\n```
5
0
['C', 'Python']
0
diagonal-traverse-ii
Java One-Liner Using Streams API (Unreadable)
java-one-liner-using-streams-api-unreada-8p3o
Intro\nWe are going to assume that you have seen the other solutions. This was my initial solution.\n\nclass Solution {\n public int[] findDiagonalOrder(List
ayazmost
NORMAL
2023-11-22T05:09:31.342610+00:00
2023-11-22T05:11:56.958039+00:00
438
false
# Intro\nWe are going to assume that you have seen the other solutions. This was my initial solution.\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n ArrayList<int[]> list = new ArrayList<>();\n for (int i = 0; i < nums.size(); i++) {\n for (int j = 0; j < nums.get(i).size(); j++) {\n list.add(new int[]{nums.get(i).get(j), i, j});\n }\n }\n\n Collections.sort(list, (a,b) -> {\n int result = Integer.compare(a[1] + a[2], b[1] + b[2]);\n if (result == 0) result = Integer.compare(b[1], a[1]);\n if (result == 0) result = Integer.compare(a[2], b[2]);\n return result;\n });\n\n int[] array = new int[list.size()];\n for (int i = 0; i < list.size(); i++) {\n array[i] = list.get(i)[0];\n }\n return array;\n }\n}\n```\n\n# Breakdown\nWe can break our initial code down into 3 steps.\n- Compress the matrix into a list of int arrays, each array containing the original value, $i$, and $j$.\n- Sorting the list such that we prioritize $(i+j)$, falling back to the $i$ (descending) and finally to the $j$ (ascending).\n- Convert the list of int arrays into a int array, discarding $i$ and $j$.\n\nWe can easily do all of this with streams!\n\n# Construction\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n return IntStream.range(0, nums.size()).mapToObj(i->IntStream.range(0, nums.get(i).size()).mapToObj(j->new int[]{nums.get(i).get(j), i, j})).flatMap(Function.identity()).sorted((a,b) -> Integer.compare(a[2], b[2])).sorted((a,b) -> Integer.compare(b[1], a[1])).sorted((a,b) -> Integer.compare(a[1] + a[2], b[1] + b[2])).mapToInt(i->i[0]).toArray();\n }\n}\n```\nFirst, we need to make the list of int arrays. We need to preserve the indices, so a simple nums.stream() won\'t work. Instead, we use an `IntStream.range(0, nums.size())`. We want to convert those indices into a int array with 3 values, so we can use the `mapToObj` method. But right now, we only have $i$. So to get $j$, we just do the same thing as we did to $i$. We do a `IntStream.range(0, nums.get(i).size)` inside of our mapToObj! After that, we will have a `Stream<Stream<int[]>>`. We want to deal with a `Stream<int[]>` instead, so we can use the `flatMap` method to make that true.\n\nNow that the hardest step is done, we can get to the second step, sorting the arrays. We can do that with the `sorted` method. Now we could make a good compareTo function lambda with `{}`, but that would break the one-line constraint. So instead, we can take advantage of the fact that sorting objects in Java is stable, meaning that if two things have the same value in the compareTo, their relative order will stay the same. So, if we first sort on the least important conditions, then eventually everything will fall into place.\n\nFinally, we just have to convert our `Stream<int[]>` into a `int[]`, only including the values and not the indices, this can be done by mapping the values using `mapToInt`, then finally using a `toArray`.\n\n# Complexity\n- Time complexity: $O(n\\log{n})$ from merge sort.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: $O(n\\log{n})$ from merge sort.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Conclusion\nYou would never write code this way. But hopefully you learned something new about the Java Streams API.\n\n
5
0
['Java']
3
diagonal-traverse-ii
Kotlin List of Diagonals, O(n) Runtime and Space
kotlin-list-of-diagonals-on-runtime-and-448o5
Intuition\nIterating through the existing list in diagonal fashion isn\'t that difficult, but since it is not uniform width, there are large gaps that will have
jschnall
NORMAL
2023-11-22T02:50:11.549885+00:00
2023-11-22T03:10:26.680079+00:00
68
false
# Intuition\nIterating through the existing list in diagonal fashion isn\'t that difficult, but since it is not uniform width, there are large gaps that will have to be traversed, which is inefficient. This could be mitigated somewhat by finding the row(s) with the maxWidth to break out of loops earlier, but it seemed tricky to optimize, if I even could make it efficient enough.\n\n# Approach\nI spent a moment looking at the matrix, and realized I could determine in advance, which diagonal each item would be in, and their order in the diagonal. This meant I could just make a new list of each diagonal without gaps, and then traverse that.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ where n is the total number of items in the matrix. We iterate through the matrix once to build the list of diagonals. I\'m not sure the runtime of flatten, but assume the worst case would also be just $$O(n)$$.\n\n- Space complexity:\n$$O(n)$$ where n is the total number of ints in the matrix, since we\'re storing another copy if each int in diags, which has been reordered. If we had some sort of large objects instead of ints though we could just store a pair of indices to the original array as an improvement. \n\n# Code\n```\nclass Solution {\n fun findDiagonalOrder(nums: List<List<Int>>): IntArray {\n val diags = mutableListOf<MutableList<Int>>()\n nums.forEachIndexed { j, row ->\n row.forEachIndexed { i, num ->\n val index = j + i\n if (index >= diags.size) {\n diags.add(mutableListOf())\n }\n diags[index].add(0, num)\n }\n }\n return diags.flatten().toIntArray()\n }\n}\n```
5
0
['Kotlin']
0
diagonal-traverse-ii
🌊Enhanced Diagonal Traversal of 2D Arrays: Handling, Directional Options, and Space Optimization⚡️
enhanced-diagonal-traversal-of-2d-arrays-4fbe
Intuition\nGiven a 2D array, to traverse it in diagonal order means moving along the diagonals, starting from the top-left corner, going down to the bottom-righ
deleted_user
NORMAL
2023-11-22T02:00:41.886719+00:00
2023-11-22T02:00:41.886740+00:00
373
false
# Intuition\nGiven a 2D array, to traverse it in diagonal order means moving along the diagonals, starting from the top-left corner, going down to the bottom-right corner, and covering elements in a zigzag pattern.\n\n# Approach\n1. Diagonal Mapping: Create a mapping where each diagonal has its list of elements. To identify each diagonal, use the sum of indices (row + column) to group elements.\n2. Traversal and Collection: Traverse the 2D array and fill the diagonal mapping.\n3. Extract Elements: Iterate through the mapping diagonally, retrieving elements in the desired order.\n4. Return: Return the collected elements as the final output.\nplaintext\nCopy code\n# Example:\n Input: [[1,2,3],\n [4,5,6],\n [7,8,9]]\n\n Diagonal Mapping:\n Diagonal 0: [1]\n Diagonal 1: [2, 4]\n Diagonal 2: [3, 5, 7]\n Diagonal 3: [6, 8]\n Diagonal 4: [9]\n\n Extracted Elements in Diagonal Order: [1, 2, 4, 7, 5, 3, 6, 8, 9]\n\n\n# Complexity\n- Traversing the 2D array to create the diagonal mapping takes O(rows * columns) time.\n- Extracting elements from the mapping and collecting them takes O(rows + columns) time.\n- Hence, the overall time complexity is O(rows * columns).\n- Space Complexity:\n- Additional space for the diagonal mapping is required, which can take up to O(rows + columns) space.\n- The space complexity is O(rows + columns) for the mapping and output.\n\n# Error Handling:\nAdd error handling for invalid inputs such as empty arrays or arrays with inconsistent lengths of rows.\n# Allow Starting Point Specification:\nEnable the option to start the diagonal traversal from a specific point other than the top-left corner of the matrix.\n# Directional Diagonal Traversal:\nImplement the capability to traverse the diagonals in the opposite direction (from bottom-left to top-right) apart from the current top-left to bottom-right approach.\n# Diagonal Grouping:\nGroup the elements within each diagonal in a specific order (ascending or descending) instead of just reverse-order extraction within each diagonal.\n# Optimizing Space:\nConsider optimizing the space complexity by using a dictionary or hashmap instead of a list for diagonal mapping, which will reduce the space needed for sparse matrices.\n# Performance Optimization:\nOptimize the code for better performance by minimizing unnecessary loops or using more efficient data structures where applicable.\n# Visualization:\nCreate a visualization of the diagonal traversal process to better understand how elements are traversed diagonally across the 2D array.\n# Additional Output Formats:\nProvide output in various formats, such as a matrix representation of the diagonals or a list of lists representing each diagonal separately.\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Code\n``` Python []\nclass Solution(object):\n def findDiagonalOrder(self, nums):\n m = len(nums)\n maxSum, size, index = 0, 0, 0\n map = [[] for _ in range(100001)]\n \n for i in range(m):\n size += len(nums[i])\n for j in range(len(nums[i])):\n _sum = i + j\n map[_sum].append(nums[i][j])\n maxSum = max(maxSum, _sum)\n \n res = [0] * size\n for i in range(maxSum + 1):\n cur = map[i]\n for j in range(len(cur) - 1, -1, -1):\n res[index] = cur[j]\n index += 1\n \n return res\n \n```\n``` C++ []\n#include <vector>\n#include <algorithm>\n\nclass Solution {\npublic:\n std::vector<int> findDiagonalOrder(std::vector<std::vector<int>>& nums) {\n int m = nums.size();\n int maxSum = 0, size = 0, index = 0;\n std::vector<std::vector<int>> mapping(100001);\n \n for (int i = 0; i < m; ++i) {\n size += nums[i].size();\n for (int j = 0; j < nums[i].size(); ++j) {\n int _sum = i + j;\n mapping[_sum].push_back(nums[i][j]);\n maxSum = std::max(maxSum, _sum);\n }\n }\n \n std::vector<int> res(size);\n for (int i = 0; i <= maxSum; ++i) {\n auto& cur = mapping[i];\n for (int j = cur.size() - 1; j >= 0; --j) {\n res[index++] = cur[j];\n }\n }\n \n return res;\n }\n};\n\n```\n``` Python3 []\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n m = len(nums)\n maxSum, size, index = 0, 0, 0\n map = [[] for _ in range(100001)]\n \n for i in range(m):\n size += len(nums[i])\n for j in range(len(nums[i])):\n _sum = i + j\n map[_sum].append(nums[i][j])\n maxSum = max(maxSum, _sum)\n \n res = [0] * size\n for i in range(maxSum + 1):\n cur = map[i]\n for j in range(len(cur) - 1, -1, -1):\n res[index] = cur[j]\n index += 1\n \n return res\n```\n
5
0
['Python']
1
diagonal-traverse-ii
[C++] || Sum of indices is same for all diagonal elements
c-sum-of-indices-is-same-for-all-diagona-lbav
For each sum of indices i + j store their corresponding elements in a map.\n\n* Traverse the map from least sum to max sum and print elements in reverse manner.
rahul921
NORMAL
2022-08-11T05:28:10.083698+00:00
2022-08-11T05:28:52.941037+00:00
773
false
* For each sum of indices `i + j` store their corresponding elements in a map.\n\n* Traverse the map from least sum to max sum and print elements in reverse manner.\n```\nclass Solution {\npublic:\n unordered_map<int,vector<int>> mpp ;\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n int c = 0 ;\n vector<int> ans ;\n for(auto &x : nums) c = max(c, (int)x.size()) ;\n \n for(int i = 0 ; i < nums.size() ; ++i ){\n for(int j = 0 ; j < nums[i].size() ; ++j ){\n int sum = i + j ;\n mpp[sum].push_back(nums[i][j]);\n }\n }\n \n for(int sum = 0 ; sum <= (nums.size() - 1 + c - 1) ; ++sum){\n for(int i = mpp[sum].size() - 1 ; i >= 0 ; --i) ans.push_back(mpp[sum][i]) ;\n }\n \n return ans ;\n \n \n }\n};\n```
5
0
['C']
0
diagonal-traverse-ii
Java | Picture included | One pass | Easy Hashmap Solution
java-picture-included-one-pass-easy-hash-yche
\n\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n if(nums==null || nums.size()==0) return null;\n \n H
U99Omega
NORMAL
2021-04-26T18:37:20.451244+00:00
2021-04-26T18:37:20.451277+00:00
336
false
![image](https://assets.leetcode.com/users/images/05079bce-abbc-40fd-98f7-722f44e940be_1619462008.5180125.png)\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n if(nums==null || nums.size()==0) return null;\n \n HashMap<Integer,ArrayList<Integer>> map=new HashMap<>();\n int count=0;\n \n for(int i=nums.size()-1;i>=0;i--){\n count+=nums.get(i).size();\n for(int j=0;j<nums.get(i).size();j++){\n if(!map.containsKey(i+j)){\n map.put(i+j,new ArrayList<Integer>());\n }\n map.get(i+j).add(nums.get(i).get(j));\n }\n }\n \n int size=map.size();\n int mapIndex=0;\n int arrIndex=0;\n \n int arr[]=new int[count];\n \n while(mapIndex<size){\n for(int i:map.get(mapIndex)){\n arr[arrIndex++]=i;\n }\n mapIndex++;\n }\n return arr;\n }\n}\n\n```
5
1
['Java']
0
diagonal-traverse-ii
Think of the grid as a binary tree, then do a row traversal
think-of-the-grid-as-a-binary-tree-then-wuwgu
Think of the grid as a binary tree. The square at (0, 0) is the root.\n\nUsing the example from the description, let\'s visualise a few nodes. \nThe number 1 is
timothyleong97
NORMAL
2020-12-25T10:29:16.028796+00:00
2020-12-25T14:08:57.304306+00:00
461
false
Think of the grid as a binary tree. The square at `(0, 0)` is the root.\n![image](https://assets.leetcode.com/users/images/d57bc1a9-af12-4d7d-951d-8ab8702a6dd2_1608891890.0055323.png)\nUsing the example from the description, let\'s visualise a few nodes. \nThe number `1` is the root of the tree.\n`6` and `2` are it\'s left and right child.\n`8` and `7` are the left and right child of `6`.\n\nThis problem reduces to doing a row traversal of a binary tree.\n\nCode below:\n```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n LinkedList<int[]> queue = new LinkedList<>();\n queue.offer(new int[]{0, 0});\n final int num_rows = nums.size();\n int elems = 0;\n for (var lst : nums) {\n elems += lst.size();\n }\n int[] res = new int[elems];\n int res_idx = 0;\n \n while (!queue.isEmpty()) {\n final int size = queue.size();\n for (int i = 0; i < size; ++i) {\n int[] next = queue.poll();\n \n // extract row and col index\n int row = next[0];\n int col = next[1];\n \n // check if this number has already been visited\n var curr_list = nums.get(row);\n if (curr_list.get(col) == Integer.MAX_VALUE) continue;\n \n // add the number you are at to your array\n res[res_idx++] = curr_list.get(col);\n \n curr_list.set(col, Integer.MAX_VALUE); // mark as visited\n \n // left child is the one below you\n if (row + 1 < num_rows \n && nums.get(row + 1).size() > col \n && nums.get(row + 1).get(col) != Integer.MAX_VALUE) {\n queue.offer(new int[]{row + 1, col});\n }\n \n // right child is the one beside you\n if (col + 1 < curr_list.size() && curr_list.get(col + 1) != Integer.MAX_VALUE) {\n queue.offer(new int[]{row, col + 1});\n }\n }\n }\n \n return res;\n }\n}\n```\n
5
0
['Binary Tree']
0
diagonal-traverse-ii
Py3 Sol: beats 78%, 1 Pass Sol, Easy to understand
py3-sol-beats-78-1-pass-sol-easy-to-unde-ma4l
Concept: Along diagonal, the sum of the indices are always SAME. For ex- take index- [0,2], [1,1], [2,0] (all have a total sum of 2).\nSo we will try to make a
ycverma005
NORMAL
2020-04-30T16:31:13.173432+00:00
2020-05-02T17:53:45.759863+00:00
820
false
Concept: Along diagonal, the sum of the indices are always SAME. For ex- take index- [0,2], [1,1], [2,0] (all have a total sum of 2).\nSo we will try to make a empty List of list, and `sum of index` will act a `new index` for `List of list`. \n\n```\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n res = []\n for i, r in enumerate(nums):\n for j, val in enumerate(r):\n if len(res) <= i + j: # adding a empty list at index i + j\n res.append([])\n res[i+j].append(val)\n l = []\n for r in res:\n l+=reversed(r)\n return l\n\n```
5
1
['Python', 'Python3']
4
diagonal-traverse-ii
EEzz simple Python solution using Hashmap/deafulatdict(list)!
eezz-simple-python-solution-using-hashma-3hni
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n(i+j) for same\xA0diago
yashaswisingh47
NORMAL
2023-11-22T13:41:26.873444+00:00
2023-11-22T13:41:26.873467+00:00
367
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n(i+j) for same\xA0diagonal elements is equal. \nThey will be added to a result(res) list after being stored in a hashmap. (To obtain the upward diagonal traversal, reverse each list in the hashmap.)\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 findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n d , res = defaultdict(list) , []\n for i in range(len(nums)):\n for j in range(len(nums[i])):\n d[i+j].append(nums[i][j])\n for k in d.values():\n k = k[::-1]\n res.extend(k)\n return res\n```
4
0
['Hash Table', 'Sorting', 'Matrix', 'Python3']
0
diagonal-traverse-ii
✅ Easy and small solution 🔥 simple idea 🚀 with some optimization
easy-and-small-solution-simple-idea-with-kk9z
Intuition\n- convert the photo to sum indexes it will be pattern problem, if we see he but all indexes with (i+j)=0 first then but all indexes with sum (i+j)=1
omar_walied_ismail
NORMAL
2023-11-22T05:21:53.509561+00:00
2023-11-22T05:21:53.509588+00:00
361
false
# Intuition\n- convert the photo to sum indexes it will be pattern problem, if we see he but all indexes with `(i+j)=0` first then but all indexes with sum `(i+j)=1` and so on, but he put it in `reversed order` so I need to store every sum in vector and reverse it and put it in `ans`\n\n# Approach\n1. create array of vectors with size $$10^5$$ because the sum of indexes not exceed that number\n2. iterate on vector nums to but every `(i+j)` in `use` and take the max sum of `(i+j)` to iterate with this only because we don\'t need much iterations\n3. iterate on every vector in `use` from end to start then push every element in this vector to `ans` vector\n\n# Complexity\n- Time complexity:\n$$O( n + m )$$ \n`n = size( nums ) , m = size of( every vector in nums )` \n\n- Space complexity:\n$$O( n + m )$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n ios_base::sync_with_stdio(0),cout.tie(0),cin.tie(0);\n vector<int>use[100000];\n int mx=0;\n for(int i=0;i<nums.size();i++)\n for(int j=0;j<nums[i].size();j++)\n use[i+j].push_back(nums[i][j]),mx=max(mx,i+j);\n vector<int>ans;\n for(int j=0;j<=mx;j++)\n for(int i=(int)use[j].size()-1;i>=0;i--)\n ans.push_back(use[j][i]);\n return ans;\n }\n};\n```\nand this optimization for the previous code \n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n ios_base::sync_with_stdio(0),cout.tie(0),cin.tie(0);\n vector<vector<int>>use;\n int j,i,sz;\n for(i=0;i<nums.size();i++){\n sz=nums[i].size();\n for(j=0;j<sz;j++){\n if(i+j>=use.size())\n use.push_back({});\n use[i+j].push_back(nums[i][j]);\n }\n }\n vector<int>ans;\n for(j=0;j<use.size();j++)\n for(i=(int)use[j].size()-1;i>=0;i--)\n ans.push_back(use[j][i]);\n return ans;\n }\n};\n```\n
4
0
['Array', 'C++']
2
diagonal-traverse-ii
C# Solution for Diagonal Traverse II Problem
c-solution-for-diagonal-traverse-ii-prob-7kyv
Intuition\n Describe your first thoughts on how to solve this problem. \n1.\tGrouping by Diagonal Sum: The solution aims to group elements from the input 2D lis
Aman_Raj_Sinha
NORMAL
2023-11-22T03:15:15.959627+00:00
2023-11-22T03:16:47.758909+00:00
256
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1.\tGrouping by Diagonal Sum: The solution aims to group elements from the input 2D list based on the sum of their row and column indices, simulating diagonal traversal.\n2.\tRetrieving Elements in Order: After creating these groups, it retrieves and concatenates the elements in the correct diagonal order to form the final output.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tHashMap for Grouping: It initializes a dictionary (groups) to map the diagonal sums to the respective elements in the 2D list.\n2.\tPopulating Groups: Iterating through the 2D list in reverse row order, it calculates the diagonal sum for each element and adds it to the corresponding group in the dictionary.\n3.\tRetrieving Diagonal Elements: It sequentially retrieves elements from the groups in ascending order of diagonal sums, adding them to the output list (ans).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tGroup Creation: The nested loop to populate the groups dictionary runs in O(m . n) time, where is the number of rows and is the average number of elements in each row.\n\u2022\tRetrieving Elements: The traversal through the groups takes O(m . n) time in the worst case, where each element is visited once.\n\nTherefore, the overall time complexity is O(m . n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tHashMap Space: The groups dictionary requires additional space to store elements based on their diagonal sums, taking up O(m . n) space.\n\u2022\tOutput List: The ans list also stores the final result and can take up to O(m . n) space in the worst case.\n\nHence, the overall space complexity is O(m . n).\n\n# Code\n```\npublic class Solution {\n public int[] FindDiagonalOrder(IList<IList<int>> nums) {\n Dictionary<int, List<int>> groups = new Dictionary<int, List<int>>();\n\n // Step 1: Populate groups based on diagonal sum\n for (int row = nums.Count - 1; row >= 0; row--) {\n for (int col = 0; col < nums[row].Count; col++) {\n int diagonal = row + col;\n if (!groups.ContainsKey(diagonal)) {\n groups[diagonal] = new List<int>();\n }\n groups[diagonal].Add(nums[row][col]);\n }\n }\n\n List<int> ans = new List<int>();\n int curr = 0;\n\n // Step 4: Traverse through groups in order\n while (groups.ContainsKey(curr)) {\n ans.AddRange(groups[curr]);\n curr++;\n }\n\n return ans.ToArray();\n }\n}\n```
4
1
['C#']
1
diagonal-traverse-ii
Rust: queue
rust-queue-by-natekot-34jy
\nuse std::collections::VecDeque;\n \nimpl Solution {\n pub fn find_diagonal_order(nums: Vec<Vec<i32>>) -> Vec<i32> {\n \n let n = nums.len();\n let
natekot
NORMAL
2023-11-22T01:45:26.130133+00:00
2023-11-22T01:45:26.130156+00:00
71
false
```\nuse std::collections::VecDeque;\n \nimpl Solution {\n pub fn find_diagonal_order(nums: Vec<Vec<i32>>) -> Vec<i32> {\n \n let n = nums.len();\n let mut q = VecDeque::new();\n let mut ans = vec![];\n \n q.push_back((0, 0));\n \n while let Some((i, j)) = q.pop_front() {\n \n ans.push(nums[i][j]);\n \n if j == 0 && i + 1 < n {\n q.push_back((i + 1, j));\n }\n \n if j + 1 < nums[i].len() {\n q.push_back((i, j + 1));\n }\n }\n \n ans\n }\n}\n```
4
0
['Rust']
1
diagonal-traverse-ii
[Java] Clean Code without HashMap
java-clean-code-without-hashmap-by-xiang-1tu0
\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int m = nums.size(), maxSum = 0, size = 0, index = 0;\n List<
xiangcan
NORMAL
2023-06-19T17:44:13.552165+00:00
2023-06-19T17:44:13.552188+00:00
470
false
```\nclass Solution {\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n int m = nums.size(), maxSum = 0, size = 0, index = 0;\n List<Integer>[] map = new ArrayList[100001];\n for (int i = 0; i < m; i++) {\n size += nums.get(i).size();\n for (int j = 0; j < nums.get(i).size(); j++) {\n int sum = i + j;\n if (map[sum] == null) map[sum] = new ArrayList<>();\n map[sum].add(nums.get(i).get(j));\n maxSum = Math.max(maxSum, sum);\n }\n }\n int[] res = new int[size];\n for (int i = 0; i <= maxSum; i++) {\n List<Integer> cur = map[i];\n for (int j = cur.size() - 1; j >= 0; j--) {\n res[index++] = cur.get(j);\n }\n }\n return res;\n }\n}\n```
4
0
['Java']
1
diagonal-traverse-ii
C++|| Super Easy Solution || Diagonal Traverse II
c-super-easy-solution-diagonal-traverse-4wkw3
\'\'\'\nSuper Easy Solution using map\nclass Solution {\npublic:\n\n\t vector findDiagonalOrder(vector>& nums) {\n map> mp;\n
code_with_dua
NORMAL
2022-07-05T07:30:29.835150+00:00
2022-07-05T07:30:29.835193+00:00
387
false
\'\'\'\n**Super Easy Solution using map**\nclass Solution {\npublic:\n\n\t vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n map<int,vector<int>> mp;\n //[i+j],{vector}\n for(int i=0;i<nums.size();i++) //0->{1}\n { //1->{2,4}\n for(int j=0;j<nums[i].size();j++) //2->{3,5,7}\n { //3->{6,8}\n mp[i+j].push_back(nums[i][j]); //4->{9}\n }\n }\n \n vector<int> ans;\n //Reversed\n for(auto it: mp) //0->{1}\n { //1->{4,2}\n reverse(it.second.begin(),it.second.end()); //2->{7,5,3}\n //3->{8,6}\n for(auto k: it.second) //4->{9}\n {\n ans.push_back(k);\n }\n }\n return ans;\n \n }\n};\n\'\'\'\n**Please upvote when you liked**
4
0
['C']
1
diagonal-traverse-ii
Python Heap Solution
python-heap-solution-by-xxixos-jkr8
We are aware that the sum of row index and col index of each element in a diagonal is the same. \n\nWe can use this property to utilize minHeap, so that element
xxixos
NORMAL
2022-01-21T14:47:34.309604+00:00
2022-01-21T14:48:22.789992+00:00
98
false
We are aware that the sum of row index and col index of each element in a diagonal is the same. \n\nWe can use this property to utilize minHeap, so that element with smaller sum comes out first, and if the sums are the same, element with smaller col index comes first.\n\n```\nclass Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n res = []\n \n m = len(nums)\n \n import heapq\n minHeap = []\n \n for i in range(0, m):\n cols = len(nums[i])\n for k in range(0, cols):\n minHeap.append((i+k, k, i))\n \n heapq.heapify(minHeap)\n \n while minHeap:\n _, k, i = heapq.heappop(minHeap)\n res.append(nums[i][k])\n \n return res\n```
4
0
['Heap (Priority Queue)']
2
diagonal-traverse-ii
[Java] Easy to Understand 22 ms 93.27%
java-easy-to-understand-22-ms-9327-by-hd-9bcd
\nclass Solution {\n class Point {\n int row;\n int sum;\n int val;\n Point(int row,int sum,int val) {\n this.row = ro
hdobhal
NORMAL
2020-09-11T11:59:34.418972+00:00
2020-09-11T11:59:34.419015+00:00
691
false
```\nclass Solution {\n class Point {\n int row;\n int sum;\n int val;\n Point(int row,int sum,int val) {\n this.row = row;\n this.sum = sum;\n this.val = val;\n }\n \n }\n public int[] findDiagonalOrder(List<List<Integer>> nums) {\n ArrayList<Point> list = new ArrayList<>();\n for(int r = 0;r<nums.size() ;r++) {\n List<Integer> elements = nums.get(r);\n for(int c =0;c<elements.size();c++) {\n list.add(new Point(r,r+c,elements.get(c)));\n }\n }\n Collections.sort(list,(o1,o2) -> {\n int result = Integer.compare(o1.sum, o2.sum);\n if(result == 0) return Integer.compare(o2.row,o1.row);\n return result;\n });\n int total = list.size();\n int[] solution = new int[total];\n for(int i=0;i<total;i++) {\n solution[i] = list.get(i).val;\n }\n return solution;\n }\n}\n\n\n```
4
1
['Java']
1
diagonal-traverse-ii
[C++]O(N) Clean Code without map
con-clean-code-without-map-by-jiah-wsji
cpp\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<list<int>> data;\n for (int i = 0; i < num
jiah
NORMAL
2020-04-26T04:49:43.256133+00:00
2020-04-26T04:49:43.256185+00:00
313
false
```cpp\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<list<int>> data;\n for (int i = 0; i < nums.size(); i++) {\n for (int j = 0; j < nums[i].size(); j++) {\n if (i+j == data.size()) \n data.push_back(list<int>());\n data[i+j].push_front(nums[i][j]);\n }\n }\n vector<int> ans;\n for (auto &li: data) {\n ans.insert(ans.end(), li.begin(), li.end());\n }\n return ans;\n }\n};\n```
4
1
[]
1
diagonal-traverse-ii
C++|easiest|map|explaination
ceasiestmapexplaination-by-alex3898-vn8a
do numbering of the elements and push them into map \nthen traverse the map\n\nclass Solution \n{\n \npublic:\n vector<int> findDiagonalOrder(vector<vecto
alex3898
NORMAL
2020-04-26T04:02:32.697449+00:00
2020-04-26T04:02:32.697486+00:00
450
false
do numbering of the elements and push them into map \nthen traverse the map\n```\nclass Solution \n{\n \npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) \n {\n int m=nums.size(),n=nums[0].size();\n \n int numbering=1;\n map<int,vector<int>>mp;\n for(int i=0;i<m;i++)\n {\n int it=numbering;\n for(int j=0;j<nums[i].size();j++)\n {\n mp[it].push_back(nums[i][j]);\n it++;\n }\n numbering++;\n }\n vector<int>ans;\n for(auto it=mp.begin();it!=mp.end();it++)\n {\n for(int i=it->second.size()-1;i>=0;i--)\n ans.push_back(it->second[i]);\n }\n return ans;\n }\n};\n```
4
1
['C']
3
diagonal-traverse-ii
Short and Simple C++, solution with explanation
short-and-simple-c-solution-with-explana-4ln5
Main idea: to identify similar blocks--> for this add their ith and jth (row or col) respectively. \nnums(1,0) and nums(0,1) will be in same map with key = (1+0
prateekchhikara
NORMAL
2020-04-26T04:01:50.993358+00:00
2020-04-26T05:43:44.370418+00:00
483
false
***Main idea:*** to identify similar blocks--> for this add their ith and jth (row or col) respectively. \nnums(1,0) and nums(0,1) will be in same map with key = (1+0 = 0+1) \n\n```\nvector<int> findDiagonalOrder(vector<vector<int>>& nums) \n {\n unordered_map<int, vector<int>> mp;\n int n = nums.size();\n int k=0;\n for(int i=0; i<n; i++)\n {\n int m = nums[i].size();\n for(int j=0; j<m; j++)\n mp[i+j].insert(mp[i+j].begin(), nums[i][j]);\n k=max(k,m);\n }\n vector<int> ans;\n for(int i=0; i<=k+n; i++)\n {\n vector<int> p = mp[i];\n for(int j=0; j<p.size(); j++)\n ans.push_back(p[j]);\n }\n return ans;\n }\n```
4
1
[]
3
diagonal-traverse-ii
EASY Solution Using Hash Map
easy-solution-using-hash-map-by-danil_m-fza1
**Explanation and Algorithm Problem Breakdown **The problem asks us to traverse a list of lists (a 2D structure) in a diagonal order and return the elements in
Danil_M
NORMAL
2025-02-20T08:34:12.656546+00:00
2025-02-20T08:34:12.656546+00:00
66
false
# **Explanation and Algorithm Problem Breakdown ** The problem asks us to traverse a list of lists (a 2D structure) in a diagonal order and return the elements in that order as an array. The diagonals are defined by the sum of the row and column indices. **Algorithm Diagonal Grouping:** Create a map (a MutableMap) where: Key: The diagonal number (which is the sum of the row and column indices: row + col). Value: A MutableList of integers that belong to that diagonal. Iterate through the input nums list of lists: For each element nums[row][col]: Calculate the diagonal number: diagonal = row + col. Add the element nums[row][col] to the list associated with that diagonal in the map. Use computeIfAbsent for more clear code. **Diagonal Traversal:** Create an empty result list (a MutableList) to store the elements in the correct order. Initialize diagonal to 0 (the first diagonal). While the map contains the current diagonal: Get the list of elements for the current diagonal from the map. Iterate through the list in reverse order (from the last element to the first). This is because we need to traverse each diagonal from bottom-up. Add each element to the result list. Increment diagonal to move to the next diagonal. ***Return Result:*** Convert the result list to an IntArray and return it. Code Breakdown findDiagonalOrder(nums: List<List<Int>>): IntArray This is the main function that takes the input nums and returns the diagonal order as an IntArray. map: The map to store elements by diagonal. **Diagonal Grouping:** for (row in nums.indices): Iterates through the rows. for (col in nums[row].indices): Iterates through the columns in the current row. diagonal = row + col: Calculates the diagonal number. map.computeIfAbsent(diagonal) { mutableListOf() }.add(nums[row][col]): Adds the element to the list for the corresponding diagonal. result: The list to store the result. diagonal: The current diagonal number. **Diagonal Traversal:** while (map.containsKey(diagonal)): Continues as long as there are diagonals left. list = map[diagonal]!!: Gets the list for the current diagonal. for (i in list.size - 1 downTo 0): Iterates in reverse order. result.add(list[i]): Adds the element to the result. diagonal++: Moves to the next diagonal. return result.toIntArray(): Returns the result as an IntArray. **computeIfAbsent:** computeIfAbsent is a method of the Map interface in Kotlin (and Java). It's a convenient way to add a key-value pair to a map only if the key is not already present. map.computeIfAbsent(diagonal) { mutableListOf() }: diagonal: This is the key you're checking for. { mutableListOf() }: This is a lambda expression that provides the value to be associated with the key if the key is not already present. In this case, it creates a new, empty MutableList. map.computeIfAbsent(diagonal) { mutableListOf() }.add(nums[row][col]): If the key is present, the lambda is not executed, and the add method is called on the existing list. If the key is not present, the lambda is executed, a new list is created, and then the add method is called on the new list. **Time and Space Complexity** Time Complexity: O(N), where N is the total number of elements in the input nums. We visit each element once to group them by diagonal, and then we visit each element again to add them to the result. Space Complexity: O(N) in the worst case. The map might need to store all the elements if they are spread across many diagonals. The result list also stores all the elements. Example Let's say nums = [[1,2,3],[4,5,6],[7,8,9]]. # Code ```kotlin [] class Solution { fun findDiagonalOrder(nums: List<List<Int>>): IntArray = findDiagonalOrderAlternativeSolution(nums) fun findDiagonalOrderAlternativeSolution(nums: List<List<Int>>): IntArray { if (nums.hasSingle()) nums[0].toIntArray() val map = mutableMapOf<Int, MutableList<Int>>() for (i in nums.indices) { for (j in 0 until nums[i].size) { map.getOrPut(i + j) { mutableListOf() }.let { it.add(nums[i][j]) } } } var diagonal = 0 val result = mutableListOf<Int>() while (map.contains(diagonal)) { val values = map.getOrDefault(diagonal, mutableListOf()) for (i in values.size - 1 downTo 0) result.add(values[i]) diagonal++ } return result.toIntArray() } private fun <T> List<T>.hasSingle(): Boolean = when { this.size == 1 -> true else -> false } } ```
3
0
['Hash Table', 'Kotlin']
0
diagonal-traverse-ii
Simple Approach ✔ with Best explanation ❤ C++ 🤞 Comments Added 😍
simple-approach-with-best-explanation-c-jom40
Intuition and approach :\n AFTER little bit of analyzing, you will surely find the patter.. that is :\n1st we have to get/find all diagonal pairs..and we can
DEvilBackInGame
NORMAL
2023-11-22T17:19:43.127561+00:00
2023-11-22T17:21:37.949354+00:00
33
false
# Intuition and approach :\n AFTER little bit of analyzing, you will surely find the patter.. that is :\n1st we have to get/find all diagonal pairs..and we can get that as follow:\n\n1. create a 2d array/vector to store all same diagonal pairs .\n2. then start inserting the element of ith row to all row starting from ith row in 2d array. \n3. do this till you insert all the element from last row.\n\nBUT, before doing this you surely get doubt on how to give/assign size to your 2d array/vector. so for that i calculated the maximum possible row and column dimensions from the given 2d array. then i allocated that size to my 2d vector. i have used here static_cast too for converting my \'size_type\' value to \'int\' as it was giving error.. and it\'s somewhat unusual to encounter such an issue with a basic arithmetic operation involving size() and an integer. but its fine.\n\nThen after getting all diagonal value all i have to do is inserting them in my result vector.\nBUT, there are in reversed order hence while inserting i have to either reverse each row then insert.. or i can simply insert each row from last index, that is more convient and good.\n\nHOPE u find it helpful :).\nand sorry as my health is not good hence i am not doing much question now a days...so posting daily solutions is tough for me.. but i will try to give u solutions. stay safe and happy . \u2764\uD83E\uDD1C\uD83E\uDD1B\n\n# C++ Code :\n```\n#include <vector>\n\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n if (nums.empty()) {\n return {};\n }\n\n int rows = nums.size();\n\n // Calculate the maximum possible diagonal length\n int maxLength = 0;\n for (int i = 0; i < rows; i++) {\n maxLength = max(maxLength, static_cast<int>(nums[i].size() + i));\n }\n\n // 2D array to store elements in diagonal order\n vector<vector<int>> diagonals(maxLength);\n\n // Push elements into diagonals\n for (int i = 0; i < rows; i++) {\n int cols = nums[i].size();\n for (int j = i; j < cols + i; j++) {\n diagonals[j].push_back(nums[i][j - i]);\n }\n }\n\n // Insert values from 2D array to the result vector by inserting each row in reverse order\n vector<int> result;\n for (int i = 0; i < maxLength; i++) {\n int s = diagonals[i].size();\n for (int j = s - 1; j >= 0; j--) {\n result.push_back(diagonals[i][j]);\n }\n }\n\n return result;\n }\n};\n\n```
3
0
['C++']
0
diagonal-traverse-ii
easy solution
easy-solution-by-skr0489-qczn
Intuition\nThe sum of i index and j index of diagonal element is same\nso , we use map to store the diagonal element wrt the some of index\n Describe your first
skr0489
NORMAL
2023-11-22T13:10:46.711622+00:00
2023-11-22T13:10:46.711639+00:00
9
false
# Intuition\nThe sum of i index and j index of diagonal element is same\nso , we use map to store the diagonal element wrt the some of index\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findDiagonalOrder(vector<vector<int>>& nums) {\n vector<int>ans;\n int n=nums.size();\n map<int,vector<int>>mp;\n for(int i=0;i<n;i++){\n\n int m=nums[i].size();\n\n for(int j=0;j<m;j++){\n int val=i+j;\n mp[val].push_back(nums[i][j]);\n }\n }\n\n for(auto i:mp){\n vector<int>temp=i.second;\n reverse(temp.begin(),temp.end());\n for(auto j:temp){\n ans.push_back(j);\n }\n }\n return ans;\n }\n};\n```
3
0
['Ordered Map', 'C++']
1