title
stringlengths 3
77
| title_slug
stringlengths 3
77
| question_content
stringlengths 38
1.55k
⌀ | tag
stringclasses 707
values | level
stringclasses 3
values | question_hints
stringlengths 19
3.98k
⌀ | view_count
int64 8
630k
| vote_count
int64 5
10.4k
| content
stringlengths 0
43.9k
| __index_level_0__
int64 0
109k
|
---|---|---|---|---|---|---|---|---|---|
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 643 | 8 | ```\nclass Solution {\n public boolean isMatch(String text, String pattern) {\n// This will help us at the end mainly for the else part given below.\n if(pattern.length() == 0)\n return text.length() == 0;\n// here is the condition if * encountered and then we are focusion how to handle the cases\n if(pattern.length() > 1 && pattern.charAt(1) == \'*\'){\n if(isMatch(text, pattern.substring(2)))\n return true;\n if(text.length() > 0 && (pattern.charAt(0) == \'.\' || text.charAt(0) == pattern.charAt(0)))\n return isMatch(text.substring(1), pattern);\n return false;\n }else{\n// here we just have to check if characters are eqal to each other else if \'.\' is present working as single integer\n if(text.length() > 0 && (pattern.charAt(0) == \'.\' || text.charAt(0) == pattern.charAt(0)))\n return isMatch(text.substring(1), pattern.substring(1));\n }\n return false;\n }\n}\n``` | 984 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 1,950 | 25 | #### algorithm\nWe start with building base cases:\n- If both the string and the pattern are empty, there is a match. \n- If the pattern is empty but the string is not, there is no match.\n- If the string is empty, it\'s still possible that there\'s a match even if the pattern is not empty, as `*` can match zero of the preceding character.\n\nThe most difficult part is that we have two special characters that we need take care of. `.` is fairly straightforward: there will be a match between `.` and any string character. However, `*` is a bit difficult to deal with, since it can either match 0 of the preceding character, or match 1 or even more of the preceding character.\n\nIn this solution, we have two pointers pointing to the current characters at the string and pattern respectively. The logic of how to build our dp array depends on the current character in the pattern string that we\'re currently at. \n- If the current character we\'re at is not `*`, then we check if it matches the current string charater. If so, then we check whether the remaining part still matches. \n- If the current character we\'re at is `*`, then we need to handle two different cases.\n\t- The first case is that this `*` might match 0 of the preceding character, therefore we need to check if the remaining part of the pattern matches the string.\n\t- The second case is that this `*` might match 1 or more of the preceding character. If so, we first need to ensure that the preceding character of `*` matches the current character in the string. We then need to see if the remaining part of the string matches with the pattern.\n\n#### O(mn) space\n\n```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n vector<vector<bool>> dp(s.size() + 1, vector<bool>(p.size() + 1, false));\n \n\t\tdp[0][0] = true;\n for (int j = 2; j <= p.size(); ++j) {\n if (p[j - 1] == \'*\') {\n dp[0][j] = dp[0][j - 2];\n }\n }\n \n for (int i = 1; i <= s.size(); ++i) {\n for (int j = 1; j <= p.size(); ++j) {\n if (p[j - 1] != \'*\') {\n dp[i][j] = (p[j - 1] == \'.\' || p[j - 1] == s[i - 1]) && dp[i - 1][j - 1];\n } else {\n dp[i][j] = dp[i][j - 2] || (((p[j - 2] == \'.\') || (p[j - 2] == s[i - 1])) && dp[i - 1][j]);\n }\n }\n }\n \n return dp[s.size()][p.size()];\n }\n};\n```\n\n#### O(n) space\nTo calculate `dp[i][j]`, we only need `dp[i][j - 2]`, `dp[i - 1][j - 1]`, and `dp[i - 1][j]`. Therefore, we can compress the original 2d array into 1d.\nHowever, since we only have one array, we might override the necessary information for later calculation when we\'re updating the dp array. Therefore, we need 2 extra variables to store the information from last iteration.\n\n```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n vector<bool> dp(p.size() + 1, false);\n \n dp[0] = true;\n for (int j = 2; j <= p.size(); ++j) {\n if (p[j - 1] == \'*\') {\n dp[j] = dp[j - 2];\n }\n }\n \n for (int i = 1; i <= s.size(); ++i) {\n bool neighborLastRow = dp[0];\n dp[0] = false;\n for (int j = 1; j <= p.size(); ++j) {\n bool currLastRow = dp[j];\n if (p[j - 1] != \'*\') {\n dp[j] = (p[j - 1] == \'.\' || p[j - 1] == s[i - 1]) && neighborLastRow;\n } else {\n dp[j] = dp[j - 2] || (((p[j - 2] == \'.\') || (p[j - 2] == s[i - 1])) && currLastRow);\n }\n neighborLastRow = currLastRow;\n }\n }\n \n return dp[p.size()];\n }\n};\n``` | 986 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 24,959 | 66 | Takes about 174ms:\n\n \n cache = {}\n def isMatch(self, s, p):\n if (s, p) in self.cache:\n return self.cache[(s, p)]\n if not p:\n return not s\n if p[-1] == '*':\n if self.isMatch(s, p[:-2]):\n self.cache[(s, p)] = True\n return True\n if s and (s[-1] == p[-2] or p[-2] == '.') and self.isMatch(s[:-1], p):\n self.cache[(s, p)] = True\n return True\n if s and (p[-1] == s[-1] or p[-1] == '.') and self.isMatch(s[:-1], p[:-1]):\n self.cache[(s, p)] = True\n return True\n self.cache[(s, p)] = False\n return False\n\n\nDP version:\n \n def isMatch(self, s, p):\n dp = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]\n dp[0][0] = True\n for i in range(1, len(p)):\n dp[i + 1][0] = dp[i - 1][0] and p[i] == '*'\n for i in range(len(p)):\n for j in range(len(s)):\n if p[i] == '*':\n dp[i + 1][j + 1] = dp[i - 1][j + 1] or dp[i][j + 1]\n if p[i - 1] == s[j] or p[i - 1] == '.':\n dp[i + 1][j + 1] |= dp[i + 1][j]\n else:\n dp[i + 1][j + 1] = dp[i][j] and (p[i] == s[j] or p[i] == '.')\n return dp[-1][-1] | 988 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 2,051 | 6 | * ***Using Bottom Up DP***\n\n* ***Time Complexity :- O(N * M)***\n\n* ***Space Complexity :- O(N * M)***\n\n```\nclass Solution {\npublic:\n bool isMatch(string str, string pat) {\n\n int n = str.size();\n \n int m = pat.size();\n\n // \'.\' can be any character\n \n // "s*" can be replace with "", "s", "ss", "sss", "ssss" and so on .....\n \n // above possibility can be replaced with "", "ss*"\n\n // str in on i direction and pat is on j direction\n\n // for the 0th row if we encounter \'*\' then we look for dp[0][j - 2]\n\n vector<vector<bool>> dp(n + 1, vector<bool> (m + 1, false));\n\n for(int i = 0; i <= n; i++)\n {\n for(int j = 0; j <= m ; j++)\n {\n if(i == 0 && j == 0)\n {\n dp[i][j] = true;\n }\n else if(j == 0)\n {\n dp[i][j] = false;\n }\n else if(i == 0)\n {\n if(pat[j - 1] == \'*\')\n {\n dp[i][j] = dp[i][j - 2];\n }\n else\n {\n dp[i][j] = false;\n }\n }\n else\n {\n if(str[i - 1] == pat[j - 1] || pat[j - 1] == \'.\')\n {\n dp[i][j] = dp[i - 1][j - 1];\n }\n else if(pat[j - 1] == \'*\')\n {\n // eg. replace "mis*" with "mi"\n\n dp[i][j] = dp[i][j - 2];\n\n // eg. replace "mis*" with "miss*"\n\n if(dp[i][j] == false && (str[i - 1] == pat[j - 2] || pat[j - 2] == \'.\'))\n {\n dp[i][j] = dp[i - 1][j];\n }\n }\n }\n }\n }\n\n return dp[n][m];\n }\n};\n``` | 989 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 1,181 | 19 | I used to complain that the official article is not explicit and detailed enough. But when I attempt to write a good one, I find it really tough to explain a question very explicitly. I hope this post can help you understand how to use DP to solve this problem. And I am not a native speaker, if my terrible english make you more confused, I would like to to say sorry.\n\n**First I want to say the * can\'t be the first character and two * can\'t show up continuously in a test case. (This isn\'t mentioned in the description)**\n\nThere is a very intuitive sentence to me in the comment section. One brother said that if we can\'t come out a DP solution at the interveiw, we can begin at the recursion method. Then we import the memoization in to avoid repeated caculations. Then if we look back what we did, we find we implemented the essence of the top-down DP. Howeve, as for this problem. Especailly under the circumstance that I have already completed "72 Edit Distance" and "161 One Edit Distance". I am very sure that use the DP table is the best way to solve this problem. But as for this problem, the regulation is a little difficult to find out. I spent a few time to write down the DP table and succedded to find the key ultimatlely. And I will share my DP table and exhibit some typical example to summarize the three conditions that we can judge the two strings match.\n\nFirst of all, we need to declare a doubel demension vector as the DP table. DP[i][j] represents s.substr(0,i-1) matched p.substr(0,j-1) Please pay attention to the index. And some basic skills to implement DP are used in the code. I thought I needn\'t explain it. \nLet\'s throw the light on three key parts in the code.\n1.s[i-1]==p[j-1],then we check DP[i-1][j-1]\n\n2.if DP[i][j-2]==1 and p[j-1]=="star" we can assign 1 to DP[i][j]\nwe can use the character at p[j-2] totally times \nexample:s="aa star" p="aac star"\n\n3.Then we will go through the most complicated condition\nwe must use the prosperity of "star" and copy the element before "star" some times to match string s\nso we need to check DP[i-1][j]==1\nand p[j-2]==s[i-1]|| p[j-2]=="."**\n![image]()\n![image]()\n![image]()\n![image]()\n![image]()\n![image]()\n\n\n```\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int s_size=s.size();\n int p_size=p.size();\n vector<vector<int>> DP(s_size+1,vector<int>(p_size+1,0));\n DP[0][0]=1;\n for(int j(2);j<=DP[0].size()-1;j++)\n {\n if(DP[0][j-2]&&p[j-1]==\'*\')\n {\n DP[0][j]=1;\n }\n }\n for(int i(1);i<=DP.size()-1;i++)\n {\n for(int j(1);j<=DP[0].size()-1;j++)\n {\n if(p[j-1] == \'*\')\n {\n DP[i][j] = DP[i][j-2];//*we use totally 0 character before it\n //so if DP[i][j-2]=1, we can directly assign 1 to DP[i][j] Think about s="a",p="ac*"\n if(p[j-2] == \'.\' || p[j-2] == s[i-1])\n {\n if(DP[i-1][j])\n {\n DP[i][j]=1;// we need to use * to copy the element before it\n }\n }\n }\n else if(p[j-1]==s[i-1]||p[j-1]==\'.\')\n {\n DP[i][j]=DP[i-1][j-1];\n }\n }\n }\n return DP[s_size][p_size]==1;\n }\n};\n``` | 990 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 3,712 | 32 | ```\nconst isMatch = (string, pattern) => {\n // early return when pattern is empty\n if (!pattern) {\n\t\t// returns true when string and pattern are empty\n\t\t// returns false when string contains chars with empty pattern\n return !string;\n }\n \n\t// check if the current char of the string and pattern match when the string has chars\n const hasFirstCharMatch = Boolean(string) && (pattern[0] === \'.\' || pattern[0] === string[0]);\n\n // track when the next character * is next in line in the pattern\n if (pattern[1] === \'*\') {\n // if next pattern match (after *) is fine with current string, then proceed with it (s, p+2). That\'s because the current pattern may be skipped.\n // otherwise check hasFirstCharMatch. That\'s because if we want to proceed with the current pattern, we must be sure that the current pattern char matches the char\n\t\t// If hasFirstCharMatch is true, then do the recursion with next char and current pattern (s+1, p). That\'s because current char matches the pattern char. \n return (\n isMatch(string, pattern.slice(2)) || \n (hasFirstCharMatch && isMatch(string.slice(1), pattern))\n );\n }\n \n // now we know for sure that we need to do 2 simple actions\n\t// check the current pattern and string chars\n\t// if so, then can proceed with next string and pattern chars (s+1, p+1)\n return hasFirstCharMatch ? isMatch(string.slice(1), pattern.slice(1)) : false;\n};\n``` | 992 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 4,753 | 6 | This problem can be solved using dynamic programming. Let dp[i][j] be a boolean indicating whether the first i characters of s match the first j characters of p. We can initialize dp[0][0] = True because an empty string matches an empty pattern.\n\nFor the first row dp[0][j], we need to consider two cases: if p[j-1] is \'*\', we can ignore it and look at dp[0][j-2] (the pattern without the \'*\' and its preceding character), or if p[j-2] matches the empty string, we can look at dp[0][j-1] (the pattern with only the \'*\' and its preceding character).\n\nFor each subsequent cell dp[i][j], we need to consider three cases: if p[j-1] is a regular character and matches s[i-1], then dp[i][j] = dp[i-1][j-1]. If p[j-1] is a \'*\', then we can either ignore the preceding character and look at dp[i][j-2] (the pattern without the \'*\' and its preceding character), or if the preceding character matches s[i-1], we can look at dp[i-1][j] (the pattern with the \'*\' and one more repetition of the preceding character), or if the preceding character does not match s[i-1], we can ignore both the preceding character and the \'*\' and look at dp[i][j-2]. If p[j-1] is a ., then dp[i][j] = dp[i-1][j-1].\n\nThe final answer is dp[m][n], where m and n are the lengths of s and p, respectively.\n\nThe time complexity of this algorithm is O(mn) and the space complexity is O(mn), where m and n are the lengths of s and p, respectively.\n\n# Code\n```\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n m, n = len(s), len(p)\n dp = [[False] * (n+1) for _ in range(m+1)]\n dp[0][0] = True\n for j in range(1, n+1):\n if p[j-1] == \'*\':\n dp[0][j] = dp[0][j-2]\n else:\n dp[0][j] = j > 1 and p[j-2] == \'*\' and dp[0][j-2]\n for i in range(1, m+1):\n for j in range(1, n+1):\n if p[j-1] == s[i-1] or p[j-1] == \'.\':\n dp[i][j] = dp[i-1][j-1]\n elif p[j-1] == \'*\':\n dp[i][j] = dp[i][j-2] or (p[j-2] == s[i-1] or p[j-2] == \'.\') and dp[i-1][j]\n else:\n dp[i][j] = False\n return dp[m][n]\n``` | 997 |
Regular Expression Matching | regular-expression-matching | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: The matching should cover the entire input string (not partial). | String,Dynamic Programming,Recursion | Hard | null | 576 | 10 | **Please upvote if it was helpful!**\n```\nclass Solution {\n bool isMatch(String s, String p) {\n if (p.isEmpty) {\n return s.isEmpty;\n }\n bool firstMatch = s.isNotEmpty && (p[0] == s[0] || p[0] == \'.\');\n\n if (p.length >= 2 && p[1] == \'*\') {\n return (isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p)));\n } else {\n return firstMatch && isMatch(s.substring(1), p.substring(1));\n }\n }\n}\n```\n[Submission Detail]() | 998 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 78,093 | 627 | # Intuition:\nThe two-pointer technique starts with the widest container and moves the pointers inward based on the comparison of heights. \nIncreasing the width of the container can only lead to a larger area if the height of the new boundary is greater. By moving the pointers towards the center, we explore containers with the potential for greater areas.\n\n# Explanation:\n1. Initialize the variables:\n - `left` to represent the left pointer, starting at the beginning of the container (index 0).\n - `right` to represent the right pointer, starting at the end of the container (index `height.size() - 1`).\n - `maxArea` to keep track of the maximum area found, initially set to 0.\n\n2. Enter a loop using the condition `left < right`, which means the pointers have not crossed each other yet.\n\n3. Calculate the current area:\n - Use the `min` function to find the minimum height between the `left` and `right` pointers.\n - Multiply the minimum height by the width, which is the difference between the indices of the pointers: `(right - left)`.\n - Store this value in the `currentArea` variable.\n\n4. Update the maximum area:\n - Use the `max` function to compare the `currentArea` with the `maxArea`.\n - If the `currentArea` is greater than the `maxArea`, update `maxArea` with the `currentArea`.\n\n5. Move the pointers inward: (Explained in detail below)\n - Check if the height at the `left` pointer is smaller than the height at the `right` pointer.\n - If so, increment the `left` pointer, moving it towards the center of the container.\n - Otherwise, decrement the `right` pointer, also moving it towards the center.\n\n6. Repeat steps 3 to 5 until the pointers meet (`left >= right`), indicating that all possible containers have been explored.\n\n7. Return the `maxArea`, which represents the maximum area encountered among all the containers.\n\n# Update the maximum area:\nThe purpose of this condition is to determine which pointer to move inward, either the left pointer (`i`) or the right pointer (`j`), based on the comparison of heights at their respective positions.\n\nImagine you have two containers represented by the heights at the left and right pointers. The condition checks which container has a smaller height and moves the pointer corresponding to that container.\n\n1. If `height[i] > height[j]`:\n - This means that the height of the left container is greater than the height of the right container.\n - Moving the right pointer (`j`) would not increase the potential area because the height of the right container is the limiting factor.\n - So, to explore containers with the possibility of greater areas, we need to move the right pointer inward by decrementing `j`.\n\n2. If `height[i] <= height[j]`:\n - This means that the height of the left container is less than or equal to the height of the right container.\n - Moving the left pointer (`i`) would not increase the potential area because the height of the left container is the limiting factor.\n - So, to explore containers with the possibility of greater areas, we need to move the left pointer inward by incrementing `i`.\n\nBy making these pointer movements, we ensure that we are always exploring containers with the potential for larger areas. The approach is based on the observation that increasing the width of the container can only lead to a larger area if the height of the new boundary is greater.\nBy following this condition and moving the pointers accordingly, the algorithm explores all possible containers and finds the one with the maximum area.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int left = 0;\n int right = height.size() - 1;\n int maxArea = 0;\n\n while (left < right) {\n int currentArea = min(height[left], height[right]) * (right - left);\n maxArea = max(maxArea, currentArea);\n\n if (height[left] < height[right]) {\n left++;\n } else {\n right--;\n }\n }\n\n return maxArea;\n }\n};\n```\n```Java []\nclass Solution {\n public int maxArea(int[] height) {\n int left = 0;\n int right = height.length - 1;\n int maxArea = 0;\n\n while (left < right) {\n int currentArea = Math.min(height[left], height[right]) * (right - left);\n maxArea = Math.max(maxArea, currentArea);\n\n if (height[left] < height[right]) {\n left++;\n } else {\n right--;\n }\n }\n\n return maxArea;\n }\n}\n```\n```Python3 []\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n left = 0\n right = len(height) - 1\n maxArea = 0\n\n while left < right:\n currentArea = min(height[left], height[right]) * (right - left)\n maxArea = max(maxArea, currentArea)\n\n if height[left] < height[right]:\n left += 1\n else:\n right -= 1\n\n return maxArea\n```\n\n![CUTE_CAT.png]()\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.** | 1,000 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 93,728 | 853 | How\'s going Ladies - n - Gentlemen, today we are going to solve another coolest problem i.e **Container With Most Water**\n\nOkay, so let\'s understand what the problem statement is saying, \n```\nYou are given an integer array height of length n\n\nReturn the maximum amount of water a container can store.\n```\n\nLet\'s take one example in order to understand this problem,\n**Input**: height = [1,8,6,2,5,4,8,3,7]\n**Output**: 49\n\n![image]()\n\nSo, we need to find max area in which most water can contains, where **`area = width * height`**\n\nAs, **height** is already given in our Array!\nBut what about **width?**\n\nSo, to find **width** of a container, all we have to do is get the difference of line.\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t |\n6\t\t\t\t|\t |\t |\t |\n5\t\t\t\t|\t |\t |\t |\t |\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t |\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n```\nSo, my one pointer is on index 1 & another pointer is on index 6\n\nTherefore, **`width = right - left`** i.e. **`6 - 1 => 5`**\n\nAnd if we look at height,\n**`height = min(8, 8)`**\nThus, area will be:-\n**`area = 5 * 8 => 40`**\n\nNow you\'ll ask why we are choosing the min height because, the water we fill in our container will got overflow, so to avoid that we are gabbing the min line.\n\nSo, now you ask. How do we solve this problem efficiently. We gonna solve this in linear time.\n\nSo, for that we have\n```\n> max area which is intially 0\n> Then, we going to have 2 pointers. One in left start at 0th index & one right start from last index.\n```\n\nNow, if I calculate the width & height our area will be:\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t | width = 8 - 0 = 8\n6\t\t\t\t|\t |\t |\t | height = min(1, 7)\n5\t\t\t\t|\t |\t |\t |\t | Area = 8 * 1 = 8\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t | max = 0 -> max = 8\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n\t left right\n```\nBy this pretty much we have get one formula all it is **`area = width * height`**\ni.e. **`area = (right - left) * min(height[left], height[right])`**\n\nSo, now you ask which pointer we suppose to move. It\'s preety simple. We gonna move the smaller height pointer. **Why?**\nBecause, we are trying to find very max. container\n\nIf we have smaller height on left or right we don\'t care about it. We always want a higher height line on our left & right.\n\n**Okay, so now moving forward.** left pointer has smaller height, so it will move forward\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t | width = 8 - 1 = 7\n6\t\t\t\t|\t |\t |\t | height = min(8, 7)\n5\t\t\t\t|\t |\t |\t |\t | Area = 7 * 7 = 49\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t | max = 8 -> max = 49\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n\t left right\n```\n**Okay, so now moving forward.** right pointer has smaller height, so it will move backward\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t | width = 7 - 1 = 6\n6\t\t\t\t|\t |\t |\t | height = min(8, 3)\n5\t\t\t\t|\t |\t |\t |\t | Area = 6 * 3 = 18\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t | max = 49\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n\t left right\n```\n**Okay, so now moving forward.** right pointer has smaller height, so it will move backward\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t | width = 6 - 1 = 5\n6\t\t\t\t|\t |\t |\t | height = min(8, 8)\n5\t\t\t\t|\t |\t |\t |\t | Area = 8 * 5 = 40\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t | max = 49\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n\t left right\n```\n**Okay, so now moving forward.** now left & right pointer both have same height, so in this case we gonna move both the pointer\'s!!\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t | width = 5 - 2 = 3\n6\t\t\t\t|\t |\t |\t | height = min(4, 6)\n5\t\t\t\t|\t |\t |\t |\t | Area = 4 * 3 = 12\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t | max = 49\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n\t left right\n```\n**Okay, so now moving forward.** right pointer has smaller height, so it will move backward\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t | width = 4 - 2 = 2\n6\t\t\t\t|\t |\t |\t | height = min(5, 6)\n5\t\t\t\t|\t |\t |\t |\t | Area = 5 * 2 = 10\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t | max = 49\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n\t left right\n```\n**Okay, so now moving forward.** right pointer has smaller height, so it will move backward\n```\n8\t\t\t\t|\t |\n7\t\t\t\t|\t |\t | width = 3 - 2 = 1\n6\t\t\t\t|\t |\t |\t | height = min(2, 6)\n5\t\t\t\t|\t |\t |\t |\t | Area = 2 * 1 = 2\n4\t\t\t\t|\t |\t |\t |\t |\t |\n3\t\t\t\t|\t |\t |\t |\t |\t |\t | max = 49\n2\t\t\t\t|\t |\t |\t |\t |\t |\t |\t |\n1\t |\t |\t |\t |\t |\t |\t |\t |\t |\n 0 1 2 3 4 5 6 7 8\n\t ^ ^\n\t left right\n```\n\nThe max area we get is **49**\n\nI hope so, ladies & gentlemen approach is clear, **Let\'s code it**\n\n**Java**\n```\nclass Solution {\n public int maxArea(int[] height) {\n int left = 0;\n int right = height.length - 1;\n int max = 0;\n while(left < right){\n int w = right - left;\n int h = Math.min(height[left], height[right]);\n int area = h * w;\n max = Math.max(max, area);\n if(height[left] < height[right]) left++;\n else if(height[left] > height[right]) right--;\n else {\n left++;\n right--;\n }\n }\n return max;\n }\n}\n```\n**C++**\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int left = 0;\n int right = height.size() - 1;\n int maxi = 0;\n while(left < right){\n int w = right - left;\n int h = min(height[left], height[right]);\n int area = h * w;\n maxi = max(maxi, area);\n if(height[left] < height[right]) left++;\n else if(height[left] > height[right]) right--;\n else {\n left++;\n right--;\n }\n }\n return maxi;\n }\n};\n```\nANALYSIS :-\n* **Time Complexity :-** BigO(N)\n\n* **Space COmplexity :-** BigO(1)\n\n\n | 1,002 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 9,537 | 73 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding two lines in a set of vertical lines (represented by an array of heights) that can form a container to hold the maximum amount of water. The water\'s capacity is determined by the height of the shorter line and the distance between the two lines. We want to find the maximum capacity among all possible combinations of two lines.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We use a two-pointer approach, starting with the left pointer at the leftmost edge of the array (left = 0) and the right pointer at the rightmost edge of the array (right = height.size() - 1).\n\n2. We initialize a variable maxWater to store the maximum water capacity, initially set to 0.\n\n3. We enter a while loop, which continues as long as the left pointer is less than the right pointer. This loop allows us to explore all possible combinations of two lines.\n\n4. Inside the loop, we calculate the width of the container by subtracting the positions of the two pointers: width = right - left.\n\n5. We calculate the height of the container by finding the minimum height between the two lines at positions height[left] and height[right]: h = min(height[left], height[right]).\n\n6. We calculate the water capacity of the current container by multiplying the width and height: water = width * h.\n\n7. We update the maxWater variable if the current container holds more water than the previous maximum: maxWater = max(maxWater, water).\n\n8. Finally, we adjust the pointers: if the height at the left pointer is smaller than the height at the right pointer (height[left] < height[right]), we move the left pointer to the right (left++); otherwise, we move the right pointer to the left (right--).\n\n9. We repeat steps 4-8 until the left pointer is less than the right pointer. Once the pointers meet, we have explored all possible combinations, and the maxWater variable contains the maximum water capacity.\n\n10. We return the maxWater value as the final result.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this algorithm is O(n), where n is the number of elements in the height array. This is because we explore all possible combinations of two lines once, and each operation inside the loop is performed in constant time.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1), which means the algorithm uses a constant amount of extra space regardless of the input size. We only use a few extra variables (left, right, maxWater, width, h, and water) that do not depend on the input size.\n\n---\n\n\n```C++ []\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int left = 0; // Left pointer starting from the leftmost edge\n int right = height.size() - 1; // Right pointer starting from the rightmost edge\n int maxWater = 0; // Initialize the maximum water capacity\n \n while (left < right) {\n // Calculate the width of the container\n int width = right - left;\n \n // Calculate the height of the container (the minimum height between the two lines)\n int h = min(height[left], height[right]);\n \n // Calculate the water capacity of the current container\n int water = width * h;\n \n // Update the maximum water capacity if the current container holds more water\n maxWater = max(maxWater, water);\n \n // Move the pointers towards each other\n if (height[left] < height[right]) {\n left++;\n } else {\n right--;\n }\n }\n \n return maxWater;\n }\n};\n```\n```Java []\nclass Solution {\n public int maxArea(int[] height) {\n int left = 0; // Left pointer starting from the leftmost edge\n int right = height.length - 1; // Right pointer starting from the rightmost edge\n int maxWater = 0; // Initialize the maximum water capacity\n \n while (left < right) {\n // Calculate the width of the container\n int width = right - left;\n \n // Calculate the height of the container (the minimum height between the two lines)\n int h = Math.min(height[left], height[right]);\n \n // Calculate the water capacity of the current container\n int water = width * h;\n \n // Update the maximum water capacity if the current container holds more water\n maxWater = Math.max(maxWater, water);\n \n // Move the pointers towards each other\n if (height[left] < height[right]) {\n left++;\n } else {\n right--;\n }\n }\n \n return maxWater;\n }\n}\n\n```\n```Python []\nclass Solution:\n def maxArea(self, height):\n left = 0 # Left pointer starting from the leftmost edge\n right = len(height) - 1 # Right pointer starting from the rightmost edge\n maxWater = 0 # Initialize the maximum water capacity\n \n while left < right:\n # Calculate the width of the container\n width = right - left\n \n # Calculate the height of the container (the minimum height between the two lines)\n h = min(height[left], height[right])\n \n # Calculate the water capacity of the current container\n water = width * h\n \n # Update the maximum water capacity if the current container holds more water\n maxWater = max(maxWater, water)\n \n # Move the pointers towards each other\n if height[left] < height[right]:\n left += 1\n else:\n right -= 1\n \n return maxWater\n\n```\n```Javascript []\nvar maxArea = function(height) {\n let left = 0; // Left pointer starting from the leftmost edge\n let right = height.length - 1; // Right pointer starting from the rightmost edge\n let maxWater = 0; // Initialize the maximum water capacity\n \n while (left < right) {\n // Calculate the width of the container\n let width = right - left;\n \n // Calculate the height of the container (the minimum height between the two lines)\n let h = Math.min(height[left], height[right]);\n \n // Calculate the water capacity of the current container\n let water = width * h;\n \n // Update the maximum water capacity if the current container holds more water\n maxWater = Math.max(maxWater, water);\n \n // Move the pointers towards each other\n if (height[left] < height[right]) {\n left++;\n } else {\n right--;\n }\n }\n \n return maxWater;\n};\n\n```\n```Ruby []\nclass Solution\n def max_area(height)\n left = 0 # Left pointer starting from the leftmost edge\n right = height.size - 1 # Right pointer starting from the rightmost edge\n max_water = 0 # Initialize the maximum water capacity\n \n while left < right\n # Calculate the width of the container\n width = right - left\n \n # Calculate the height of the container (the minimum height between the two lines)\n h = [height[left], height[right]].min\n \n # Calculate the water capacity of the current container\n water = width * h\n \n # Update the maximum water capacity if the current container holds more water\n max_water = [max_water, water].max\n \n # Move the pointers towards each other\n if height[left] < height[right]\n left += 1\n else\n right -= 1\n end\n end\n \n max_water\n end\nend\n\n```\n```C []\nint maxArea(int* height, int heightSize) {\n int left = 0; // Left pointer starting from the leftmost edge\n int right = heightSize - 1; // Right pointer starting from the rightmost edge\n int maxWater = 0; // Initialize the maximum water capacity\n\n while (left < right) {\n // Calculate the width of the container\n int width = right - left;\n\n // Calculate the height of the container (the minimum height between the two lines)\n int h = height[left] < height[right] ? height[left] : height[right];\n\n // Calculate the water capacity of the current container\n int water = width * h;\n\n // Update the maximum water capacity if the current container holds more water\n if (water > maxWater) {\n maxWater = water;\n }\n\n // Move the pointers towards each other\n if (height[left] < height[right]) {\n left++;\n } else {\n right--;\n }\n }\n\n return maxWater;\n}\n\n```\n\n# \uD83D\uDCA1If you come this far, then i would like to request you to please upvote this solution so that it could reach out to another one \u2763\uFE0F\uD83D\uDCA1\n\n\n\n | 1,004 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 779 | 6 | # Intuition\nThe question is similar to rainwater trapping problem. Just we do not have to slant the container.\nSo if we think to contain water between two walls of differnt length we say the water is area between two.\n\nfor say e.g 4 and 3 length walls.\nhence area between the two where the water is contained is\n`area=3*breadth;` (minimum of two) \nand if we consider the larger one then the water will overflow.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSo the basic approach i thought was to see maximal possible size between walls of differnt height and for that for every wall we have to see every possible wall which would give a time complexity of O(N^2) but the constrains are 10^4. So that would give a TLE. \n\nHence i got down to greedy 2 pointers approach where i would see the last 2 walls and calculate water contained within it. Now, if first wall is greater than last then we decrase last else first.\nBeacause the larger wall may give more optimal answer with other walls.\n`if(height[i] > height[j]) j--;\nelse i++;`\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int n = height.size()-1;\n int i=0, j=n;\n int ans=0;\n while(i <= j){\n int area=0;\n int ht = min(height[i], height[j]);\n area = (j-i)*ht;\n ans = max(ans, area);\n if(height[i] > height[j]) j--;\n else i++;\n }\n\n return ans;\n }\n};\n``` | 1,026 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 4,956 | 23 | \n# Code\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int ans = 0, n = height.size();\n int i = 0, j = n-1;\n while(i<j){\n if(height[i]>height[j]){\n ans = max(ans, (j-i)*height[j]);\n j--;\n }\n else{\n ans = max(ans, (j-i)*height[i]);\n i++;\n }\n }\n return ans;\n }\n};\n``` | 1,027 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 417 | 6 | \n\nThe strategy is to start with the container of the <i>longest</i> width and move the sides inwards one by one to see if we can get a larger area by shortening the width but getting a taller height. But how do we know which side to move?\n\nThe key insight here is that moving the <i>longer</i> side inwards is completely unnecessary because the height of the water is bounded by the <i>shorter</i> side. In other words, we will never be able to get a greater area by moving the longer side inwards because the height will either stay the same or get shorter, and the width will keep decreasing.\n\nSo we can skip all those calculations and instead move the <i>shorter</i> side inwards. This way, we <i>might</i> get a taller height and a larger area. So at each step, we calculate the area then move the shorter side inwards. When the left and right sides meet, we are done and we can return the largest area calculated so far.\n\n# Code\n```\nclass Solution(object):\n def maxArea(self, height):\n max_area = 0\n l = 0\n r = len(height) - 1\n while l < r:\n area = (r - l) * min(height[r], height[l])\n max_area = max(max_area, area)\n if height[l] < height[r]:\n l += 1\n else:\n r -= 1\n return max_area\n``` | 1,029 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 166,861 | 2,051 | I've seen some "proofs" for the common O(n) solution, but I found them very confusing and lacking. Some even didn't explain anything but just used lots of variables and equations and were like "Tada! See?". I think mine makes more sense:\n\n**Idea / Proof:**\n\n 1. The widest container (using first and last line) is a good candidate, because of its width. Its water level is the height of the smaller one of first and last line.\n 2. All other containers are less wide and thus would need a higher water level in order to hold more water.\n 3. The smaller one of first and last line doesn't support a higher water level and can thus be safely removed from further consideration.\n\n**Implementation:** (Python)\n\n class Solution:\n def maxArea(self, height):\n i, j = 0, len(height) - 1\n water = 0\n while i < j:\n water = max(water, (j - i) * min(height[i], height[j]))\n if height[i] < height[j]:\n i += 1\n else:\n j -= 1\n return water\n\n**Further explanation:**\n\nVariables `i` and `j` define the container under consideration. We initialize them to first and last line, meaning the widest container. Variable `water` will keep track of the highest amount of water we managed so far. We compute `j - i`, the width of the current container, and `min(height[i], height[j])`, the water level that this container can support. Multiply them to get how much water this container can hold, and update `water` accordingly. Next remove the smaller one of the two lines from consideration, as justified above in "Idea / Proof". Continue until there is nothing left to consider, then return the result. | 1,030 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 281,946 | 1,772 | The O(n) solution with proof by contradiction doesn\'t look intuitive enough to me. Before moving on, read any [example]() of the algorithm first if you don\'t know it yet.\n\nHere\'s another way to see what happens in a matrix representation:\n\nDraw a matrix where rows correspond to the position of the left line, and columns corresponds to the position of the right line.\n\nFor example, say `n=6`. Element at `(2,4)` would corresponds to the case where the left line is at position `2` and the right line is at position `4`. The value of the element is the volume for the case.\n\nIn the figures below, `x` means we don\'t need to compute the volume for that case, because:\n1. on the diagonal, the two lines are overlapped;\n2. the lower left triangle area of the matrix, the two lines are switched and the case is symmetric to the upper right area.\n\nWe start by computing the volume at `(1,6)`, denoted by `o`. Now if the left line is shorter than the right line, then moving the right line towards left would only decrease the volume, so all the elements left to `(1,6)` on the first row have smaller volume. Therefore, we don\'t need to compute those cases (crossed by `---`).\n \n\n 1 2 3 4 5 6\n 1 x ------- o\n 2 x x\n 3 x x x \n 4 x x x x\n 5 x x x x x\n 6 x x x x x x\n\nSo we can only move the left line towards right to `2` and compute `(2,6)`. Now if the right line is shorter, all cases below `(2,6)` are eliminated.\n\n 1 2 3 4 5 6\n 1 x ------- o\n 2 x x o\n 3 x x x |\n 4 x x x x |\n 5 x x x x x |\n 6 x x x x x x\nAnd no matter how this `o` path goes, we end up only need to find the max value on this path, which contains `n-1` cases.\n\n 1 2 3 4 5 6\n 1 x ------- o\n 2 x x - o o o\n 3 x x x o | |\n 4 x x x x | |\n 5 x x x x x |\n 6 x x x x x x\nHope this helps. I feel more comfortable seeing things this way. | 1,035 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 211 | 6 | # Intuition\nThe idea is that we gradually raise the water level up to the maximum height. And we check the permissible height with two pointers. Read more further.\n\n# Approach\n\n**Step 1**\nThe first thing we do is find the maximum height.\nThis will be our limit.\n\nfor example, let\'s take an array `height = [1,8,6,2,5,4,8,3,7]`\nThen `max = 8`\n```\nint max = 0;\nfor(int i : height){\n if(i > max){\n max = i;\n }\n}\n```\n![image.png]()\n\n**Step 2**\nWe install pointers at the edges.\nWe create an array for storing areas for each water level up to and including the maximum. That is, the size of the array will be max+1. This is possible due to the fact that the height limit is 0 < h[i] < 10,000.\n\n`val = [0,0,0,0,0,0,0,0]`\n\nWe will also need a variable to determine the water level\n `int levelIndex = 0;`\n\n![image.png]()\n\n**Step 3**\n\nThen we have the classic implementation of two pointers. While i < j we iterate.\n\nThe most interesting thing here is the conditions inside the loop. Every time we increase the water level, we have to make sure that it doesn\'t overflow over the walls.\n\nWe calculate the value of the area and write it to the array.\n`values[levelIndex++] = (j - i) * levelIndex;`\n`value = [8,0,0,0,0,0,0,0]`\n\n\n![image.png]()\n\nIn the picture below, after we have increased the amount of water to 2. We see that the left wall stops working, so we move the pointer left.\n\n![image.png]()\n`value = [8,14,0,0,0,0,0,0]`\n![image.png]()\n\nThen the cycle repeats.\n\n![image.png]()\n\n**Step 4**\n\nWe find the maximum value in the area array.\n\n`Values = [8,14,21,28,35,42,49,40]`\n\nAnswer = 49 \n\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(max)$$ \nwhere max is the maximum value of the input array height.\n\n# Code\n```\n\nclass Solution {\n public int maxArea(int[] height) {\n if(height.length == 2) return Math.min(height[0],height[1]);\n\n int max = 0;\n //find the maximum height value\n for(int i : height){\n if(i > max){\n max = i;\n }\n }\n\n int i = 0;\n int j = height.length - 1;\n int [] values = new int[max + 1]; // array for storing areas\n int levelIndex = 0;\n\n //iterate each time increasing the water level\n while (i < j){\n if(height[i] <= levelIndex){\n i++;\n }else if(height[j] <= levelIndex){\n j--;\n }else{\n values[levelIndex++] = (j - i) * levelIndex;\n }\n }\n\n int answer = 0;\n //find the maximum area value\n for(int temp : values){\n if (temp > answer) answer = temp;\n }\n\n return answer;\n }\n}\n\n```\n\n# **Please upvote, if you liked it** | 1,036 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 577 | 10 | ```\nfunction maxArea(height: number[]): number {\n let result = 0;\n \n for (let i = 0; i < height.length; i++) {\n for (let j = (height.length - 1); j >= i; j--) {\n const wi = j - i;\n const he = Math.min(height[i], height[j]);\n const area = wi * he;\n result = Math.max(result, area);\n }\n }\n \n return result;\n};\n``` | 1,043 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 11,626 | 63 | \n\n# Two Pointer Logic : TC----->O(N)\n```\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n left,right,answer=0,len(height)-1,0\n while left<=right:\n area=min(height[right],height[left])*(right-left)\n answer=max(answer,area)\n if height[right]>height[left]:\n left+=1\n else:\n right-=1\n return answer\n```\n# please upvote me it would encourage me alot\n | 1,051 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 16,036 | 100 | \n# Code\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int ans = 0, n = height.size();\n int i = 0, j = n-1;\n while(i<j){\n if(height[i]>height[j]){\n ans = max(ans, (j-i)*height[j]);\n j--;\n }\n else{\n ans = max(ans, (j-i)*height[i]);\n i++;\n }\n }\n return ans;\n }\n};\n\nDo Upvote if it helps.\n``` | 1,052 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 2,572 | 11 | # Intuition\nTwo pointer approach to solve this problem\n\n# Approach\n1. use two pointers , keep ***s at start*** and ***e at end***.\n2. move the pointer with lower height only\n3. we have to calculate the area and keep the maximum in the ***maxArea*** variable everytime\n4. return maxArea\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int maxArea = 0;\n int s = 0, e = height.size()-1;\n\n while(s < e){\n if(height[s] <= height[e]){\n maxArea = max(maxArea,(e-s) * height[s]);\n s++;\n }else{\n maxArea = max(maxArea,(e-s) * height[e]);\n e--;\n }\n }\n return maxArea;\n }\n};\n``` | 1,053 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 8,539 | 56 | # 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```\n Code in JAVA and C :-\n```\n# JAVA :-\n -- | Details | --\n--- | --- | ---:\n**Runtime** | **3** *ms* | *Beats* **92%**\n**Memory** | **50** *MB* | *Beats* **89%**\n```\nclass Solution {\n public int maxArea(int[] arr) {\n final int N = arr.length;\n int max = 0 , test, i=0, j=N-1;\n while(j>i){\n test = arr[i] < arr[j] ? arr[i] : arr[j];\n test = (j - i) * test;\n if(max < test) max = test;\n if(arr[i] < arr[j]) i++ ;\n else j--;\n }\n return max;\n }\n}\n```\n\n---\n\n# C :-\n -- | Details | --\n--- | --- | ---:\n**Runtime** | 88ms | Beats **97%**\n**Memory** | 12MB | Beats **65%**\n```\nint maxArea(int* arr, int N){\n int max = 0,test,i=0,j=N-1;\n while(j>i){\n test = arr[i];\n if(test>arr[j]) test = arr[j];\n test = (j - i) * test;\n if(max < test) max = test;\n if(arr[i] < arr[j]) i++ ;\n else j--;\n }\n return max;\n}\n```\n\n## Tom need a UPVOTE : |\n![waiting-tom-and-jerry.gif]() | 1,054 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 21,172 | 185 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nFirst, we check the widest possible container starting from the first line to the last one. Next, we ask ourselves, how is it possible to form an even bigger container? Every time we narrow the container, the width becomes smaller so the only way to get a bigger area is to find higher lines. So why not just greedily shrink the container on the side that has a shorter line? Every time we shrink the container, we calculate the area and save the maximum.\n\nTime: **O(n)** \nSpace: **O(1)**\n\nRuntime: 819 ms, faster than **75.10%** of Python3 online submissions for Container With Most Water.\nMemory Usage: 27.4 MB, less than **58.32%** of Python3 online submissions for Container With Most Water.\n\n```\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n l, r, area = 0, len(height) - 1, 0\n while l < r:\n area = max(area, (r - l) * min(height[l], height[r]))\n if height[l] < height[r]:\n\t\t\t\tl += 1\n else:\n\t\t\t\tr -= 1\n\t\t\t\t\n return area\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.** | 1,055 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 751 | 5 | # Approach\nTwo Pointer Approach\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& height) {\n int n = height.size();\n int left = 0, right = n-1;\n int maxWater = 0;\n while (left < right) {\n int area = min (height[left], height[right]) * (right - left);\n maxWater = max (maxWater, area);\n if (height[left] < height[right]) {\n left++;\n } else {\n right--;\n }\n }\n return maxWater;\n }\n};\n``` | 1,065 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 107,838 | 880 | Start by evaluating the widest container, using the first and the last line. All other possible containers are less wide, so to hold more water, they need to be higher. Thus, after evaluating that widest container, skip lines at both ends that don't support a higher height. Then evaluate that new container we arrived at. Repeat until there are no more possible containers left.\n\n**C++**\n\n int maxArea(vector<int>& height) {\n int water = 0;\n int i = 0, j = height.size() - 1;\n while (i < j) {\n int h = min(height[i], height[j]);\n water = max(water, (j - i) * h);\n while (height[i] <= h && i < j) i++;\n while (height[j] <= h && i < j) j--;\n }\n return water;\n }\n\n**C**\n\nA bit shorter and perhaps faster because I can use raw int pointers, but a bit longer because I don't have `min` and `max`.\n\n int maxArea(int* heights, int n) {\n int water = 0, *i = heights, *j = i + n - 1;\n while (i < j) {\n int h = *i < *j ? *i : *j;\n int w = (j - i) * h;\n if (w > water) water = w;\n while (*i <= h && i < j) i++;\n while (*j <= h && i < j) j--;\n }\n return water;\n } | 1,067 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 19,453 | 293 | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n***Idea:***\n\nThe first thing we should realize is that the amount of water contained is always going to be a rectangle whose area is defined as **length * width**. The width of any container will be the difference between the index of the two lines (**i** and **j**), and the height will be whichever of the two sides is the lowest (**min(H[i], H[j])**).\n\nThe brute force approach would be to compare every single pair of indexes in **H**, but that would be far too slow. Instead, we can observe that if we start with the lines on the opposite ends and move inward, the only possible time the area could be larger is when the height increases, since the width will continuously get smaller.\n\nThis is very easily observed with the use of visuals. Let\'s say we start with a graph of **H** like this:\n\n![Visual 1]()\n\nThe first step would be to find our starting container described by the lines on either end:\n\n![Visual 2]()\n\nWe can tell that the line on the right end will never make a better match, because any further match would have a smaller width and the container is already the maximum height that that line can support. That means that our next move should be to slide **j** to the left and pick a new line:\n\n![Visual 3]()\n\nThis is a clear improvement over the last container. We only moved over one line, but we more than doubled the height. Now, it\'s the line on the left end that\'s the limiting factor, so the next step will be to slide **i** to the right. Just looking at the visual, however, it\'s obvious that we can skip the next few lines because they\'re already underwater, so we should go to the first line that\'s larger than the current water height:\n\n![Visual 4]()\n\nThis time, it doesn\'t look like we made much of a gain, despite the fact that the water level rose a bit, because we lost more in width than we made up for in height. That means that we always have to check at each new possible stop to see if the new container area is better than the current best. Just lik before we can slide **j** to the left again:\n\n![Visual 5]()\n\nThis move also doesn\'t appear to have led to a better container. But here we can see that it\'s definitely possible to have to move the same side twice in a row, as the **j** line is still the lower of the two:\n\n![Visual 6]()\n\nThis is obviously the last possible container to check, and like the last few before it, it doesn\'t appear to be the best match. Still, we can understand that it\'s entirely possible for the best container in a different example to be only one index apart, if both lines are extremely tall.\n\nPutting together everything, it\'s clear that we need to make a **2-pointer sliding window solution**. We\'ll start from either end and at each step we\'ll check the container area, then we\'ll shift the lower-valued pointer inward. Once the two pointers meet, we know that we must have exhausted all possible containers and we should **return** our answer (**ans**).\n\n---\n\n***Implementation:***\n\nJavascript was weirdly more performant when using both **Math.max()** and **Math.min()** rather than performing more basic comparisons, even with duplicated effort in the ternary.\n\nFor the other languages, it made more sense (and was ultimately more performant) to only have to do the basic comparisons once each.\n\n---\n\n***Javascript Code:***\n\nThe best result for the code below is **68ms / 41.1MB** (beats 100% / 41%).\n```javascript\nvar maxArea = function(H) {\n let ans = 0, i = 0, j = H.length-1\n while (i < j) {\n ans = Math.max(ans, Math.min(H[i], H[j]) * (j - i))\n H[i] <= H[j] ? i++ : j--\n }\n return ans\n};\n```\n\n---\n\n***Python Code:***\n\nThe best result for the code below is **140ms / 16.4MB** (beats 100% / 75%).\n```python\nclass Solution:\n def maxArea(self, H: List[int]) -> int:\n ans, i, j = 0, 0, len(H)-1\n while (i < j):\n if H[i] <= H[j]:\n res = H[i] * (j - i)\n i += 1\n else:\n res = H[j] * (j - i)\n j -= 1\n if res > ans: ans = res\n return ans\n```\n\n---\n\n***Java Code:***\n\nThe best result for the code below is **1ms / 40.3MB** (beats 100% / 88%).\n```java\nclass Solution {\n public int maxArea(int[] H) {\n int ans = 0, i = 0, j = H.length-1, res = 0;\n while (i < j) {\n if (H[i] <= H[j]) {\n res = H[i] * (j - i);\n i++;\n } else {\n res = H[j] * (j - i);\n j--;\n }\n if (res > ans) ans = res;\n }\n return ans;\n }\n}\n```\n\n---\n\n***C++ Code:***\n\nThe best result for the code below is **12ms / 17.6MB** (beats 100% / 100%).\n```c++\nclass Solution {\npublic:\n int maxArea(vector<int>& H) {\n int ans = 0, i = 0, j = H.size()-1, res = 0;\n while (i < j) {\n if (H[i] <= H[j]) {\n res = H[i] * (j - i);\n i++;\n } else {\n res = H[j] * (j - i);\n j--;\n }\n if (res > ans) ans = res;\n }\n return ans;\n }\n};\n``` | 1,068 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 672 | 13 | # Intuition\nAn esoteric solution to a reasonable interview question!\n\n# Approach\nSolve normally using two pointer approach. Purposefully obfuscate to one line.\n\nUses the exec() function from Python to encode a solution into a one-line string with escape codes.\n\n\\- Please, do not do this in an interview.\n\n# Complexity\n- Time complexity:\nO(n) maybe? Underlying function is still two pointer.\n\n- Space complexity:\nexec() statement makes this abhorrent.\n\n# Code\n```\nclass Solution:\n def maxArea(self, h: List[int]) -> int:\n global w, g; w, g = 0, h; exec(\'l, r, w = 0, len(g)-1, 0\\nwhile l < r:\\n\\tw = max(w, min(g[l], g[r]) * (r-l))\\n\\tif g[l] >= g[r]: r -=1\\n\\telse: l +=1\', globals()); return w\n``` | 1,070 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 2,852 | 18 | ```\nfunction maxArea(height: number[]): number {\n let result = 0;\n \n for (let i = 0; i < height.length; i++) {\n for (let j = (height.length - 1); j >= i; j--) {\n const wi = j - i;\n const he = Math.min(height[i], height[j]);\n const area = wi * he;\n result = Math.max(result, area);\n }\n }\n \n return result;\n};\n``` | 1,076 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 6,323 | 35 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor maximinzing the area , breadth should be maximum , so thats why we start our "j" pointer from the last and "i" pointer to the start .\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# C++\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& v) {\n\n int i = 0;\n int n = v.size();\n int j = n - 1;\n int area = 0;\n\n while(j > i){\n area = max(area, min(v[i],v[j]) * abs(i - j));\n if(v[i] < v[j]) i++;\n else j--;\n }\n\n return area;\n \n }\n};\n```\n\n# Python \n```\nclass Solution:\n def maxArea(self, v):\n i = 0\n n = len(v)\n j = n - 1\n area = 0\n while j > i:\n area = max(area, min(v[i], v[j]) * abs(i - j))\n if v[i] < v[j]:\n i += 1\n else:\n j -= 1\n return area\n\n```\n\n# Java\n```\nclass Solution {\n public int maxArea(int[] arr) {\n final int N = arr.length;\n int max = 0 , area, i=0, j=N-1;\n while(j>i){\n area = arr[i] < arr[j] ? arr[i] : arr[j];\n area = (j - i) * area;\n if(max < area) max = area;\n if(arr[i] < arr[j]) i++ ;\n else j--;\n }\n return max;\n }\n}\n\n```\n# Tom need a UPVOTE : |\n\n![Upvote.gif]()\n | 1,081 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 1,039 | 5 | # Code\n```\nclass Solution {\npublic:\n int maxArea(vector<int>& nums) {\n int area = 0;\n int j = nums.size()-1;\n int i = 0;\n while(i < j){\n int temp = min(nums[i],nums[j]);\n int dist = j-i;\n int temp_area = dist*temp;\n area = max(area,temp_area);\n if(nums[i] < nums[j])\n i++;\n else\n j--;\n }\n return area;\n }\n};\n``` | 1,084 |
Container With Most Water | container-with-most-water | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. | Array,Two Pointers,Greedy | Medium | The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container. | 17,847 | 353 | The max area is calculated by the following formula:\n\n```S = (j - i) * min(ai, aj)```\n\nWe should choose (i, j) so that S is max. Note that ```i, j``` go through the range (1, n) and j > i. That\'s it.\n\nThe simple way is to take all possibilities of (i, j) and compare all obtained S. The time complexity is ```n * (n-1) / 2```\n\nWhat we gonna do is to choose all possibilities of (i, j) in a wise way. I noticed that many submitted solutions here can\'t explain why when :\n* ```ai < aj``` we will check the next ```(i+1, j)``` (or move i to the right)\n* ```ai >= aj``` we will check the next ```(i, j-1)``` (or move j to the left)\n\nHere is the explaination for that:\n\n* When ```ai < aj``` , we don\'t need to calculate all ```(i, j-1)```, ```(i, j-2)```, .... Why? because these max areas are smaller than our S at ```(i, j)```\n\n**Proof**: Assume at ```(i, j-1)``` we have ```S\'= (j-1-i) * min(ai, aj-1)```\n```S\'< (j-1-i) * ai < (j-i) * ai = S```, and when ```S\'<S```, we don\'t need to calculate\nSimilar at ```(i, j-2)```, ```(i, j-3)```, etc.\n\nSo, that\'s why when ```ai < aj```, we should check the next at ```(i+1, j)``` (or move i to the right)\n\n* When ```ai >= aj```, the same thing, all ```(i+1, j)```, ```(i+2, j)```, .... are not needed to calculate.\n\nWe should check the next at ```(i, j-1)``` (or move j to the left)\n\n```\n\t\tint S = 0, i = 0, j = A.length -1;\n while (i < j) {\n S = Math.max(S, (j - i) * Math.min(A[i], A[j]));\n if (A[i] < A[j]) i++; else j--;\n }\n return S;\n```\n\n\n\n\n\n\n\n | 1,089 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 68,948 | 431 | \n\n# Code\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};\n string tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n string hrns[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};\n string ths[]={"","M","MM","MMM"};\n \n return ths[num/1000] + hrns[(num%1000)/100] + tens[(num%100)/10] + ones[num%10];\n }\n};\n```\n\n# ***Please Upvote if it helps \u2764\uFE0F*** | 1,100 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 179,224 | 2,521 | ```\npublic static String intToRoman(int num) {\n String M[] = {"", "M", "MM", "MMM"};\n String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};\n String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};\n String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};\n return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];\n}\n``` | 1,105 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 38,411 | 233 | # Intuition of this Problem:\nThis code takes a non-negative integer as input and converts it into its corresponding Roman numeral representation. The approach used here is to store the Roman numeral values and their corresponding symbols in a vector of pairs. The algorithm then iterates through the vector and repeatedly adds the corresponding symbols to the result string while subtracting the corresponding value from the input integer until the input integer becomes zero.\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Initialize an empty string called Roman to store the resulting Roman numeral.\n2. Create a vector of pairs called storeIntRoman, to store the Roman numeral values and their corresponding symbols.\n3. Iterate through the storeIntRoman vector using a for loop.\n4. For each pair, check if the input integer is greater than or equal to the Roman numeral value.\n5. If it is, add the corresponding symbol to the Roman string and subtract the corresponding value from the input integer.\n6. Repeat steps 4-5 until the input integer becomes zero.\n7. Return the Roman string.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\n//Approach 1 : \n//time complexity - O(1) since the algorithm always iterates through a constant number of values (13 in this case).\n//O(1) since the amount of extra space used is constant (the size of the storeIntRoman vector, which is also 13 in this case\nclass Solution {\npublic:\n string intToRoman(int num) {\n string Roman = "";\n // Creating vector of pairs to store the Roman numeral values and their corresponding symbols\n vector<pair<int, string>> storeIntRoman = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};\n // Iterating through the vector and repeatedly adds the corresponding symbols to the result string while subtracting the corresponding value from the input integer until the input integer becomes zero.\n for (int i = 0; i < storeIntRoman.size(); i++) {\n while (num >= storeIntRoman[i].first) {\n Roman += storeIntRoman[i].second;\n num -= storeIntRoman[i].first;\n }\n }\n return Roman;\n }\n};\n```\n```C++ []\n//Approach 2\n//time complexity - O(1) since the algorithm always iterates through a constant number of values (13 in this case).\n//O(1) since the amount of extra space used is constant (the size of the storeIntRoman vector, which is also 13 in this case\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};\n string tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};\n string hundreds[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};\n string thousands[]= {"", "M", "MM", "MMM"};\n \n string Roman = thousands[num / 1000] + hundreds[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];\n return Roman;\n }\n};\n```\n```Java []\nclass Solution {\n public String intToRoman(int num) {\n String Roman = "";\n int[][] storeIntRoman = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};\n for (int i = 0; i < storeIntRoman.length; i++) {\n while (num >= storeIntRoman[i][0]) {\n Roman += storeIntRoman[i][1];\n num -= storeIntRoman[i][0];\n }\n }\n return Roman;\n }\n}\n\n```\n```Python []\nclass Solution:\n def intToRoman(self, num: int) -> str:\n Roman = ""\n storeIntRoman = [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]]\n for i in range(len(storeIntRoman)):\n while num >= storeIntRoman[i][0]:\n Roman += storeIntRoman[i][1]\n num -= storeIntRoman[i][0]\n return Roman\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(13) = O(1)** - Approach 1\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(13) = O(1)** - Approach 1\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 1,106 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 26,666 | 581 | ```\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};\n string tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n string hrns[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};\n string ths[]={"","M","MM","MMM"};\n \n return ths[num/1000] + hrns[(num%1000)/100] + tens[(num%100)/10] + ones[num%10];\n }\n};\n``` | 1,107 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 4,981 | 66 | # Intuition\nMy initial approach to solving this problem involves converting an integer to its Roman numeral representation using a predefined set of values and corresponding Roman numeral symbols.\n\n# Approach\nTo achieve this, I utilize a greedy approach where I repeatedly subtract the largest possible value from the given number while appending the corresponding Roman numeral symbol to the result string. I maintain two arrays: `values`, which contains the integer values corresponding to Roman numerals, and `romanNumerals`, which contains the corresponding Roman numeral symbols.\n\nStarting with the largest value, I iterate through the `values` array and at each step, I check if the current value can be subtracted from the given number. If it can be, I append the corresponding Roman numeral symbol to the result string and subtract the value from the number. If not, I move on to the next smaller value.\n\nI continue this process until the given number becomes zero, and the result string represents the Roman numeral equivalent of the original number.\n\n\n# Code\n```java\nclass Solution {\n public String intToRoman(int num) {\n \n int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n String[] romanNumerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};\n\n StringBuilder sb = new StringBuilder();\n\n int i = 0;\n \n while (num > 0) {\n if (num >= values[i]) {\n \n sb.append(romanNumerals[i]);\n num -= values[i];\n } else {\n i++;\n }\n }\n\n return sb.toString();\n }\n}\n\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]() | 1,108 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 22,457 | 170 | **\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: \n\n**Solution:**\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n # Creating Dictionary for Lookup\n num_map = {\n 1: "I",\n 5: "V", 4: "IV",\n 10: "X", 9: "IX",\n 50: "L", 40: "XL",\n 100: "C", 90: "XC",\n 500: "D", 400: "CD",\n 1000: "M", 900: "CM",\n }\n \n # Result Variable\n r = \'\'\n \n \n for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:\n # If n in list then add the roman value to result variable\n while n <= num:\n r += num_map[n]\n num-=n\n return r\n```\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.** | 1,109 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 529 | 5 | # Intuition\n<!-- Describe your first thougStringhts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create two arrays, one to store the Roman numerals and the other to store their corresponding values.\n2. Initialize a StringBuilder to store the Roman numeral representation of the integer.\n3. Iterate over the arrays in parallel.\n4. While the integer is greater than or equal to the value at the current index of the values array, append the Roman numeral at the corresponding index of the notations array to the StringBuilder.\n5. Decrement the integer by the value at the current index of the values array.\n6. Repeat steps 4 and 5 until the integer is less than the value at the first index of the values array.\n7. Return the String representation of the StringBuilder\n\n\n\n\n# Code\n```\nclass Solution {\n public String intToRoman(int num) {\n int []values={1000,900,500,400,100,90,50,40,10,9,5,4,1};\n String []notations={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n StringBuilder sb=new StringBuilder();\n\n for(int i=0;i<values.length;i++){\n while(num>=values[i])\n {\n num-=values[i];\n sb.append(notations[i]);\n }\n }\n\n return sb.toString();\n }\n}\n``` | 1,110 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 1,950 | 5 | ```\nclass Solution {\npublic:\n string intToRoman(int num) {\n vector<pair<int, string>> map{{1, "I"}, {4, "IV"}, {5, "V"}, {9, "IX"}, {10, "X"}, {40, "XL"}, {50, "L"}, \n\t\t{90, "XC"}, {100, "C"}, {400, "CD"}, {500, "D"}, {900, "CM"}, {1000, "M"}};\n int l = map.size()-1;\n string s="";\n \n while(num!=0){\n while(map[l].first>num){\n l--;\n }\n s += map[l].second;\n num -= map[l].first;\n }\n return s;\n }\n};\n\n``` | 1,111 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 956 | 10 | # 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```\nimport java.util.Enumeration;\nimport java.util.Hashtable;\n\nclass Solution {\n public static String intToRoman(int num)\n {\n StringBuilder s = new StringBuilder();\n\n Hashtable<Integer , String > list = new Hashtable<>();\n list.put(1 , "I");\n list.put(4 , "IV");\n list.put(5 , "V");\n list.put(9 , "IX");\n list.put(10 , "X");\n list.put(40 , "XL");\n list.put(50 , "L");\n list.put(90 , "XC");\n list.put(100 , "C");\n list.put(400 , "CD");\n list.put(500 , "D");\n list.put(900 , "CM");\n list.put(1000 , "M");\n \n while (num > 0)\n {\n int maxkey = getMaxKey(list , num);\n s.append(list.get(maxkey));\n num -= maxkey;\n }\n return s.toString();\n }\n\n public static int getMaxKey(Hashtable list , int target)\n {\n int maxKey = -1;\n\n Enumeration<Integer> keys = list.keys();\n while (keys.hasMoreElements()) {\n int key = keys.nextElement();\n if (key <= target && key > maxKey) {\n maxKey = key;\n }\n }\n return maxKey;\n }\n}\n```\n\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository]()\n\n\n![e78315ef-8a9d-492b-9908-e3917f23eb31_1674946036.087042.jpeg]()\n | 1,112 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 505 | 5 | # Approach 1\n\n\n# Complexity\n- Time complexity:\n$$O(1)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n vector <string> s = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};\n vector <int> value = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};\n string ans = "";\n int i = value.size() - 1; \n while (i >= 0 ) {\n if (num < value[i]) {\n i--;\n } else {\n ans += s[i];\n num -= value[i];\n } \n }\n return ans;\n};\n```\n\n# Approach 2\n\n\n# Complexity\n- Time complexity:\n$$O(1)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n vector <string> ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};\n vector <string> tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};\n vector <string> hrns = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};\n vector <string> ths = {"", "M", "MM", "MMM"};\n \n return ths[num/1000] + hrns[(num%1000)/100] + tens[(num%100)/10] + ones[num%10];\n }\n};\n``` | 1,116 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 18,943 | 124 | **Please connect with me if u like my solution**\n**Please Upvote**\n\n\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n int normal[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};\n string roman[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n string res;\n for(int i=0;i<13;i++){\n while(num>=normal[i]){\n res.append(roman[i]);\n num-=normal[i];\n }\n }\n return res;\n }\n};\n``` | 1,117 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 14,699 | 50 | # Intuition:\nThe given problem is about converting an integer into a Roman numeral. To do this, we can create arrays that represent the Roman numeral symbols for each place value (ones, tens, hundreds, thousands). Then, we can divide the given number into its respective place values and concatenate the corresponding Roman numeral symbols.\n\n# Approach:\n1. Create four arrays: `ones`, `tens`, `hrns`, and `ths`, representing the Roman numeral symbols for ones, tens, hundreds, and thousands respectively. Each array contains the symbols for the numbers from 0 to 9 in their respective place value.\n2. Divide the given number `num` into its respective place values:\n - `thousands = num / 1000`\n - `hundreds = (num % 1000) / 100`\n - `tens = (num % 100) / 10`\n - `ones = num % 10`\n3. Concatenate the Roman numeral symbols based on the place values:\n - `ths[num/1000]` represents the Roman numeral for thousands place.\n - `hrns[(num%1000)/100]` represents the Roman numeral for hundreds place.\n - `tens[(num%100)/10]` represents the Roman numeral for tens place.\n - `ones[num%10]` represents the Roman numeral for ones place.\n4. Return the concatenation of the Roman numeral symbols obtained from step 3.\n\n# Complexity:\n- Time complexity: O(1) because the number of digits in the given number is constant (up to 4 digits for the given range).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) because the arrays storing the Roman numeral values have fixed sizes.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n# C++\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};\n string tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n string hrns[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};\n string ths[]={"","M","MM","MMM"};\n \n return ths[num/1000] + hrns[(num%1000)/100] + tens[(num%100)/10] + ones[num%10];\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public String intToRoman(int num) {\n String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};\n String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};\n String[] hrns = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};\n String[] ths = {"", "M", "MM", "MMM"};\n\n return ths[num / 1000] + hrns[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];\n }\n}\n\n```\n\n---\n# JavaScript\n```\nvar intToRoman = function(num) {\n const ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];\n const tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];\n const hrns = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];\n const ths = ["", "M", "MM", "MMM"];\n return ths[Math.floor(num / 1000)] + hrns[Math.floor((num % 1000) / 100)] + tens[Math.floor((num % 100) / 10)] + ones[num % 10];\n};\n```\n---\n# Python\n```\nclass Solution:\n def intToRoman(self, num):\n ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]\n tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]\n hrns = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]\n ths = ["", "M", "MM", "MMM"]\n\n return ths[num / 1000] + hrns[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10]\n\n``` | 1,118 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 1,447 | 5 | ```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n symbolMap = {\n 1 : "I", \n 5 : \'V\', \n 10 : "X", \n 50 : "L", \n 100 : "C", \n 500 : "D", \n 1000 : "M"\n }\n \n res = [] \n while num >= 1000: \n res.append(symbolMap[1000])\n num -= 1000 \n \n while num >= 900: \n res.append(symbolMap[100])\n res.append(symbolMap[1000])\n num -= 900 \n \n while num >= 500: \n res.append(symbolMap[500])\n num -= 500\n \n while num >= 400: \n res.append(symbolMap[100])\n res.append(symbolMap[500])\n num -= 400 \n \n while num >= 100: \n res.append(symbolMap[100])\n num -= 100 \n \n while num >= 90: \n res.append(symbolMap[10])\n res.append(symbolMap[100])\n num -= 90 \n \n while num >= 50: \n res.append(symbolMap[50])\n num -= 50 \n \n while num >= 40: \n res.append(symbolMap[10])\n res.append(symbolMap[50])\n num -= 40 \n \n while num >= 10: \n res.append(symbolMap[10])\n num -= 10\n \n while num >= 9: \n res.append(symbolMap[1])\n res.append(symbolMap[10])\n num -= 400 \n \n while num >= 5:\n res.append(symbolMap[5])\n num -= 5 \n \n while num >= 4: \n res.append(symbolMap[1])\n res.append(symbolMap[5])\n num -= 400 \n \n while num >= 1: \n res.append(symbolMap[1])\n num -= 1 \n \n return "".join(res)\n``` | 1,124 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 95,574 | 695 | Reference:\n\n\npublic class Solution {\n public String intToRoman(int num) {\n \n int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};\n String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n \n StringBuilder sb = new StringBuilder();\n \n for(int i=0;i<values.length;i++) {\n while(num >= values[i]) {\n num -= values[i];\n sb.append(strs[i]);\n }\n }\n return sb.toString();\n }\n} | 1,126 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 4,874 | 5 | This problem is the Daily LeetCoding Challenge for October, Day 20.
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⭐**]() 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 2 approaches in the official solution</summary>
**Approach 1:** Greedy
**Approach 2:** Hardcode Digits
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**]()!
---
<br>
<p align="center">
<a href="" target="_blank">
<img src="" width="560px" />
</a>
</p>
<br> | 1,129 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 623 | 5 | \n# Code\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n vector<pair<int, string>> map{{1, "I"}, {4, "IV"}, {5, "V"}, {9, "IX"}, {10, "X"}, {40, "XL"}, {50, "L"}, \n\t\t{90, "XC"}, {100, "C"}, {400, "CD"}, {500, "D"}, {900, "CM"}, {1000, "M"}};\n int l = map.size()-1;\n string s="";\n \n while(num!=0){\n while(map[l].first>num){\n l--;\n }\n s += map[l].second;\n num -= map[l].first;\n }\n return s;\n }\n};\n``` | 1,130 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 434 | 8 | ```\nclass Solution {\n public String intToRoman(int n) {\n \n String units[]={"","I","II","III","IV","V","VI","VII","VIII","IX"};\n \n String tens[]={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n \nString hundreds[]= {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};\n \nString thousands[]={"","M","MM","MMM"};\n\n \n return (thousands[n/1000]+\n hundreds[(n % 1000)/100]+\n tens[(n%100)/10]+\n units[n%10]);\n \n \n }\n} \n``` | 1,137 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 2,462 | 27 | [Watch]()\n\n\n\n\nAlso you can SUBSCRIBE \uD83E\uDC81 \uD83E\uDC81 \uD83E\uDC81 this channel for the daily leetcode challange solution.\n\n\n\n \u2B05\u2B05 Telegram link to discuss leetcode daily questions and other dsa problems\n**C++**\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n vector<pair<int, string>> vm = {{1000, "M"},{900, "CM"} , {500, "D"},{400, "CD"} , {100, "C"} , {90, "XC"}, {50, "L"}, {40, "XL"},{10, "X"}, {9, "IX"},{5, "V"} , {4, "IV"},{1, "I"} };\n string s_ans = "";\n while(num > 0){\n for(auto x : vm){\n if(num >= x.first){\n s_ans += x.second;\n num = num - x.first;\n break;\n }\n }\n }\n \n return s_ans;\n }\n};\n```\n**If you find my solution helpful please upvote it.** | 1,138 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 5,904 | 37 | \n\n# Python Solution\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n M=["","M","MM","MMM"]\n C=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"]\n X=["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"]\n I=["","I","II","III","IV","V","VI","VII","VIII","IX"]\n return M[num//1000]+C[num%1000//100]+X[num%1000%100//10]+I[num%1000%100%10]\n```\n# please upvote me it would encourage me alot\n | 1,141 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 18,397 | 152 | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nJust like Roman to Integer, this problem is most easily solved using a **lookup table** for the conversion between digit and numeral. In this case, we can easily deal with the values in descending order and insert the appropriate numeral (or numerals) as many times as we can while reducing the our target number (**N**) by the same amount.\n\nOnce **N** runs out, we can **return ans**.\n\n---\n\n#### ***Implementation:***\n\nJava\'s **StringBuilder** can take care of repeated string concatenations without some of the overhead of making string copies.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **124ms / 43.5MB** (beats 100% / 100%).\n```javascript\nconst val = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\nconst rom = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]\n\nvar intToRoman = function(N) {\n let ans = ""\n for (let i = 0; N; i++)\n while (N >= val[i]) ans += rom[i], N -= val[i]\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **40ms / 14.1MB** (beats 95% / 86%).\n```python\nval = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\nrom = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]\n\nclass Solution:\n def intToRoman(self, N: int) -> str:\n ans = ""\n for i in range(13):\n while N >= val[i]:\n ans += rom[i]\n N -= val[i]\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **3ms / 38.1MB** (beats 100% / 95%).\n```java\nclass Solution {\n final static int[] val = {1000,900,500,400,100,90,50,40,10,9,5,4,1};\n final static String[] rom = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n\n public String intToRoman(int N) {\n StringBuilder ans = new StringBuilder();\n for (int i = 0; N > 0; i++)\n while (N >= val[i]) {\n ans.append(rom[i]);\n N -= val[i];\n }\n return ans.toString();\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 5.8MB** (beats 100% / 98%).\n```c++\nclass Solution {\npublic:\n const int val[13] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};\n const string rom[13] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n\n string intToRoman(int N) {\n string ans = "";\n for (int i = 0; N; i++)\n while (N >= val[i]) ans += rom[i], N -= val[i];\n return ans;\n }\n};\n``` | 1,143 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 2,279 | 8 | # 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![image.png]()\n\n# Code\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n x = \'\'\n while num!=0:\n if num>= 1000:\n x+=\'M\'\n num-=1000\n elif num>= 900:\n x+=\'CM\'\n num-=900\n elif num>= 500:\n x+=\'D\'\n num-= 500\n elif num>= 400: \n x+=\'CD\' \n num-= 400\n elif num>= 100:\n x+=\'C\'\n num-=100\n elif num>= 90:\n x+=\'XC\' \n num-=90\n elif num>= 50:\n x+=\'L\' \n num-=50\n elif num>= 40:\n x+=\'XL\' \n num-=40\n elif num>= 10:\n x+=\'X\' \n num-=10\n elif num>= 9:\n x+=\'IX\' \n num-=9\n elif num>= 5:\n x+=\'V\' \n num-=5\n elif num>= 4:\n x+=\'IV\' \n num-=4\n else:\n x+=\'I\'\n num-=1\n return x\n``` | 1,153 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 5,518 | 39 | I do my best everyday to give a clear explanation, so to help everyone improve their skills.\n\nIf you find this **helpful**, please \uD83D\uDC4D **upvote** this post and watch my [Github Repository]().\n\nThank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.\n\n---\n\n#### Java - Using Dictionary - Approach 1\n\n```\npublic String intToRoman(int num) {\n\n // Approach:\n // This method uses two arrays with the corresponding integer-roman map, in descending order.\n\n int[] value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};\n\n StringBuilder romanNumeral = new StringBuilder();\n\n for (int i = 0; i < value.length && num > 0; i++) {\n // Check from the highest value, 1000 to the smallest.\n // If it is possible to subtract, for example 400, we know the roman numeral next is "CD".\n while (num >= value[i]) {\n romanNumeral.append(roman[i]);\n num -= value[i];\n }\n }\n return romanNumeral.toString();\n }\n```\n---\n\n#### Java - Without Dictionary - Approach 2\n```\nclass Solution {\n public String intToRoman(int num) {\n String romanNumeral = "";\n while (num >= 1000) {\n romanNumeral += "M";\n num -= 1000;\n }\n while (num >= 900) {\n romanNumeral += "CM";\n num -= 900;\n }\n while (num >= 500) {\n romanNumeral += "D";\n num -= 500;\n }\n while (num >= 400) {\n romanNumeral += "CD";\n num -= 400;\n }\n while (num >= 100) {\n romanNumeral += "C";\n num -= 100;\n }\n while (num >= 90) {\n romanNumeral += "XC";\n num -= 90;\n }\n while (num >= 50) {\n romanNumeral += "L";\n num -= 50;\n }\n while (num >= 40) {\n romanNumeral += "XL";\n num -= 40;\n }\n while (num >= 10) {\n romanNumeral += "X";\n num -= 10;\n }\n while (num >= 9) {\n romanNumeral += "IX";\n num -= 9;\n }\n while (num >= 5) {\n romanNumeral += "V";\n num -= 5;\n }\n while (num >= 4) {\n romanNumeral += "IV";\n num -= 4;\n }\n while (num >= 1) {\n romanNumeral += "I";\n num -= 1;\n }\n\n return romanNumeral;\n }\n}\n``` | 1,155 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 914 | 5 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string intToRoman(int num) \n {\n int normal[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};\n string roman[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n string rom;\n for(int i=0;i<13;i++){\n while(num>=normal[i]){\n rom.append(roman[i]);\n num-=normal[i];\n }\n }\n return rom;\n }};\n``` | 1,160 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 1,054 | 10 | ```\nclass Solution:\n def intToRoman(self, num: int) -> str: \n\n mils = ["", "M", "MM", "MMM"]\n\n cens = [ "", "C", "CC", "CCC", "CD",\n "D", "DC", "DCC", "DCCC", "CM"]\n\n decs = [ "", "X", "XX", "XXX", "XL",\n "L", "LX", "LXX", "LXXX", "XC"]\n\n unes = [ "", "I", "II", "III", "IV",\n "V", "VI", "VII", "VIII", "IX"] # EX: num = 2579\n\n m, num = divmod(num,1000) # m = 2 num = 579\n c, num = divmod(num,100 ) # m = 5 num = 79\n d, u = divmod(num,10 ) # m = 7 u = 9\n\n return mils[m]+cens[c]+decs[d]+unes[u] # mils[2]+cens[5]+decs[7]+unes[9] = MM + D + LXX + IX = MMDLXXIX \n```\n[](http://) | 1,162 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 432 | 8 | ```\n\tpublic String intToRoman(int num) {\n TreeMap<Integer, String> tm = new TreeMap<Integer, String>();\n tm.put(1,"I");\n tm.put(5,"V");\n tm.put(10,"X");\n tm.put(50,"L");\n tm.put(100,"C");\n tm.put(500,"D");\n tm.put(1000,"M");\n tm.put(4,"IV");\n tm.put(9,"IX");\n tm.put(40,"XL");\n tm.put(90,"XC");\n tm.put(400,"CD");\n tm.put(900,"CM");\n \n StringBuilder romanNumeral = new StringBuilder("");\n while(num > 0){\n int nearestNum = tm.floorKey(num);\n romanNumeral.append(tm.get(nearestNum));\n num = num - nearestNum;\n }\n \n return romanNumeral.toString();\n \n }\n\n``` | 1,164 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 2,685 | 21 | ```\nstring intToRoman(int num) {\n string str[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};\n int val[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n string ans;\n for (int i=0; i<13; i++) {\n for (int j=0; j<(num/val[i]); j++) {\n ans += str[i];\n }\n num %= val[i];\n }\n return ans;\n}\n```\nHelpful? | 1,165 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 18,970 | 300 | class Solution {\n public:\n string intToRoman(int num) \n {\n string res;\n string sym[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};\n int val[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n \n for(int i=0; num != 0; i++)\n {\n while(num >= val[i])\n {\n num -= val[i];\n res += sym[i];\n }\n }\n \n return res;\n }\n }; | 1,166 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 4,579 | 20 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n Easiest Approaah using arrays \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n store the info and use it\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n# Code\n```\nclass Solution {\n public String intToRoman(int num) {\n String[] s={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n int[] values={1000,900,500,400,100,90,50,40,10,9,5,4,1};\n String t="";\n int i=0;\n while(num>0){\n if(num>=values[i]){\n t+=s[i];\n num-=values[i];\n }\n else\n i++;\n }\n return t;\n }\n}\n``` | 1,169 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 413 | 6 | ```\nclass Solution {\npublic:\n // creating int to roman map.\n unordered_map<int,char>itor={\n {1,\'I\'},{5,\'V\'},{10,\'X\'},{50,\'L\'},{100,\'C\'},{500,\'D\'},{1000,\'M\'}\n };\n // reverse the string.\n void reverse(string &s)\n {\n int i=0,j=s.length()-1;\n while(i<j)\n {\n swap(s[i],s[j]);\n i++;j--;\n }\n }\n // main function.\n string intToRoman(int num) {\n \n string res="";\n //Multiplier to determine once,tens... places\n int mul=1;\n while(num)\n {\n int x=num%10; //last digit\n num/=10; //removing last digit from num.\n if(x==0) //if zero then move to next digit (with increasing multiplier).\n {\n mul*=10;\n continue;\n }\n // we have two cases 4 and 9 then make b=5 || 10.\n int b=-1;\n if(x==4)\n b=5;\n else if(x==9)\n b=10;\n \n if(b==-1) //if last digit is not 4||9 then simply add I. for 3= III\n {\n while(x)\n {\n if(x==5)\n {\n res+=itor[5*mul];\n x-=5;\n }\n else\n {\n res+=itor[1*mul];\n x-=1;\n }\n }\n }\n else // if(last digit is 4||9) then add IV or IX to res.\n {\n res+=itor[b*mul];\n res+=itor[1*mul];\n }\n mul*=10;\n }\n //we traversed from lsb to msb so reverse the string.\n reverse(res);\n return res;\n // remember if 4 comes then we add VI to res so that reverse will be IV.\n }\n};\n``` | 1,172 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 236 | 9 | **METHOD 1: Short and easy**\n\nEach quotient will tell how much is the value / what should be the Roman Symbol\n\n//KHELO DIMAAG SE XD\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};\n string tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n string hrns[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};\n string ths[]={"","M","MM","MMM"};\n \n return ths[num/1000] + hrns[(num%1000)/100] + tens[(num%100)/10] + ones[num%10];\n }\n};\n\n```\n\n**Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F\nIf you have some \uD83E\uDD14 doubts feel free to bug me (^~^)***\n```\n\n```\n\n**METHOD 2: correct but quite bulky ;)**\n\nSuppose num = 1984\nwe split it as : 1000 + 900 + 80 + 4 \nand at each iteration compare it\'s value.\n\nSpecial cases are dealt separately. (4,9,40,90,400,90)\n\n80 is internally split as : 50 + 10 +10 +10\nSEE RANGES of num in the if-else ladder \n\nand atlast we do num = num - val;\n\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ans="";\n int val=1;\n while(num>0){\n string ch="";\n if(num>=1000)\n val=1000;\n else if(num>=900)\n val=900;\n else if(num>=500)\n val=500;\n else if(num>=400)\n val=400;\n else if(num>=100)\n val=100;\n else if(num>=90)\n val=90;\n else if(num>=50)\n val=50;\n else if(num>=40)\n val=40;\n else if(num>=10)\n val=10;\n else if(num==9)\n val=9;\n else if(num>=5)\n val=5;\n else if(num==4)\n val=4;\n else if(num>=1)\n val=1;\n \n switch(val){\n case 1: ch="I";break;\n case 5: ch="V";break;\n case 10: ch="X";break;\n case 50: ch="L";break;\n case 100: ch="C";break;\n case 500: ch="D";break;\n case 1000: ch="M";break;\n case 4: ch="IV";break;\n case 9: ch="IX";break;\n case 40: ch="XL";break;\n case 90: ch="XC";break;\n case 400: ch="CD";break;\n case 900: ch="CM";break;\n }\n ans+=ch;\n num=num-val;\n }\n return ans;\n }\n};\n\n```\n | 1,176 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 44,076 | 262 | \n def intToRoman1(self, num):\n values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ]\n numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ]\n res, i = "", 0\n while num:\n res += (num//values[i]) * numerals[i]\n num %= values[i]\n i += 1\n return res\n \n def intToRoman(self, num):\n values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ]\n numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ]\n res = ""\n for i, v in enumerate(values):\n res += (num//v) * numerals[i]\n num %= v\n return res | 1,177 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 2,016 | 17 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using String + Hash Table + Math.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the all the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is given in code comment.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity is given in code comment.\n\n# Code\n```\n/*\n\n Time Complexity : O(1), We are scanning Array(val) of the number one by one therefore, the maximum time can\n be used to iterate over Array(val) is O(1) which is constant because we can maximum do around 18 iteration\n which is constant.\n\n Space Complexity : O(1), We are using integer arrays and one string array whose sizes don\u2019t depend on the\n input size hence the space complexity will be O(1).\n\n Solved using String + Hash Table + Math.\n\n*/\n\n\n/***************************************** Approach 1 *****************************************/\n\nclass Solution {\npublic:\n string intToRoman(int num) {\n string res;\n string sym[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};\n int val[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n\n for(int i=0; num != 0; i++){\n while(num >= val[i]){\n num -= val[i];\n res += sym[i];\n }\n }\n return res;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(1), We are scanning each digit of the number one by one therefore, the time complexity\n will be O(log10N). But N cannot be grater than 3999, therefore, the maximum time can be O(loh103999) ~= \n O(3.60) which is constant hence the overall time complexity will be O(1).\n\n Space Complexity : O(1), We are using four arrays whose sizes don\u2019t depend on the input size hence the space\n complexity will be O(1).\n\n Solved using String + Hash Table + Math.\n\n*/\n\n\n/***************************************** Approach 2 *****************************************/\n\nclass Solution {\npublic:\n string intToRoman(int num) {\n vector<string> ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};\n vector<string> tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};\n vector<string> hundred = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};\n vector<string> thousand = {"", "M", "MM", "MMM"};\n \n string ans = "";\n \n ans += thousand[num/1000] + hundred[(num%1000)/100] + tens[(num%100)/10] + ones[num%10];\n return ans;\n }\n};\n\n\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]() | 1,179 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 1,123 | 6 | # Code\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n roman_mapping = {\n 1000: \'M\',\n 900: \'CM\',\n 500: \'D\',\n 400: \'CD\',\n 100: \'C\',\n 90: \'XC\',\n 50: \'L\',\n 40: \'XL\',\n 10: \'X\',\n 9: \'IX\',\n 5: \'V\',\n 4: \'IV\',\n 1: \'I\'\n }\n result = ""\n for value, symbol in roman_mapping.items():\n while num >= value:\n result += symbol\n num -= value\n return result\n\n``` | 1,181 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 525 | 7 | Initially we need to store all the integer values which have specific roman values.\nThen we will extract the key in sorted order (biggest to smallest) and check again and again if number is greater than the key then subtract the key from number and also add the roman in the answer.\n\n\n\n```\nclass Solution {\npublic:\n string intToRoman(int num) {\n // map is decreasing sorted by key\n map<int, string, greater<int>> m;\n m[1000] = "M";\n m[900] = "CM";\n m[500] = "D";\n m[400] = "CD";\n m[100] = "C";\n m[90] = "XC";\n m[50] = "L";\n m[40] = "XL";\n m[10] = "X";\n m[9] = "IX";\n m[5] = "V";\n m[4] = "IV";\n m[1] = "I";\n \n string ans = "";\n\t\t// take pair from map\n for(auto p: m)\n {\n // if number is lesser or equal to key then add\n while(num >= p.first)\n {\n ans += p.second;\n num -= p.first;\n }\n }\n \n return ans;\n }\n};\n | 1,183 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 1,104 | 10 | **IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n**** \n**Python.** This [**solution**]() employs a repetition of Roman digits. It demonstrated **47 ms runtime (96.77%)** and used **13.9 MB memory (35.57%)**. Time complexity is contstant: **O(1)**. Space complexity is constant: **O(1)**.\n```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n \n\t\t# Starting from Python 3.7, dictionary order is guaranteed \n\t\t# to be insertion order\n num_to_roman = { 1000 : "M", 900 : "CM", 500 : "D", 400 : "CD",\n 100 : "C", 90 : "XC", 50 : "L", 40 : "XL",\n 10 : "X", 9 : "IX", 5 : "V", 4 : "IV",\n 1 : "I" }\n roman: str = ""\n\n # The idea is to repeat each of Roman digits as many times\n # as needed to cover the decimal representation.\n for i, r in num_to_roman.items():\n roman += r * (num // i)\n num %= i\n else:\n return roman\n```\n**** \n**Rust.** This [**solution**]() employs a brute force digit substitution. It demonstrated **0 ms runtime (100.00%)** and used **2.0 MB memory (94.20%)**. Time complexity is constant: **O(1)**. Space complexity is constant: **O(1)**.\n```\nconst ONES : [&str;10] = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];\nconst TENS : [&str;10] = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];\nconst CENT : [&str;10] = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];\nconst MILS : [&str;4] = ["", "M", "MM", "MMM"];\n\nimpl Solution \n{\n pub fn int_to_roman(num: i32) -> String \n {\n // Given that the number of outcomes is small, a brute force\n\t\t// substituion for each power of ten is a viable solution...\n\t\tformat!("{}{}{}{}", MILS[(num / 1000 % 10) as usize],\n CENT[(num / 100 % 10) as usize],\n TENS[(num / 10 % 10) as usize],\n ONES[(num % 10) as usize])\n }\n}\n```\n**** \n**\u0421++.** This [**solution**]() employs an iterative build-up of a Roman number. It demonstrated **0 ms runtime (100.0%)** and used **6.1 MB memory (47.60%)**. Time complexity is constant: **O(1)**. Space complexity is constant: **O(1)**.\n```\nclass Solution \n{\n const int intgr[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n const string roman[13] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n\npublic:\n string intToRoman(int num)\n {\n string rom = "";\n\t\t\n for (int i = 0; num > 0; i++)\n\t\t // each digit is repeated as many times as needed to \n\t\t\t// completely cover the decimal representation \n while (num >= intgr[i]) rom += roman[i], num -= intgr[i];\n return rom;\n }\n};\n```\n | 1,184 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 336 | 6 | Please Upvote if it helped you !!!\nHappy Coding :)\n```\nstring intToRoman(int num) \n {\n string answer="";\n string ones[]={"","I","II","III","IV","V","VI","VII","VIII","IX"};\n string tens[]={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n string hundreds[] ={"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};\n string thousands[]={"","M","MM","MMM"};\n answer=thousands[num/1000]+hundreds[(num%1000)/100]+tens[(num%100)/10]+ones[num%10];\n return answer;\n }\n```\t | 1,188 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 4,802 | 18 | ```\nclass Solution:\n def intToRoman(self, num: int) -> str:\n i=1\n dic={1:\'I\',5:\'V\',10:\'X\',50:\'L\',100:\'C\',500:\'D\',1000:\'M\'}\n s=""\n while num!=0:\n y=num%pow(10,i)//pow(10,i-1)\n if y==5:\n s=dic[y*pow(10,i-1)]+s\n elif y==1:\n s=dic[y*pow(10,i-1)]+s\n elif y==4:\n s=dic[1*pow(10,i-1)]+dic[5*pow(10,i-1)]+s\n elif y==9:\n s=dic[1*pow(10,i-1)]+dic[1*pow(10,i)]+s\n elif y<4:\n s=dic[pow(10,i-1)]*y+s\n elif y>5 and y<9:\n y-=5\n s=dic[5*pow(10,i-1)]+dic[pow(10,i-1)]*y+s\n num=num//pow(10,i)\n num*=pow(10,i)\n i+=1\n return s\n``` | 1,193 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 1,978 | 20 | String[] Thousands={"","M","MM","MMM"};\n String[] Hundreds={"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};\n String[] Tens={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};\n String[] Units={"","I","II","III","IV","V","VI","VII","VIII","IX"};\n return Thousands[num/1000]+Hundreds[(num%1000)/100]+Tens[(num%100)/10]+Units[(num%10)]; | 1,194 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 2,976 | 44 | ```\nclass Solution {\npublic:\n string intToRoman(int num) {\n int intCode[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};\n string code[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};\n \n string s;\n for(int i=0; i<13; ++i){\n while(num>=intCode[i]){\n s.append(code[i]);\n num-=intCode[i];\n }\n }\n return s;\n }\n};\n```\nPlease **UPVOTE** | 1,197 |
Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. | Hash Table,Math,String | Medium | null | 469 | 7 | ```\nclass Solution {\npublic:\n string intToRoman(int num) {\n string ans;\n int val[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n string sym[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};\n \n int i=0;\n while(num){\n \n while(val[i]<=num){\n num-=val[i];\n ans+=sym[i];\n }\n \n i++;\n }\n \n return ans;\n }\n};\n```\n\n**Please Upvote and thank you**\n\n**Feel Free to ask questions** | 1,199 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 199,202 | 1,369 | **Certainly! Let\'s break down the code and provide a clear intuition and explanation, using the examples "IX" and "XI" to demonstrate its functionality.**\n\n# Intuition:\nThe key intuition lies in the fact that in Roman numerals, when a smaller value appears before a larger value, it represents subtraction, while when a smaller value appears after or equal to a larger value, it represents addition.\n\n# Explanation:\n\n1. The unordered map `m` is created and initialized with mappings between Roman numeral characters and their corresponding integer values. For example, \'I\' is mapped to 1, \'V\' to 5, \'X\' to 10, and so on.\n2. The variable `ans` is initialized to 0. This variable will accumulate the final integer value of the Roman numeral string.\n3. The for loop iterates over each character in the input string `s`.\n **For the example "IX":**\n \n - When `i` is 0, the current character `s[i]` is \'I\'. Since there is a next character (\'X\'), and the value of \'I\' (1) is less than the value of \'X\' (10), the condition `m[s[i]] < m[s[i+1]]` is true. In this case, we subtract the value of the current character from `ans`.\n \n `ans -= m[s[i]];`\n `ans -= m[\'I\'];`\n `ans -= 1;`\n `ans` becomes -1.\n \n - When `i` is 1, the current character `s[i]` is \'X\'. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don\'t need to evaluate the condition. In this case, we add the value of the current character to `ans`.\n \n `ans += m[s[i]];`\n `ans += m[\'X\'];`\n `ans += 10;`\n `ans` becomes 9.\n \n **For the example "XI":**\n \n - When `i` is 0, the current character `s[i]` is \'X\'. Since there is a next character (\'I\'), and the value of \'X\' (10) is greater than the value of \'I\' (1), the condition `m[s[i]] < m[s[i+1]]` is false. In this case, we add the value of the current character to `ans`.\n \n `ans += m[s[i]];`\n `ans += m[\'X\'];`\n `ans += 10;`\n `ans` becomes 10.\n \n - When `i` is 1, the current character `s[i]` is \'I\'. This is the last character in the string, so there is no next character to compare. Since there is no next character, we don\'t need to evaluate the condition. In this case, we add the value of the current character to `ans`.\n \n `ans += m[s[i]];`\n `ans += m[\'I\'];`\n `ans += 1;`\n `ans` becomes 11.\n\n4. After the for loop, the accumulated value in `ans` represents the integer conversion of the Roman numeral string, and it is returned as the result.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> m;\n \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 \n int ans = 0;\n \n for(int i = 0; i < s.length(); i++){\n if(m[s[i]] < m[s[i+1]]){\n ans -= m[s[i]];\n }\n else{\n ans += m[s[i]];\n }\n }\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int romanToInt(String s) {\n Map<Character, Integer> m = new HashMap<>();\n \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 \n int ans = 0;\n \n for (int i = 0; i < s.length(); i++) {\n if (i < s.length() - 1 && m.get(s.charAt(i)) < m.get(s.charAt(i + 1))) {\n ans -= m.get(s.charAt(i));\n } else {\n ans += m.get(s.charAt(i));\n }\n }\n \n return ans;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n m = {\n \'I\': 1,\n \'V\': 5,\n \'X\': 10,\n \'L\': 50,\n \'C\': 100,\n \'D\': 500,\n \'M\': 1000\n }\n \n ans = 0\n \n for i in range(len(s)):\n if i < len(s) - 1 and m[s[i]] < m[s[i+1]]:\n ans -= m[s[i]]\n else:\n ans += m[s[i]]\n \n return ans\n```\n![CUTE_CAT.png]()\n\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\n1. [Two Sum]()\n2. [Roman to Integer]()\n3. [Palindrome Number]()\n4. [Maximum Subarray]()\n5. [Remove Element]()\n6. [Contains Duplicate]()\n7. [Add Two Numbers]()\n8. [Majority Element]()\n9. [Remove Duplicates from Sorted Array]()\n10. **Practice them in a row for better understanding and please Upvote for more questions.**\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\n\n | 1,200 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 200,159 | 1,001 | ```\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\nplease upvote if you liked the solution.\n | 1,201 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 64,700 | 323 | \n# Hash Table in python\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}\n number=0\n for i in range(len(s)-1):\n if roman[s[i]] < roman[s[(i+1)]]:\n number-=roman[s[i]]\n else:\n number+=roman[s[i]]\n return number+roman[s[-1]]\n\n\n```\n# please upvote me it would encourage me alot\n | 1,202 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 99,306 | 404 | \n# Approach\nIf there are Numbers such as XL, IV, etc. \nSimply subtract the smaller number and add the larger number in next step. \nFor example, if there is XL, ans =-10 in first step, ans=-10+50=40 in next step.\n\nOtherwise, just add the numbers. \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\n\n# Code\n```\nclass Solution {\npublic:\n int romanToInt(string s) {\n int ans=0;\n unordered_map <char,int> mp{\n {\'I\',1},{\'V\',5},{\'X\',10},{\'L\',50},{\'C\',100},{\'D\',500},{\'M\',1000}};\n\n for(int i=0;i<s.size();i++){\n if(mp[s[i]]<mp[s[i+1]]){\n //for cases such as IV,CM, XL, etc...\n ans=ans-mp[s[i]];\n }\n else{\n ans=ans+mp[s[i]];\n }\n }\n return ans;\n }\n};\n```\n**Please upvote if it helped. Happy Coding!** | 1,203 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 165,006 | 1,920 | The Romans would most likely be angered by how it butchers their numeric system. Sorry guys.\n\n```Python\nclass Solution:\n def romanToInt(self, s: str) -> int:\n translations = {\n "I": 1,\n "V": 5,\n "X": 10,\n "L": 50,\n "C": 100,\n "D": 500,\n "M": 1000\n }\n number = 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 char in s:\n number += translations[char]\n return number\n``` | 1,204 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 115,492 | 402 | Code:\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman_to_integer = {\n \'I\': 1,\n \'V\': 5,\n \'X\': 10,\n \'L\': 50,\n \'C\': 100,\n \'D\': 500,\n \'M\': 1000,\n }\n s = s.replace("IV", "IIII").replace("IX", "VIIII").replace("XL", "XXXX").replace("XC", "LXXXX").replace("CD", "CCCC").replace("CM", "DCCCC")\n return sum(map(lambda x: roman_to_integer[x], s))\n```\n**Time Complexity**: `O(n)`\n**Space Complexity**: `O(1)`\n<br/>\n | 1,210 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 58,618 | 360 | **Intuitive**\nRoman numerals are usually written largest to smallest from left to right, for example: XII (7), XXVII (27), III (3)...\nIf a small value is placed before a bigger value then it\'s a combine number, for exampe: IV (4), IX (9), XIV (14)...\nIV = -1 + 5\nVI = 5 + 1\nXL = -10 + 50\nLX = 50 + 10\nSo, if a smaller number appears before a larger number, it indicates that the number is smaller by a quantity used as a suffix to it, which made going backwards seem easy.\n\n\t\n\t\n\t\n\tclass Solution {\n\tpublic:\n int romanToInt(string s) {\n unordered_map<char,int> mp{\n {\'I\',1},\n {\'V\',5},\n {\'X\',10},\n {\'L\',50},\n {\'C\',100},\n {\'D\',500},\n {\'M\',1000},\n };\n int ans =0;\n for(int i=0;i<s.size();i++){\n if(mp[s[i]]<mp[s[i+1]])\n ans-=mp[s[i]];\n else\n ans+=mp[s[i]];\n }\n return ans;\n \n }\n\t};\n\t\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). \nHAPPY CODING:)**\n\n*Any suggestions and improvements are always welcome*\n\n\t | 1,211 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 42,020 | 269 | To solve this problem, we need to create a hash table, the characters in which will correspond to a certain number. Passing along the line, we will check the current and the next character at once, if the current one is greater than the next one, then everything is fine, we add it to the result (it is initially equal to 0), otherwise, we subtract the current value from the next value (for example, the current 10, and the next 100 , we do 100 - 10, and we get 90), we also add to the result and additionally increase the index **by 1**. As a result, at the end of the loop, we will get the result we need.\n\nI hope the picture below will help you understand in more detail!)\n\n![image]()\n\n```\nvar romanToInt = function(s) {\n const sym = {\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\n for (let i = 0; i < s.length; i++) {\n const cur = sym[s[i]];\n const next = sym[s[i + 1]];\n\n if (cur < next) {\n result += next - cur;\n i++;\n } else {\n result += cur;\n }\n }\n\n return result;\n};\n```\n\nI hope I was able to explain clearly.\n**Happy coding!** \uD83D\uDE43\n | 1,212 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 1,167 | 12 | \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``` | 1,217 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 2,952 | 6 | # Intuition\nBy far the hardest part of this problem was to understand how Roman numerals work lmao. After some studying I had already had a concept in mind, using a map to compare values from left to right.\n\n# Approach\n1. Create an unordered map called **roman_values** to store the mapping of Roman numerals to their corresponding integer values. Each Roman numeral character (\'I\', \'V\', \'X\', etc.) is mapped to its respective integer value (1, 5, 10, etc.).\n2. Initialize the **result** variable to 0, which will hold the final integer value.\n3. Iterate over the input string **s** from the first character to the second-to-last character. For each character at index **i**, compare its value with the value of the next character at index **i + 1**.\n4. If the value of the Roman numeral at index **i** is less than the value of the Roman numeral at index **i + 1**, it indicates that a subtraction case is encountered (e.g., "IV" for 4 or "IX" for 9). In this case, subtract the value of the Roman numeral at index **i** from the **result**.\n5. Otherwise, if the value of the Roman numeral at index **i** is greater than or equal to the value of the Roman numeral at index **i + 1**, it indicates a normal addition case. In this case, add the value of the Roman numeral at index **i** to the **result**.\n6. After the loop, add the value of the last Roman numeral in the string **s** to the **result**.\n7. Finally, return the **result** as the converted integer value.\n\n# Complexity\n- Time complexity:\n$$O(n)$$, where n is the length of the input string **s**\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```c++\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> roman_values = {\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.length() - 1; i++) {\n if (roman_values[s[i]] < roman_values[s[i + 1]]) {\n result -= roman_values[s[i]];\n } else {\n result += roman_values[s[i]];\n }\n }\n\n result += roman_values[s.back()];\n\n return result;\n }\n};\n``` | 1,218 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 5,313 | 25 | # \u2705Do upvote if you like the solution and explanation please \uD83D\uDE80\n\n# \u2705Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this code is to iterate through the Roman numeral string from right to left, converting each symbol to its corresponding integer value. If the current symbol has a smaller value than the symbol to its right, we subtract its value from the result; otherwise, we add its value to the result. By processing the string from right to left, we can handle cases where subtraction is required (e.g., IV for 4) effectively.\n\n---\n\n# \u2705Approach for code \n<!-- Describe your approach to solving the problem. -->\n1. Create an unordered map (romanValues) to store the integer values corresponding to each Roman numeral symbol (\'I\', \'V\', \'X\', \'L\', \'C\', \'D\', \'M\').\n\n2. Initialize a variable result to 0 to store the accumulated integer value.\n\n3. Iterate through the input string s from right to left (starting from the last character).\n\n4. For each character at index i, get its integer value (currValue) from the romanValues map.\n\n5. Check if the current symbol has a smaller value than the symbol to its right (i.e., currValue < romanValues[s[i + 1]]) using the condition i < s.length() - 1. If true, subtract currValue from the result; otherwise, add it to the result.\n\n6. Update the result accordingly for each symbol as you iterate through the string.\n\n7. Finally, return the accumulated result as the integer equivalent of the Roman numeral.\n\n---\n\n# \u2705Complexity\n## 1. Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is O(n), where \'n\' is the length of the input string s. This is because we iterate through the entire string once from right to left.\n## 2. Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) because the size of the romanValues map is fixed and does not depend on the input size. We use a constant amount of additional space to store the result and loop variables, so the space complexity is constant.\n\n---\n\n# \uD83D\uDCA1"If you have made it this far, I would like to kindly request that you upvote this solution to ensure its reach extends to others as well."\u2763\uFE0F\uD83D\uDCA1\n\n---\n\n# \u2705Code\n```C++ []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> romanValues = {\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\n for (int i = s.length() - 1; i >= 0; i--) {\n int currValue = romanValues[s[i]];\n\n if (i < s.length() - 1 && currValue < romanValues[s[i + 1]]) {\n result -= currValue;\n } else {\n result += currValue;\n }\n }\n\n return result;\n }\n};\n\n```\n```Python []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n romanValues = {\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\n for i in range(len(s) - 1, -1, -1):\n currValue = romanValues[s[i]]\n\n if i < len(s) - 1 and currValue < romanValues[s[i + 1]]:\n result -= currValue\n else:\n result += currValue\n\n return result\n\n```\n```Java []\nimport java.util.HashMap;\nimport java.util.Map;\n\nclass Solution {\n public int romanToInt(String s) {\n Map<Character, Integer> romanValues = new HashMap<>();\n romanValues.put(\'I\', 1);\n romanValues.put(\'V\', 5);\n romanValues.put(\'X\', 10);\n romanValues.put(\'L\', 50);\n romanValues.put(\'C\', 100);\n romanValues.put(\'D\', 500);\n romanValues.put(\'M\', 1000);\n\n int result = 0;\n\n for (int i = s.length() - 1; i >= 0; i--) {\n int currValue = romanValues.get(s.charAt(i));\n\n if (i < s.length() - 1 && currValue < romanValues.get(s.charAt(i + 1))) {\n result -= currValue;\n } else {\n result += currValue;\n }\n }\n\n return result;\n }\n}\n\n```\n```Javascript []\nvar romanToInt = function(s) {\n const romanValues = {\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\n for (let i = s.length - 1; i >= 0; i--) {\n const currValue = romanValues[s[i]];\n\n if (i < s.length - 1 && currValue < romanValues[s[i + 1]]) {\n result -= currValue;\n } else {\n result += currValue;\n }\n }\n\n return result;\n};\n\n```\n | 1,219 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 15,697 | 25 | ### C#,Java,Python3,JavaScript different solution with explanation\n**\u2B50[]()\u2B50**\n\n**\uD83E\uDDE1See next question solution - [Zyrastory-Longest Common Prefix]()**\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!** | 1,227 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 4,555 | 11 | # Converter for Roman numbers\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTranslating numbers from the end\nRuntime Beats ~88.00% (93% - 79%).\nMamory Beats ~ 99%\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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int romanConverter(char c);\n int romanToInt(string s);\n};\n\nint Solution::romanConverter(char c) {\n switch(c) {\n case \'I\': return 1;\n case \'V\': return 5;\n case \'X\': return 10;\n case \'L\': return 50;\n case \'C\': return 100;\n case \'D\': return 500;\n case \'M\': return 1000;\n default : return 0;\n }\n}\n\nint Solution::romanToInt(string s) {\n int result = 0;\n short num_last = 0;\n short num_this = 0;\n for (int i = s.size() -1; i >= 0; i--) {\n num_this = romanConverter(s[i]);\n num_this < num_last? result -= num_this: result += num_this;\n num_last = num_this;\n }\n\n return result;\n}\n\n``` | 1,230 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 2,368 | 8 | # 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 int currVal = 0;\n int prevVal = 0;\n int res = 0;\n for(int i = s.length() - 1; i >= 0; i--) {\n switch(s.charAt(i)) {\n case \'I\' :\n currVal = 1;\n break;\n case \'V\' :\n currVal = 5;\n break;\n case \'X\' :\n currVal = 10;\n break;\n case \'L\' :\n currVal = 50;\n break;\n case \'C\' :\n currVal = 100;\n break;\n case \'D\' :\n currVal = 500;\n break;\n case \'M\' :\n currVal = 1000;\n break;\n }\n if(currVal < prevVal) {\n res -= currVal;\n } else {\n res += currVal;\n }\n prevVal = currVal;\n }\n return res;\n }\n}\n``` | 1,233 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 2,091 | 5 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n roman = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}\n\n res = 0\n\n for i in range(len(s)):\n if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]:\n res -= roman[s[i]]\n else:\n res += roman[s[i]]\n return res\n``` | 1,234 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 13,015 | 84 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using String + Hash Table + Math.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the approach by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity : O(1), The maximum length of the string(s) can be 15 (as per the Constgraint), therefore, the worst case time complexity can be O(15) or O(1).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity : O(1), We are using unordered_map(map) to store the Roman symbols and their corresponding integer values but there are only 7 symbols hence the worst case space complexity can be O(7) which is equivalent to O(1).\n\n# Code\n```\n/*\n\n Time Complexity : O(1), The maximum length of the string(s) can be 15 (as per the Constgraint), therefore, the\n worst case time complexity can be O(15) or O(1).\n\n Space Complexity : O(1), We are using unordered_map(map) to store the Roman symbols and their corresponding\n integer values but there are only 7 symbols hence the worst case space complexity can be O(7) which is\n equivalent to O(1).\n\n Solved using String + Hash Table + Math.\n\n*/\n\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> map;\n\n map[\'I\'] = 1;\n map[\'V\'] = 5;\n map[\'X\'] = 10;\n map[\'L\'] = 50;\n map[\'C\'] = 100;\n map[\'D\'] = 500;\n map[\'M\'] = 1000;\n \n int ans = 0;\n \n for(int i=0; i<s.length(); i++){\n if(map[s[i]] < map[s[i+1]]){\n ans -= map[s[i]];\n }\n else{\n ans += map[s[i]];\n }\n }\n return ans;\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]() | 1,236 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 1,715 | 11 | # 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 char [] myarray = s.toCharArray();\n int sum = 0;\n\n String[][] arr = {\n {"I", "1"},\n {"V", "5"},\n {"X", "10"},\n {"L", "50"},\n {"C", "100"},\n {"D", "500"},\n {"M", "1000"}\n };\n\n String[][] condition = {\n {"IV", "4"},\n {"IX", "9"},\n {"XL", "40"},\n {"XC", "90"},\n {"CD", "400"},\n {"CM", "900"}\n };\n\n for (int i = 0; i < myarray.length; i++) {\n\n String str = "";\n if ((i+1) < (myarray.length)){\n str +=myarray[i];\n str +=myarray[i+1];\n }\n\n boolean cond = false;\n\n test1:for (int j = 0; j < condition.length ; j++) {\n if (str == "") break test1;\n if (condition[j][0].equals(str)) {\n int a = Integer.parseInt(condition[j][1]);\n sum += a;\n i = i + 1;\n\n cond=true;\n break test1;\n\n }\n }\n\n\n test2:for (int l = 0; l < arr.length; l++) {\n if (cond) break test2;\n \n if (arr[l][0].equals(String.valueOf(myarray[i]))) {\n int a = Integer.parseInt(arr[l][1]);\n sum += a;\n\n break test2;\n }\n }\n\n }\n\n\n return sum;\n }\n}\n```\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository]()\n\n\n![abcd1.jpeg]()\n\n | 1,237 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 10,853 | 23 | # 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!*** | 1,238 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 1,047 | 8 | TRICK : We can see that in this map mp={{"I",1},{"IV",4},{"V",5},{"IX",9},{"X",10},{"XL",40}, {"L",50},{"XC",90},{"C",100},{"CD",400},{"D",500},{"CM",900},{"M",1000}}; either there are strings of length 2 or 1 this means that we can check if the substring from the current index of length 2 is available in the map then simply we will add its val to the ans else we will have to add the val for the substr of length 1 present in the map. The last one thing : we have added this condition that the index if is n-1 means it is standing at the last 1 length string this means that only case 2 i.e. else case can be executed for it. \n\n```\nclass Solution {\nint func(map<string , int >& mp, string s)\n{\n int ans=0;\n int n=s.length();\n for(int i=0; i<n; )\n {\n if(mp.find(s.substr(i,2))!=mp.end() && i!=n-1)\n {\n ans+=mp[s.substr(i,2)];\n i+=2;\n }\n else\n {\n ans+=mp[s.substr(i,1)];\n i+=1;\n }\n }\n return ans;\n}\npublic:\n int romanToInt(string s) {\n map<string, int> mp;\n mp={{"I",1},{"IV",4},{"V",5},{"IX",9},{"X",10},{"XL",40},\n {"L",50},{"XC",90},{"C",100},{"CD",400},{"D",500},{"CM",900},{"M",1000}};\n return func(mp,s);\n }\n};\n// IF you LIKE it then pleasee.. __/\\__ do UPVOTE ...Thank you :) :) \n``` | 1,239 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 7,751 | 14 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\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\n int res = map.get(s.charAt(s.length()-1));\n for(int i=s.length()-2;i>=0;i--){\n if(map.get(s.charAt(i)) < map.get(s.charAt(i+1))){\n res -= map.get(s.charAt(i));\n }else{\n res += map.get(s.charAt(i));\n }\n }\n return res;\n }\n}\n``` | 1,240 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 25,992 | 51 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe essentially start scanning adding all of the corresponding values for each character regardless of order. (e.g. "IX" is 11 not 9) Then, we check the order of the elements, and if we find that the order is reversed (i.e. "IX"), we make the necessary adjustment (e.g. for "IX," we subtract 2)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Introduce the total sum variable, and the dictionary containing the corresponding number values for each Roman letter\n2) We add all of the corresponding number values together regardless of order of elements\n3) We check if certain ordered pairs are in the Roman number and make the adjustments if necessary\n\n\n# Code\n```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n total = 0\n theDict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}\n\n for i in s:\n total += theDict[i]\n\n if "IV" in s:\n total -= 2\n if "IX" in s:\n total -= 2\n if "XL" in s:\n total -= 20\n if "XC" in s:\n total -= 20\n if "CD" in s:\n total -= 200\n if "CM" in s:\n total -= 200\n\n \n return total\n``` | 1,251 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 106,895 | 709 | \n class Solution:\n # @param {string} s\n # @return {integer}\n def romanToInt(self, s):\n roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}\n z = 0\n for i in range(0, len(s) - 1):\n if roman[s[i]] < roman[s[i+1]]:\n z -= roman[s[i]]\n else:\n z += roman[s[i]]\n return z + roman[s[-1]]\n\n\n*Note: The trick is that the last letter is always added. Except the last one, if one letter is less than its latter one, this letter is subtracted. | 1,253 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 13,022 | 49 | # Intuition of this Problem:\nThe given code is implementing the conversion of a Roman numeral string into an integer. It uses an unordered map to store the mapping between Roman numerals and their corresponding integer values. The algorithm takes advantage of the fact that in a valid Roman numeral string, the larger numeral always appears before the smaller numeral if the smaller numeral is subtracted from the larger one. Thus, it starts with the last character in the string and adds the corresponding value to the integer variable. Then, it iterates through the remaining characters from right to left and checks whether the current numeral is greater than or equal to the previous numeral. If it is greater, then it adds the corresponding value to the integer variable, otherwise, it subtracts the corresponding value from the integer variable.\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Create an unordered map and store the mapping between Roman numerals and their corresponding integer values.\n2. Reverse the input Roman numeral string.\n3. Initialize an integer variable to 0.\n4. Add the integer value corresponding to the last character in the string to the integer variable.\n5. Iterate through the remaining characters from right to left.\n6. Check whether the integer value corresponding to the current character is greater than or equal to the integer value corresponding to the previous character.\n7. If it is greater, add the integer value to the integer variable.\n8. If it is smaller, subtract the integer value from the integer variable.\n9. Return the final integer variable.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int romanToInt(string s) {\n unordered_map<char, int> storeKeyValue;\n storeKeyValue[\'I\'] = 1;\n storeKeyValue[\'V\'] = 5;\n storeKeyValue[\'X\'] = 10;\n storeKeyValue[\'L\'] = 50;\n storeKeyValue[\'C\'] = 100;\n storeKeyValue[\'D\'] = 500;\n storeKeyValue[\'M\'] = 1000;\n reverse(s.begin(), s.end());\n int integer = 0;\n integer += storeKeyValue[s[0]];\n for (int i = 1; i < s.length(); i++) {\n if(storeKeyValue[s[i]] >= storeKeyValue[s[i-1]])\n integer += storeKeyValue[s[i]];\n else\n integer -= storeKeyValue[s[i]];\n }\n return integer;\n }\n};\n```\n```Java []\nclass Solution {\n public int romanToInt(String s) {\n HashMap<Character, Integer> storeKeyValue = new HashMap<>();\n storeKeyValue.put(\'I\', 1);\n storeKeyValue.put(\'V\', 5);\n storeKeyValue.put(\'X\', 10);\n storeKeyValue.put(\'L\', 50);\n storeKeyValue.put(\'C\', 100);\n storeKeyValue.put(\'D\', 500);\n storeKeyValue.put(\'M\', 1000);\n int integer = 0;\n integer += storeKeyValue.get(s.charAt(0));\n for (int i = 1; i < s.length(); i++) {\n if(storeKeyValue.get(s.charAt(i)) >= storeKeyValue.get(s.charAt(i-1)))\n integer += storeKeyValue.get(s.charAt(i));\n else\n integer -= storeKeyValue.get(s.charAt(i));\n }\n return integer;\n }\n}\n\n```\n```Python []\nclass Solution:\n def romanToInt(self, s: str) -> int:\n storeKeyValue = {}\n storeKeyValue[\'I\'] = 1\n storeKeyValue[\'V\'] = 5\n storeKeyValue[\'X\'] = 10\n storeKeyValue[\'L\'] = 50\n storeKeyValue[\'C\'] = 100\n storeKeyValue[\'D\'] = 500\n storeKeyValue[\'M\'] = 1000\n s = s[::-1]\n integer = 0\n integer += storeKeyValue[s[0]]\n for i in range(1, len(s)):\n if storeKeyValue[s[i]] >= storeKeyValue[s[i-1]]:\n integer += storeKeyValue[s[i]]\n else:\n integer -= storeKeyValue[s[i]]\n return integer\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(s.length()) = O(15) = O(1)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(7) = O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 1,256 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 2,166 | 6 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->from the question we can understand that we need to keep adding the integer equivalent of each no. Now the problem is how to manage those cases when we need to subtract the no. If we travel from right to left it becomes easier to track those cases, i.e by maintaining a previous variable. if the current digit is smaller than the previous then we need to subtract it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Now we can solve it using if else of switch, but its easier to use switch as there are countable multiple possible values of a single variable.\nso maintain a result variable res to store the final value, maintain a prev variable to store previous value keep comparing with prev, and add or subtract accordingly then update prev variable.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int romanToInt(string s) {\n char c;\n int res=0;\n int prev=0;\n int n=s.length();\n for(int i=n-1;i>=0;i--){\n c=s[i];\n switch(c){\n case \'I\':{\n if(prev<=1)\n res+=1;\n else\n res-=1;\n prev=1;\n break;\n }\n case \'V\':{\n if(prev<=5)\n res+=5;\n else\n res-=5;\n prev=5;\n break;\n }\n case \'X\':{\n if(prev<=10)\n res+=10;\n else\n res-=10;\n prev=10;\n break;\n }\n case \'L\':{\n if(prev<=50)\n res+=50;\n else\n res-=50;\n prev=50;\n break;\n }\n case \'C\':{\n if(prev<=100)\n res+=100;\n else\n res-=100;\n prev=100;\n break;\n }\n case \'D\':{\n if(prev<=500)\n res+=500;\n else\n res-=500;\n prev=500;\n break;\n }\n case \'M\':{\n if(prev<=1000)\n res+=1000;\n else\n res-=1000;\n prev=1000;\n break;\n }\n }\n }\n return res;\n }\n};\n``` | 1,258 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 1,100 | 6 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int romanToInt(string s) {\n int n=s.size(),ans=0;\n vector<int>v;\n for(int i=0;i<n;i++){\n if(s[i]==\'I\'){v.emplace_back(1);}\n if(s[i]==\'V\'){v.emplace_back(5);}\n if(s[i]==\'X\'){v.emplace_back(10);}\n if(s[i]==\'L\'){v.emplace_back(50);}\n if(s[i]==\'C\'){v.emplace_back(100);}\n if(s[i]==\'D\'){v.emplace_back(500);}\n if(s[i]==\'M\'){v.emplace_back(1000);}\n }\n v.emplace_back(1);\n for(int i=0;i<n;){\n if(v[i]<v[i+1]){ans+=(v[i+1]-v[i]);i+=2;}\n else{ans+=v[i];i++;}\n }\n return ans; \n }\n};\nDo UPVOTE if you like\n``` | 1,259 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 133,467 | 667 | Problem is simpler to solve by working the string from back to front and using a map. Runtime speed is 88 ms.\n\n\n\n int romanToInt(string s) \n {\n unordered_map<char, int> T = { { 'I' , 1 },\n { 'V' , 5 },\n { 'X' , 10 },\n { 'L' , 50 },\n { 'C' , 100 },\n { 'D' , 500 },\n { 'M' , 1000 } };\n \n int sum = T[s.back()];\n for (int i = s.length() - 2; i >= 0; --i) \n {\n if (T[s[i]] < T[s[i + 1]])\n {\n sum -= T[s[i]];\n }\n else\n {\n sum += T[s[i]];\n }\n }\n \n return sum;\n } | 1,260 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 693 | 6 | class 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 s = s.replace("IV", "IIII").replace("IX", "VIIII").replace("XL", "XXXX").replace("XC", "LXXXX").replace("CD", "CCCC").replace("CM", "DCCCC")\n\n sum = 0\n for i in s:\n sum += d[i]\n return sum | 1,261 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 35,831 | 321 | ```\nsymbols = {\n "I": 1,\n "V": 5,\n "X": 10,\n "L": 50,\n "C": 100,\n "D": 500,\n "M": 1000\n};\n\nvar romanToInt = function(s) {\n value = 0;\n for(let i = 0; i < s.length; i+=1){\n symbols[s[i]] < symbols[s[i+1]] ? value -= symbols[s[i]]: value += symbols[s[i]]\n }\n return value\n};\n``` | 1,264 |
Roman to Integer | roman-to-integer | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. | Hash Table,Math,String | Easy | Problem is simpler to solve by working the string from back to front and using a map. | 2,113 | 8 | ```\nclass Solution:\n def romanToInt(self, s: str) -> int:\n a={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}\n sum=0 \n x=0\n while x<len(s):\n if x<len(s)-1 and a[s[x]]<a[s[x+1]]:\n sum += (a[s[x+1]] - a[s[x]])\n x += 2\n else:\n sum += a[s[x]]\n x += 1\n return sum\n``` | 1,265 |