question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-compatibility-score-sum | [C++] DP + Bitmask | 15 lines of code with explanation | 0ms | Beats 100% | c-dp-bitmask-15-lines-of-code-with-expla-gxfl | We assign j-th mentor to i-th student from the set of mentors available. We iterate with a fixed mentors available. For every mentor_set, if we calculate the c | pratyushk82010 | NORMAL | 2021-07-25T22:35:34.717889+00:00 | 2021-07-25T22:35:34.717937+00:00 | 66 | false | We assign j-th mentor to i-th student from the set of mentors available. We iterate with a fixed mentors available. For every mentor_set, if we calculate the compatibility score of assigning j-th mentor to i-th student then what is important for us is the compatibility score of assigning all other mentors (exept j-th) from current mentor-set to all other students (exept i-th). Also, if we have k mentors available then k students only can be used since exactly one mentor must be assigned to each student. Hence, finally our answer is when all (m) mentors are considered in mentor-set.\n\n```\n int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) {\n int m = students.size(), n = students[0].size();\n vector<int> dp((1 << m), 0);\n for (int mentor_set = 0; mentor_set < (1 << m); ++mentor_set) {\n int i = __builtin_popcount(mentor_set) - 1;\n for (int j = 0; j < m; ++j) {\n if (mentor_set & (1 << j)) {\n int curr = 0;\n for (int k = 0; k < n; ++k)\n if (students[i][k] == mentors[j][k])\n ++curr;\n dp[mentor_set] = max(dp[mentor_set], curr + dp[mentor_set & ~(1 << j)]);\n }\n }\n }\n return dp[(1 << m) - 1];\n }\n \n ``` | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | Easy bitmask and backtracking | easy-bitmask-and-backtracking-by-2pac_sh-i19g | Why backtracking\nThe contraints are only till 8, so we can explore all the paths.\nWhy bitmask\nRecursive call consumes less space, so, it is easy to keep trac | 2pac_shakur | NORMAL | 2021-07-25T10:14:31.202757+00:00 | 2021-07-25T10:14:31.202792+00:00 | 73 | false | **Why backtracking**\nThe contraints are only till 8, so we can explore all the paths.\n**Why bitmask**\nRecursive call consumes less space, so, it is easy to keep track of which mentor is assigned and which isn\'t.\n\n```\n /**\n Find compatablilty scores for each student to each mentor.\n \n Try to explore all the possibilites of assigning a student to a mentor.\n Start with "mask = 0", means, all bits are 0 in 0, means all mentors are free.\n "mask and (1 shl j) == 0", means, is \'jth\' bit in the mask is \'0\'?, means, \'jth\' mentor is free.\n - assign the mentor and explore other paths\n - new mask will be updated as "mask or (1 shl j)", means, we have to set the \'jth\' bit in mask\n **/\n \n fun maxCompatibilitySum(A: Array<IntArray>, B: Array<IntArray>): Int {\n val n = A.size\n val compat = Array(n) { IntArray(n) }\n var ans = 0\n for ((i, row1) in A.withIndex()) {\n for ((j, row2) in B.withIndex()) {\n var score = 0\n for (k in 0 until row1.size)\n score += if (row1[k] == row2[k]) 1 else 0 // if both are same, score increases\n compat[i][j] = score // ith student with jth mentor\n }\n }\n fun dfs(i: Int, mask: Int, total: Int) {\n if (i == n) { // all students are explored\n ans = maxOf(ans, total)\n return\n }\n for (j in 0 until n) { // explore all mentors for \'ith\' student\n if (mask and (1 shl j) == 0) // is \'jth\' mentor free?\n dfs(i + 1, mask or (1 shl j), total + compat[i][j])\n }\n }\n \n dfs(0, 0, 0)\n return ans\n }\n``` | 1 | 0 | ['Bitmask', 'Kotlin'] | 0 |
maximum-compatibility-score-sum | Java - Bitmask DP - Easy to understand | java-bitmask-dp-easy-to-understand-by-al-5gm3 | \n\nclass Solution {\n Integer[] dp;\n int ALL;\n int[][] students;\n int[][] mentors;\n public int maxCompatibilitySum(int[][] students, int[][] | alan_black | NORMAL | 2021-07-25T08:13:55.668750+00:00 | 2021-07-25T08:13:55.668793+00:00 | 308 | false | \n```\nclass Solution {\n Integer[] dp;\n int ALL;\n int[][] students;\n int[][] mentors;\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n final int nStudents = students.length;\n final int nAnswers = students[0].length;\n this.students = students;\n this.mentors = mentors;\n\n ALL = (1<<nStudents)-1;\n dp = new Integer[ALL + 1];\n return dfs(0,0, nAnswers);\n }\n\n int dfs(int iStudent, int assignedMentors, int nAnswers){\n if (assignedMentors == ALL) return 0;\n if(iStudent >= students.length) return 0;\n if(dp[assignedMentors] != null) return dp[assignedMentors];\n int max = 0;\n for (int iMentor = 0; iMentor < mentors.length; iMentor++) {\n if ((assignedMentors & (1 << iMentor)) == 0) {\n final int curr = getScore(students[iStudent], mentors[iMentor], nAnswers);\n final int right = dfs(iStudent + 1, assignedMentors | (1 << iMentor), nAnswers);\n max = Math.max(max, curr + right);\n }\n }\n return dp[assignedMentors] = max;\n }\n\n int getBits(int[] A){\n int res = 0;\n for (int a : A) {\n res |= a;\n res <<= 1;\n }\n res = res >> 1;\n return res;\n }\n\n int getScore(int[] a, int[] b, int size){\n return Integer.bitCount(getBits(a) ^ ~getBits(b)) -32 + size;\n }\n}\n``` | 1 | 0 | ['Dynamic Programming', 'Bitmask', 'Java'] | 0 |
maximum-compatibility-score-sum | JAVA | java-by-kapil08-bu6t | \nclass Solution {\n int max=0;\n Set<Integer>set=new HashSet<>();\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n \n | kapil08 | NORMAL | 2021-07-25T07:19:28.425802+00:00 | 2021-07-25T07:19:28.425845+00:00 | 60 | false | ```\nclass Solution {\n int max=0;\n Set<Integer>set=new HashSet<>();\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n \n solve(students,mentors,"");\n return max;\n }\n \n void solve(int[][]students,int[][]mentor,String s){\n\t\n\t//find the ans from each permutation and return the ,max answer\n if(students.length==set.size()){\n int sum=0;\n for(int i=0;i<students.length;i++){\n \n int p=0;\n int[]z=students[i];\n int[]z1=mentor[s.charAt(i)-\'0\'];\n \n for(int j=0;j<z.length;j++){\n if(z[j]==z1[j]){\n p++;\n }\n }\n sum=sum+p;\n }\n max=Math.max(max,sum);\n return;\n }\n\t\t// Calculate all permutations\n for(int i=0;i<students.length;i++){\n if(set.contains(i)){\n continue;\n }\n set.add(i);\n solve(students,mentor,s+i);\n set.remove(i);\n }\n \n }\n}\n``` | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | [C++] Simple Backtracking Solution | c-simple-backtracking-solution-by-varun0-m183 | ```\nint res = 0;\n \nvoid countScore(vector >& mentors, vector >& students) {\n\tint count = 0;\n\tfor(int i = 0; i<students.size(); i++) {\n\t\tfor(int j = | varun09 | NORMAL | 2021-07-25T07:03:40.062658+00:00 | 2021-07-25T07:03:40.062700+00:00 | 37 | false | ```\nint res = 0;\n \nvoid countScore(vector<vector<int> >& mentors, vector<vector<int> >& students) {\n\tint count = 0;\n\tfor(int i = 0; i<students.size(); i++) {\n\t\tfor(int j = 0; j<students[i].size(); j++) {\n\t\t\tif(students[i][j] == mentors[i][j]) count++;\n\t\t}\n\t}\n\tres = max(res, count);\n}\n\nvoid permute(vector<vector<int> >& mentors, vector<vector<int> >& students, int j) {\n\tif(j == mentors.size()-1) {\n\t\tcountScore(mentors, students);\n\t\treturn;\n\t}\n\n\tfor(int i = j; i<mentors.size(); i++) {\n\t\tswap(mentors[j], mentors[i]);\n\t\tpermute(mentors, students, j+1);\n\t\tswap(mentors[j], mentors[i]); //Backtracking\n\t}\n}\nint maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) {\n\tpermute(mentors, students, 0);\n\treturn res;\n}\n\n | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | Simple Backtracking solution C++ | simple-backtracking-solution-c-by-gaurav-dk50 | \nclass Solution {\npublic:\n int calculate(vector<int>v1,vector<int>v2)\n {\n int s=0;\n for(int i=0;i<v1.size();i++)\n {\n | gaurav1903 | NORMAL | 2021-07-25T05:28:17.419166+00:00 | 2021-07-25T05:28:17.419210+00:00 | 30 | false | ```\nclass Solution {\npublic:\n int calculate(vector<int>v1,vector<int>v2)\n {\n int s=0;\n for(int i=0;i<v1.size();i++)\n {\n if(v1[i]==v2[i])\n s+=1;\n }\n return s;\n }\n int maxscore=0;\n \n void allcombo(vector<vector<int>>& students, vector<vector<int>>& mentors,vector<int>&done,int i=0,int sum=0)//i is for students\n {\n if(i==mentors.size())\n {\n maxscore=max(maxscore,sum);\n return ;\n }\n for(int j=0;j<mentors.size();j++)\n {\n if(done[j]==0)\n {\n done[j]=1;\n allcombo(students,mentors,done,i+1,sum+calculate(students[i],mentors[j]));\n done[j]=0;\n }\n }\n }\n int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) {\n vector<int>done(mentors.size(),0);\n allcombo(students,mentors,done);\n return maxscore;\n }\n};\n``` | 1 | 0 | [] | 1 |
maximum-compatibility-score-sum | Python 2 lines brute force with permutations | python-2-lines-brute-force-with-permutat-6fd0 | python\nn = len(students)\nsums = []\nfor s in students:\n\ttemp = []\n\tfor m in mentors:\n\t\ttemp.append(sum([s[i] == m[i] for i in range(len(s))]))\n\tsums. | FACEPLANT | NORMAL | 2021-07-25T04:42:29.791184+00:00 | 2021-07-25T04:42:29.791214+00:00 | 66 | false | ```python\nn = len(students)\nsums = []\nfor s in students:\n\ttemp = []\n\tfor m in mentors:\n\t\ttemp.append(sum([s[i] == m[i] for i in range(len(s))]))\n\tsums.append(temp)\nperm = list(permutations(range(0, n)))\nresult = 0\nfor p in perm:\n\tresult = max(result, sum([sums[i][p[i]] for i in range(n)]))\nreturn result\n```\n\n2 lines version:\n```python\nsums = [[sum([s[i] == m[i] for i in range(len(s))]) for m in mentors] for s in students]\nreturn max(sum([sums[i][x[i]] for i in range(len(students))]) for x in list(permutations(range(0, len(students)))))\n```\n | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | [C++] | [OPTIMIZED Backtracking Solution] | [Easy-To-Understand] | c-optimized-backtracking-solution-easy-t-hhvd | \nclass Solution {\npublic:\n inline int score(vector<int> &a, vector<int> &b, int &size)\n {\n int s=0;\n for(int i=0;i<size;++i)\n | prakhar-pipersania | NORMAL | 2021-07-25T04:39:55.691229+00:00 | 2021-07-25T05:48:50.869055+00:00 | 93 | false | ```\nclass Solution {\npublic:\n inline int score(vector<int> &a, vector<int> &b, int &size)\n {\n int s=0;\n for(int i=0;i<size;++i)\n if(a[i]==b[i])\n s++;\n return s;\n }\n inline void solve(int arr[], vector<bool> &a, int &m, int &n, int &ms, int l, int sum)\n {\n if(l==m)\n ms=max(ms,sum);\n else if(sum+((m-l)*n)>ms)\n {\n for(int i=0;i<m;++i)\n {\n if(a[i])\n {\n a[i]=0;\n solve(arr,a,m,n,ms,l+1,sum+arr[(l*m)+i]);\n a[i]=1;\n }\n }\n }\n }\n inline int maxCompatibilitySum(vector<vector<int>>& stu, vector<vector<int>>& men) \n {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n \n int ms=0,m=stu.size(),n=stu[0].size(),t=m*m;\n vector<bool> a(m,1);\n int *arr=new int[t];\n \n for(int i=0;i<m;++i)\n for(int j=0;j<m;++j)\n arr[(i*m)+j]=score(stu[i],men[j],n);\n \n solve(arr,a,m,n,ms,0,0);\n return ms;\n }\n};\n```\n***Do Hit Upvote if you like the Solution*** | 1 | 0 | ['C'] | 0 |
maximum-compatibility-score-sum | python dfs recursion | python-dfs-recursion-by-ayushman_123-s75x | ```\ndef cscore(a,b):\n ans=0\n for i in range(len(a)):\n if a[i]==b[i]:\n ans+=1\n return ans \ndef function(students,mentors,n,s | Ayushman_123 | NORMAL | 2021-07-25T04:33:43.510353+00:00 | 2021-10-02T01:04:28.317483+00:00 | 180 | false | ```\ndef cscore(a,b):\n ans=0\n for i in range(len(a)):\n if a[i]==b[i]:\n ans+=1\n return ans \ndef function(students,mentors,n,score,ans,visited):\n \n if n==0:\n ans.append(score)\n return\n for i in range(len(students)):\n if not visited[i]:\n visited[i]=True\n function(students,mentors,n-1,score+cscore(students[n-1],mentors[i]),ans,visited)\n visited[i]=False\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n ans=[]\n score=0\n n=len(students)\n visited=[False]*(len(students))\n function(students,mentors,n,score,ans,visited)\n #print(ans)\n return(max(ans)) | 1 | 0 | ['Depth-First Search', 'Python'] | 0 |
maximum-compatibility-score-sum | Java Simple and easy to understand solution, clean code with comments | java-simple-and-easy-to-understand-solut-dkjd | \nclass Solution {\n int maxScoreSum;\n \n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n int s = students.length;\n | satyaDcoder | NORMAL | 2021-07-25T04:17:46.626339+00:00 | 2021-07-25T04:17:46.626368+00:00 | 103 | false | ```\nclass Solution {\n int maxScoreSum;\n \n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n int s = students.length;\n int m = mentors.length;\n \n //store the cores of each pair of students and mentors\n int[][] scores = new int[s][m];\n \n for(int i = 0; i < s; i++){\n for(int j = 0; j < m; j++){\n scores[i][j] = getScore(students[i], mentors[j]);\n }\n }\n \n maxScoreSum = 0; \n \n \n //try every permutation of mentonr and student\n backtracking(scores, new boolean[m], 0, 0);\n \n \n return maxScoreSum;\n }\n \n private void backtracking(int[][] scores, boolean[] used, int index, int sum){\n \n if(index == scores.length){\n maxScoreSum = Math.max(maxScoreSum, sum);\n return;\n }\n \n \n for(int i = 0; i < scores[0].length; i++){\n if(used[i]) continue;\n \n used[i] = true;\n \n backtracking(scores, used, index + 1, sum + scores[index][i]);\n \n used[i] = false;\n \n }\n \n \n }\n \n private int getScore(int[] student, int[] mentor){\n int score = 0;\n \n for(int i = 0; i < mentor.length; i++){\n if(student[i] == mentor[i]) {\n score ++;\n }\n }\n \n return score;\n }\n}\n``` | 1 | 1 | ['Backtracking', 'Java'] | 0 |
maximum-compatibility-score-sum | JAVA DFS + Memorization faster than 100% | java-dfs-memorization-faster-than-100-by-qi5a | \nclass Solution {\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n int[][] scores = new int[students.length][students.length]; | jianjia2 | NORMAL | 2021-07-25T04:17:43.268869+00:00 | 2021-07-25T04:19:33.534306+00:00 | 77 | false | ```\nclass Solution {\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n int[][] scores = new int[students.length][students.length];\n for (int i = 0; i < scores.length; i++) {\n for (int j = 0; j < scores[0].length; j++) {\n scores[i][j] = getCompatibilityScore(students[i], mentors[j]);\n }\n }\n boolean[][] states = new boolean[2][students.length];\n\t\t// Use list of indexes to represent whethe current state has been visited or not\n Map<List<Integer>, Integer> cache = new HashMap<>();\n return getMaxScore(scores, cache, states);\n }\n \n private int getMaxScore(int[][] scores, Map<List<Integer>, Integer> cache, boolean[][] states) {\n List<Integer> indexes = getIndexes(states);\n\t\t// If visited, directly return\n if (cache.containsKey(indexes)) {\n return cache.get(indexes);\n }\n // there is only one element\n if (indexes.size() == 2) {\n cache.put(indexes, scores[indexes.get(0)][indexes.get(1)]);\n return cache.get(indexes);\n }\n // there are a lot element\n int currMax = 0;\n for (int i = 0; i < indexes.size() / 2; i++) {\n int row = indexes.get(0);\n states[0][row] = true;\n for (int j = 0; j < indexes.size() / 2; j++) {\n int col = indexes.get(j + indexes.size() / 2);\n states[1][col] = true;\n currMax = Math.max(currMax, scores[row][col] + getMaxScore(scores, cache, states));\n states[1][col] = false;\n }\n states[0][row] = false;\n }\n cache.put(indexes, currMax);\n return cache.get(indexes);\n }\n \n private List<Integer> getIndexes(boolean[][] states) {\n List<Integer> indexes = new ArrayList<>();\n for (int i = 0; i < states.length; i++) {\n for (int j = 0; j < states[0].length; j++) {\n if (states[i][j] == false) {\n indexes.add(j);\n }\n }\n }\n return indexes;\n }\n \n private int getCompatibilityScore(int[] student, int[] mentor) {\n int sum = 0;\n for (int i = 0; i < student.length; i++) {\n if (student[i] == mentor[i]) {\n sum++;\n }\n }\n return sum;\n }\n}\n``` | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | Java Backtracking DFS | java-backtracking-dfs-by-hw1635-s4ot | \nclass Solution {\n public int max = 0;\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n List<Integer> scores = new ArrayLi | hw1635 | NORMAL | 2021-07-25T04:16:41.640953+00:00 | 2021-07-25T04:16:41.640981+00:00 | 72 | false | ```\nclass Solution {\n public int max = 0;\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n List<Integer> scores = new ArrayList<>(); \n boolean[] visited = new boolean[students.length];\n backtrack(students, mentors, 0, 0, visited);\n return max;\n }\n public void backtrack(int[][] students, int[][] mentors, int ind, int curScore, boolean[] visited) {\n \n if (ind == students.length) {\n max = Math.max(max, curScore);\n return;\n }\n \n int[] student = students[ind];\n for (int i = 0; i < mentors.length; i++) {\n if (visited[i]) {continue;}\n int comp = getComp(student, mentors[i]);\n visited[i] = true;\n \n backtrack(students, mentors, ind + 1, curScore + comp, visited);\n visited[i] = false;\n }\n }\n public int getComp(int[] a, int[] b) {\n int score = 0;\n for (int i = 0; i < a.length; i++) {\n if (a[i] == b[i]) {score++;}\n }\n return score;\n }\n \n \n}\n``` | 1 | 0 | [] | 1 |
maximum-compatibility-score-sum | [Python3] Simple Bitmask DP | python3-simple-bitmask-dp-by-blackspinne-1ata | \nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m = len(students)\n n = len(st | blackspinner | NORMAL | 2021-07-25T04:10:15.896623+00:00 | 2021-07-25T21:22:13.362027+00:00 | 101 | false | ```\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m = len(students)\n n = len(students[0])\n complete = (1 << m) - 1\n scores = [[0] * m for _ in range(m)]\n def calc(st, me):\n score = 0\n for i in range(n):\n if st[i] == me[i]:\n score += 1\n return score\n for i in range(m):\n for j in range(m):\n scores[i][j] = calc(students[i], mentors[j])\n @lru_cache(None)\n def dfs(mask1, mask2):\n if mask1 == complete:\n return 0\n res = 0\n for i in range(m):\n if (mask1 >> i) & 1:\n continue\n for j in range(m):\n if (mask2 >> j) & 1:\n continue\n res = max(res, dfs(mask1 ^ (1 << i), mask2 ^ (1 << j)) + scores[i][j])\n return res\n res = dfs(0, 0)\n dfs.cache_clear()\n return res\n``` | 1 | 0 | [] | 1 |
maximum-compatibility-score-sum | [Python 3] Easy understand Backtracking Solution | python-3-easy-understand-backtracking-so-m1lh | The first thing we need to do is to initialize the student-teacher compatibility score matrix:\nmat[i][j] = n - sum(abs(students[i][x] - mentors[j][x]) for x in | danielxue | NORMAL | 2021-07-25T04:10:03.003601+00:00 | 2021-07-25T04:11:32.842146+00:00 | 88 | false | The first thing we need to do is to initialize the `student-teacher` compatibility score matrix:\n`mat[i][j] = n - sum(abs(students[i][x] - mentors[j][x]) for x in range(n))`\n\nAfter we build the compatibility score matrix, than it becomes the standard backtracking problem.\nCode:\n```python\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m, n = len(students), len(students[0])\n\t\t# mat[i][j] represents compatibility Score between students i and mentor j\n mat = [[0] * m for _ in range(m)]\n \n for i in range(m):\n for j in range(m):\n mat[i][j] = n - sum(abs(students[i][x] - mentors[j][x]) for x in range(n))\n \n self.res = 0\n seen = set()\n \n def backtrack(step, score):\n if step == m:\n self.res = max(self.res, score)\n return\n \n for i in range(m):\n if i not in seen:\n # pair students and mentor\n\t\t\t\t\t# add mentor\'s index to seen set\n seen.add(i)\n # move to next state\n backtrack(step + 1, score + mat[step][i])\n # backtrack\n seen.remove(i)\n \n backtrack(0, 0)\n return self.res\n\n``` | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | C++ concise code | using next_permutation | O(n*(n*m)*n!) | c-concise-code-using-next_permutation-on-wyxx | \nclass Solution {\npublic:\n int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) {\n int n = students.size();\n | asciarp08 | NORMAL | 2021-07-25T04:09:09.255136+00:00 | 2021-07-25T04:14:16.501847+00:00 | 112 | false | ```\nclass Solution {\npublic:\n int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) {\n int n = students.size();\n int m = students[0].size();\n vector<int>pos;\n \n for(int i = 0; i<n;i++){\n pos.push_back(i);\n }\n \n int ans = 0;\n \n do{\n int cur = 0;\n for(int i = 0; i<n;i++){\n for(int j = 0; j<m; j++){\n if(students[i][j]==mentors[pos[i]][j])cur++;\n }\n }\n ans = max(cur,ans);\n }while(next_permutation(pos.begin(), pos.end()));\n return ans;\n }\n};``\n``` | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | JAVA O(n^3) Kuhn-Munkres (Hungarian) | java-on3-kuhn-munkres-hungarian-by-reed_-5qzf | ```\nclass Solution {\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n return sln1(students, mentors);\n }\n \n privat | reed_w | NORMAL | 2021-07-25T04:07:27.075517+00:00 | 2021-07-25T04:07:27.075566+00:00 | 206 | false | ```\nclass Solution {\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n return sln1(students, mentors);\n }\n \n private int sln1(int[][] sts, int[][] mts){\n int m = sts.length;\n int n = sts[0].length;\n int[][] arr = new int[m][m];\n for(int i = 0;i<m;i++){\n for(int j = 0;j< m;j++){\n int score = 0;\n for(int k = 0;k < n;k++){\n score += 1^sts[i][k]^mts[j][k];\n }\n arr[i][j] = score;\n }\n }\n \n return km(arr);\n }\n \n private int km(int[][] w){\n int n = w.length;\n int m = w[0].length;\n int[] lx = new int[n];\n int[] ly = new int[m];\n int[] from = new int[m];\n int[] to = new int[n];\n \n Arrays.fill(from, -1);\n Arrays.fill(to, -1);\n \n for(int i=0;i<n;i++)//\u521D\u59CB\u5316\u6807\u6746 \n for(int j=0;j<m;j++)\n lx[i]=Math.max(lx[i],w[i][j]);\n for(int i=0;i<n;i++) {//x\u8FB9\u6BCF\u4E2A\u70B9\u7684\u5339\u914D \n while(true) {\n boolean[] s = new boolean[n];\n boolean[] t = new boolean[m];\n if(find(i, s, t, from, to, lx, ly, w)) break;\n else update(s, t, from, to, lx, ly, w);\n }\n }\n \n int ans=0;\n for(int i=0;i<n;i++)//\u8BA1\u7B97\u7B54\u6848 \n ans+=w[i][to[i]];\n \n return ans;\n }\n \n private boolean find(int x, boolean[] s, boolean[] t, int[] from, int[] to, int[] lx, int[] ly, int[][] w) { //\u5308\u7259\u5229\u7B97\u6CD5 \n int m = t.length;\n s[x]=true;\n for(int i=0;i<m;i++){\n if(lx[x]+ly[i]==w[x][i]&&!t[i]) {\n t[i]=true;\n if(from[i]<0 || find(from[i], s, t, from, to, lx, ly, w)) {\n from[i]=x;\n to[x]=i;\n return true;\n }\n }\n }\n return false;\n }\n \n private void update(boolean[] s, boolean[] t, int[] from, int[] to, int[] lx, int[] ly, int[][] w)//\u66F4\u65B0\u6807\u6746 \n {\n int n = s.length;\n int m = t.length;\n int d = Integer.MAX_VALUE;\n for(int i=0;i<n;i++){\n if(s[i]){\n for(int j=0;j<m;j++){\n if(!t[j]){\n d=Math.min(d,lx[i]+ly[j]-w[i][j]);//\u6309\u7167\u4E0A\u9762\u7ED9\u51FA\u7684\u539F\u5219\u8BA1\u7B97d \n }\n }\n }\n }\n for(int i=0;i<n;i++)//\u70B9\u96C6s\u4E2D\u7684\u70B9\u7684\u6807\u6746lx[i]-d \n if(s[i]) lx[i]-=d;\n for(int j=0;j<m;j++)//\u70B9\u96C6t\u4E2D\u7684\u70B9\u7684\u6807\u6746ly[j]+d \n if(t[j]) ly[j]+=d;\n }\n\n} | 1 | 2 | [] | 0 |
maximum-compatibility-score-sum | [C++] DP + next_permutation() 100% fast | c-dp-next_permutation-100-fast-by-satvik-tfjr | \nclass Solution {\npublic:\n\n int maxCompatibilitySum(vector<vector<int>>& s, vector<vector<int>>& m) {\n vector<vector<int>>dp(s.size(),vector<int> | satvikshrivas | NORMAL | 2021-07-25T04:06:07.042285+00:00 | 2021-07-25T13:41:24.889950+00:00 | 236 | false | ```\nclass Solution {\npublic:\n\n int maxCompatibilitySum(vector<vector<int>>& s, vector<vector<int>>& m) {\n vector<vector<int>>dp(s.size(),vector<int>(s.size(),0));\n \n for(int i =0;i<s.size();i++){\n for(int j =0;j<s.size();j++){\n int cnt=0;\n for(int x =0;x<s[0].size();x++){\n if(s[i][x] == m[j][x])\n cnt++;\n } \n dp[i][j]=cnt;\n }\n }\n \n vector<int>a;\n for(int i =0;i<s.size();i++)a.push_back(i);\n \n int ans=0;\n do{\n int res=0;\n for(int i =0;i<dp.size();i++){\n int sum=0;\n for(int j =0;j<a.size();j++)sum+=dp[j][a[j]];\n res = max(res,sum);\n }\n ans = max(ans,res);\n }while(next_permutation(a.begin(),a.end()));\n \n return ans;\n }\n};\n``` | 1 | 1 | ['Dynamic Programming', 'C'] | 0 |
maximum-compatibility-score-sum | Python Solution | python-solution-by-lzhangucb-9mct | \nclass Solution(object):\n def maxCompatibilitySum(self, students, mentors):\n """\n :type students: List[List[int]]\n :type mentors: L | lzhangucb | NORMAL | 2021-07-25T04:05:02.211987+00:00 | 2021-07-25T04:13:54.896320+00:00 | 75 | false | ```\nclass Solution(object):\n def maxCompatibilitySum(self, students, mentors):\n """\n :type students: List[List[int]]\n :type mentors: List[List[int]]\n :rtype: int\n """\n m = len(students)\n n = len(students[0])\n scores =[ [sum([students[i][k] == mentors[j][k] for k in range(n)]) for i in range(m)] for j in range(m)]\n \n \n #print(scores)\n def get_maximum_scores(mat):\n if len(mat) == 1:\n return mat[0][0]\n else:\n lst = [mat[0][j]+ get_maximum_scores( [mat[k1][:j] + mat[k1][j+1:] for k1 in range(1, len(mat)) ]) for j in range(len(mat))]\n return max(lst)\n \n return get_maximum_scores(mat = scores)\n``` | 1 | 1 | [] | 0 |
maximum-compatibility-score-sum | Python solution with backtracking | python-solution-with-backtracking-by-rhp-d1ic | \nclass Solution:\n \n def check_commonality(self, student, mentor):\n i = 0\n count = 0\n while i < len(student):\n if st | rhpatel | NORMAL | 2021-07-25T04:04:49.366262+00:00 | 2021-07-25T04:05:54.777608+00:00 | 235 | false | ```\nclass Solution:\n \n def check_commonality(self, student, mentor):\n i = 0\n count = 0\n while i < len(student):\n if student[i] == mentor[i]:\n count+=1\n i+=1\n return count\n \n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n matrix = [[0 for x in range(len(mentors))] for y in range(len(students))]\n \n for i in range(len(students)):\n for j in range(len(mentors)):\n matrix[i][j] = self.check_commonality(students[i], mentors[j])\n nums_ = []\n def dfs(i, sum_, visited):\n if i == len(matrix):\n nums_.append(sum_)\n return\n max_ = 0\n for j in range(len(matrix[0])):\n if j not in visited:\n visited.append(j)\n dfs(i+1, sum_ + matrix[i][j], visited)\n visited.pop()\n dfs(0, 0, [])\n \n return max(nums_)\n``` | 1 | 0 | ['Combinatorics', 'Python', 'Python3'] | 0 |
maximum-compatibility-score-sum | JAVA | Simple DFS | java-simple-dfs-by-uchihasasuke-ag26 | \nclass Solution {\n int[][] students;\n int[][] mentors;\n int len = 0;\n int res = 0;\n public int maxCompatibilitySum(int[][] _students, int[] | uchihasasuke | NORMAL | 2021-07-25T04:01:19.850762+00:00 | 2021-07-25T04:07:11.389082+00:00 | 169 | false | ```\nclass Solution {\n int[][] students;\n int[][] mentors;\n int len = 0;\n int res = 0;\n public int maxCompatibilitySum(int[][] _students, int[][] _mentors) { \n students = _students;\n mentors = _mentors;\n if(students == null || students.length == 0 || mentors == null || mentors.length == 0) {\n return 0;\n }\n \n len = students.length;\n dfs(0, new ArrayList<>(), new HashSet<Integer>());\n return res;\n }\n \n private void dfs(int index, ArrayList<int[]> list, HashSet<Integer> set) {\n if(list.size() == len) {\n //System.out.println(list.size());\n int temp = score(list);\n res = Math.max(temp, res);\n }\n \n for(int i = 0; i < len; i++) {\n if(!set.contains(i)) {\n set.add(i);\n list.add(mentors[i]);\n dfs(i + 1, list, set);\n list.remove(mentors[i]); \n set.remove(i);\n }\n } \n }\n\n private int score(ArrayList<int[]> list) {\n int count = 0;\n for(int i = 0; i < list.size(); i++) {\n int[] student = students[i];\n int[] mentor = list.get(i);\n for(int p = 0; p < student.length; p++) {\n if(student[p] == mentor[p]) {\n count++;\n }\n }\n }\n return count;\n } \n}\n``` | 1 | 1 | [] | 0 |
maximum-compatibility-score-sum | brute-force C++ permutations | brute-force-c-permutations-by-claytonjwo-77bx | \nclass Solution {\npublic:\n using VI = vector<int>;\n using VVI = vector<VI>;\n int maxCompatibilitySum(VVI& A, VVI& B, int best = 0) {\n int | claytonjwong | NORMAL | 2021-07-25T04:00:45.417795+00:00 | 2021-07-25T04:00:45.417823+00:00 | 167 | false | ```\nclass Solution {\npublic:\n using VI = vector<int>;\n using VVI = vector<VI>;\n int maxCompatibilitySum(VVI& A, VVI& B, int best = 0) {\n int M = A.size(),\n N = A[0].size();\n sort(A.begin(), A.end());\n do {\n auto cand = 0;\n for (auto i{ 0 }; i < M; ++i)\n for (auto j{ 0 }; j < N; ++j)\n cand += A[i][j] == B[i][j];\n best = max(best, cand);\n } while (next_permutation(A.begin(), A.end()));\n return best;\n }\n};\n``` | 1 | 0 | [] | 0 |
maximum-compatibility-score-sum | Using Recursion | using-recursion-by-rachanikhilrnr-abwp | IntuitionHere you need to understand that you can link any of the student to any of the mentor and explore all the posibilities to get max scoreApproachI hope y | rachanikhilrnr | NORMAL | 2025-04-10T07:10:49.029468+00:00 | 2025-04-10T07:10:49.029468+00:00 | 3 | false | # Intuition
Here you need to understand that you can link any of the student to any of the mentor and explore all the posibilities to get max score
# Approach
I hope you already know recursion & dynamic programming !
Loop through all the students
One student at a time and try all possiblities of mentors...
Consider i=0, 0th index student linked to one mentor randomly and count score then next
Consider i=1, now linked any other mentor to 1th index student randomly...
keep this going on...
Through recursion find max scores in all possiblities
# Complexity
- Time complexity:
2^n since it is recursion
- Space complexity:
O(n^2)
# Code
```java []
class Solution {
public int maxCompatibilitySum(int[][] students, int[][] mentors) {
boolean menVis[] = new boolean[mentors.length];
int n = students.length;
return f(n-1,students,mentors,menVis);
}
public static int f(int i,int[][] students,int[][] mentors,boolean[] menVis){
if(i<0) return 0;
int max = 0;
for(int j=0;j<menVis.length;j++){
if(menVis[j]==false){
menVis[j]=true;
int points = 0 ;
for(int k=0;k<mentors[j].length;k++){
if(students[i][k]==mentors[j][k]) points++;
}
int sum = points+f(i-1,students,mentors,menVis);
menVis[j]=false;
max = Math.max(sum,max);
}
}
return max;
}
}
| 0 | 0 | ['Dynamic Programming', 'Recursion', 'Java'] | 0 |
reshape-the-matrix | Java Concise O(nm) time | java-concise-onm-time-by-compton_scatter-d1vc | \npublic int[][] matrixReshape(int[][] nums, int r, int c) {\n int n = nums.length, m = nums[0].length;\n if (r*c != n*m) return nums;\n int[][] res = | compton_scatter | NORMAL | 2017-04-30T03:04:28.788000+00:00 | 2018-10-24T18:17:30.146724+00:00 | 31,347 | false | ```\npublic int[][] matrixReshape(int[][] nums, int r, int c) {\n int n = nums.length, m = nums[0].length;\n if (r*c != n*m) return nums;\n int[][] res = new int[r][c];\n for (int i=0;i<r*c;i++) \n res[i/c][i%c] = nums[i/m][i%m];\n return res;\n}\n``` | 327 | 2 | [] | 36 |
reshape-the-matrix | One loop | one-loop-by-stefanpochmann-gut1 | We can use matrix[index / width][index % width] for both the input and the output matrix.\n\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n | stefanpochmann | NORMAL | 2017-04-30T07:11:21.850000+00:00 | 2018-09-26T04:54:59.576207+00:00 | 18,359 | false | We can use `matrix[index / width][index % width]` for both the input and the output matrix.\n\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int m = nums.length, n = nums[0].length;\n if (r * c != m * n)\n return nums;\n int[][] reshaped = new int[r][c];\n for (int i = 0; i < r * c; i++)\n reshaped[i/c][i%c] = nums[i/n][i%n];\n return reshaped;\n } | 171 | 3 | [] | 17 |
reshape-the-matrix | ✅ C++ One-Loop Easy Solution | Column-first and Row-first Approaches | c-one-loop-easy-solution-column-first-an-m23c | There\'s nothing much to this problem - Just check if total elements in both matrices will be same and then transform. I have mentioned two approaches below.\n\ | archit91 | NORMAL | 2021-07-05T07:33:14.194909+00:00 | 2022-01-12T18:49:52.143808+00:00 | 15,977 | false | There\'s nothing much to this problem - Just check if total elements in both matrices will be same and then transform. I have mentioned two approaches below.\n\n----\n\n\u2714\uFE0F ***Solution (Row-First Approach)***\n\nIterate each row column-by-column, wrap around when you reach the end on one row and move to the next row. Here, we are copying all elements of one row and then moving on to the next row.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat;\n vector<vector<int>> ans(r, vector<int>(c));\n for(int i = 0; i < total; i++) \n ans[i / c][i % c] = mat[i / n][i % n];\n return ans;\n }\n};\n```\n\n<blockquote>\n<details>\n<summary><b>\u2714\uFE0F Commented Solution</b></summary>\n\n\nIf the above appraoch was not clear, you can refer the below commented code -\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat; // return if total elements don\'t match\n vector<vector<int>> ans(r, vector<int>(c));\n int i = 0, j = 0, new_i = 0, new_j = 0; // i, j iterates over old matrix | new_i, new_j iterates over new matrix\n while(total--) {\n ans[new_i][new_j] = mat[i][j]; \n j++, new_j++; // move to next column in both matrix\n if(j == n) j = 0, i++; // start from beginning of next row when you reach the end of row in old matrix\n if(new_j == c) new_j = 0, new_i++; // start from beginning of next row when you reach the end of row in new matrix\n }\n return ans;\n }\n};\n```\n\n</details>\n</blockquote>\n\n***Time Complexity :*** `O(r*c)`\n***Space Complexity :*** `O(1)`, ignoring output space complexity\n\n\n---\n\n\u2714\uFE0F ***Solution - II (Column-First Appraoch)***\n\nAll other posts have mentioned the first approach. It might be a good follow-up to try implementing it using column-first approach.\n\nIterate each column row-by-row, wrap around when you reach the end on one column and then move to the next column. Here, we are copying all elements of one column and then moving on to the next column.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat; \n vector<vector<int>> ans(r, vector<int>(c));\n for(int col = 0; col < n; col++) {\n for(int row = 0; row < m; row++) {\n int new_row = (n * row + col) / c;\n int new_col = (n * row + col) % c;\n ans[new_row][new_col] = mat[row][col]; \n }\n }\n return ans;\n }\n};\n```\n\n<blockquote>\n<details>\n<summary><b>\u2714\uFE0F Single-Loop Solution</b></summary>\n\nIf anyone figures out a cleaner code than the following version, please let me know :)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat; \n vector<vector<int>> ans(r, vector<int>(c));\n for(int i = 0; i < total; i++) \n ans[(i%m * n + i/m) / c][(i%m * n + i/m) % c] = mat[i % m][i / m];\n return ans;\n }\n};\n```\n\n\n</details>\n</blockquote>\n\n***Time Complexity :*** `O(r*c)`\n***Space Complexity :*** `O(1)`, ignoring output space complexity\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n--- | 169 | 7 | ['C'] | 10 |
reshape-the-matrix | [Python] Intuitive + Direct for Beginners with Illustrations | python-intuitive-direct-for-beginners-wi-klng | Given a matrix mat of 3 rows * 4 columns, \nwe want reshape it into 2 rows (r = 2) * 6 columns(c = 6): \n\n[[0, 1, 2, 3],\n [4, 5, 6, 7], | ziaiz-zythoniz | NORMAL | 2022-05-17T05:45:14.586264+00:00 | 2022-05-17T06:04:56.764490+00:00 | 10,336 | false | Given a matrix `mat` of 3 rows * 4 columns, \nwe want reshape it into 2 rows (`r = 2`) * 6 columns(`c = 6`): \n```\n[[0, 1, 2, 3],\n [4, 5, 6, 7], -> [[0, 1, 2, 3, 4, 5],\n [8, 9, 10, 11]] [6, 7, 8, 9, 10, 11]]\n```\n**Step 1:** Flatten the given matrix `mat` to a 1-D list `flatten` for easier visualizations and calculations for future steps\n```\nflatten = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n```\n**Step 2:** Check whether the total number of given elements `len(flatten)` and the new shape `r * c` matches (i.e. whether "*given parameters is possible and legal*")\n```\nr = 2, c = 6\nr * c = 12\n```\n**Step 3:** Rearrange all elements in 1-D list `flatten` into the `new_mat` according to given number of row `r` and given number of columns `c`\n```\nflatten = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n```\n\nreshaping: \n```\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\nrow_index: 0\t\t\t| c0 c1 c2 c3 c4 c5 |\nrow_index: 1 \t\t\t | c0 c1 c2 c3 c4 c5 |\n\nindex in flatten: [row_index * c : row_index * c + c])\n\n\t\t\t [0*6 : 0*6 + 6], \n\t\t\t\t\t\t\t\t\t\t [1*6 : 1*6+6]\n\t\t\t\t\t\t\t\t\t\t\t\t \n [0 : 6], \n\t\t\t\t\t\t\t\t\t\t [6 : 12]\n```\n- **iteration 0**:` row_index` **0**\n```\nflatten[0 : 6] -> [0, 1, 2, 3, 4, 5]\n\nappending:\nnew_mat = [[0, 1, 2, 3, 4, 5]]\n```\n- **iteration 1**: `row_index` **1**\n```\nflatten[6 : 12] -> [6, 7, 8, 9, 10, 11]\n\nappending:\nnew_mat = [[0, 1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10, 11]]\n```\n\n\n\n___________________________\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n flatten = []\n new_mat = []\n for row in mat:\n for num in row:\n flatten.append(num)\n \n if r * c != len(flatten): # when given parameters is NOT possible and legal\n return mat\n else:\n for row_index in range(r):\n new_mat.append(flatten[row_index * c : row_index * c + c])\n return new_mat\n```\n\n________________________________________________________________________\n\nAs a total beginner, I am writing these all out to help myself, and hopefully also help anyone out there who is like me at the same time.\n\nPlease upvote\u2B06\uFE0F if you find this helpful or worth-reading for beginners in anyway. \nYour upvote is much more than just supportive to me. \uD83D\uDE33\uD83E\uDD13\uD83E\uDD70\n\nIf you find this is not helpful, needs improvement, or is questionable, would you please leave a quick comment below to point out the problem before you decide to downvote? It will be very helpful for me (maybe also others) to learn as a beginner.\n\nThank you very much either way \uD83E\uDD13.\n | 157 | 0 | ['Matrix', 'Python', 'Python3'] | 10 |
reshape-the-matrix | JAVA SOLUTION || DETAILED EXPLANATION || EASY APPROCH || 100% Efficent | java-solution-detailed-explanation-easy-qvyv3 | Approch -``\n\n1st condition to be checked -\nFirstly will have to check if the product of dimension of the given array matrix(mat) and the product of dimension | sarrthac | NORMAL | 2022-01-28T18:27:21.701045+00:00 | 2022-01-28T18:27:50.503700+00:00 | 10,447 | false | # Approch -``\n\n***1st condition** to be checked -*\nFirstly will have to check if the product of dimension of the given array matrix(**mat**) and the product of dimensions of the new array matrix are eqaul. If they are not equal this means we cannot fill all the elements perfectly in one of the matrix hence in this condition, will have to return the original array.\n\n***Secondly***, we will traverse through the first matrix and add the elements in our newly created **output matrix**, but here we have to keep in mind to add elements column wise and not row wise. i.e we will maintain two seperate pointers for rows and colums and firstly we will go through colums & if (**column == c**) then we will move to next row & also set the column pointer to zero again.\n\n***For Better unnderstnading let\'s look at the code***\n\n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n \n //Storing the values of mat matrix\n //i.e m = rows & n = cols\n int rows = mat.length;\n int cols = mat[0].length;\n \n //if the product of rows & cols of mat matrix and the new matrix are not same then return original matrix\n if((rows * cols) != (r * c)) return mat;\n \n //Creating the new matrix\n int[][] output = new int[r][c];\n int output_rows = 0;\n int output_cols = 0;\n \n \n //Traversing the mat matrix and storing the its values in new matrix output cols wise\n for(int i = 0; i < rows; i++)\n {\n for(int j = 0; j < cols; j++)\n {\n output[output_rows][output_cols] = mat[i][j];\n output_cols++;\n \n //if the cols value reached then change the row and set the cols value to 0.\n if(output_cols == c)\n {\n output_cols = 0;\n output_rows++;\n }\n }\n }\n \n return output;\n }\n}\n```\n\n\n**If found helpful, please upvote.\nThank You !!** | 141 | 1 | ['Java'] | 12 |
reshape-the-matrix | Python Solutions | python-solutions-by-stefanpochmann-lzxb | Solution 1 - NumPy\n\n\nWhen I read "MATLAB", I immediately thought "NumPy". Thanks to @fallcreek for pointing out tolist, makes converting the result to the co | stefanpochmann | NORMAL | 2017-04-30T07:01:29.434000+00:00 | 2017-04-30T07:01:29.434000+00:00 | 19,772 | false | #### **Solution 1 - `NumPy`**\n\n\nWhen I read "MATLAB", I immediately thought "NumPy". Thanks to @fallcreek for pointing out `tolist`, makes converting the result to the correct type easier than what I had originally.\n```\nimport numpy as np\n\nclass Solution(object):\n def matrixReshape(self, nums, r, c):\n try:\n return np.reshape(nums, (r, c)).tolist()\n except:\n return nums\n```\n#### **Solution 2 - Oneliner**\n\nAn ugly oneliner :-)\n\n def matrixReshape(self, nums, r, c):\n return nums if len(sum(nums, [])) != r * c else map(list, zip(*([iter(sum(nums, []))]*c)))\n\nA more readable version of that:\n\n def matrixReshape(self, nums, r, c):\n flat = sum(nums, [])\n if len(flat) != r * c:\n return nums\n tuples = zip(*([iter(flat)] * c))\n return map(list, tuples)\n\n#### **Solution 3 - `itertools`**\n\n def matrixReshape(self, nums, r, c):\n if r * c != len(nums) * len(nums[0]):\n return nums\n it = itertools.chain(*nums)\n return [list(itertools.islice(it, c)) for _ in xrange(r)] | 91 | 10 | [] | 16 |
reshape-the-matrix | [Python] One pass - Clean & Concise | python-one-pass-clean-concise-by-hiepit-dp9y | Python 3\n\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n | hiepit | NORMAL | 2021-07-05T08:04:11.715005+00:00 | 2021-07-05T08:04:11.715047+00:00 | 3,686 | false | **Python 3**\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n if r * c != m * n: return mat # Invalid size -> return original matrix\n ans = [[0] * c for _ in range(r)]\n for i in range(m * n):\n ans[i // c][i % c] = mat[i // n][i % n]\n return ans\n```\n**Complexity**\n - Time & Space: `O(M*N)` | 65 | 3 | [] | 3 |
reshape-the-matrix | Javascript ES6 simple solution | javascript-es6-simple-solution-by-leomac-a8t6 | \nvar matrixReshape = function (nums, r, c) {\n var arr = nums.flat();\n if (r * c != arr.length) return nums;\n\n var res = [];\n while (arr.length) res.pu | leomacode | NORMAL | 2020-07-13T21:23:23.125193+00:00 | 2020-07-13T21:23:23.125228+00:00 | 2,832 | false | ```\nvar matrixReshape = function (nums, r, c) {\n var arr = nums.flat();\n if (r * c != arr.length) return nums;\n\n var res = [];\n while (arr.length) res.push(arr.splice(0, c));\n return res;\n};\n``` | 58 | 1 | ['JavaScript'] | 8 |
reshape-the-matrix | Easy Java Solution | easy-java-solution-by-shawngao-iotb | \npublic class Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int m = nums.length, n = nums[0].length;\n if (m * n ! | shawngao | NORMAL | 2017-04-30T03:05:45.954000+00:00 | 2018-09-03T23:15:13.686661+00:00 | 7,645 | false | ```\npublic class Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int m = nums.length, n = nums[0].length;\n if (m * n != r * c) return nums;\n \n int[][] result = new int[r][c];\n int row = 0, col = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n result[row][col] = nums[i][j];\n col++;\n if (col == c) {\n col = 0;\n row++;\n }\n }\n }\n \n return result;\n }\n}\n``` | 53 | 1 | [] | 8 |
reshape-the-matrix | C solution | c-solution-by-stefanpochmann-uq1n | \nint** matrixReshape(int** nums, int m, int n, int r, int c, int** columnSizes, int* returnSize) {\n if (r * c != m * n) {\n r = m;\n c = n;\n | stefanpochmann | NORMAL | 2017-05-03T12:28:04.121000+00:00 | 2018-10-14T03:57:36.655603+00:00 | 11,002 | false | ```\nint** matrixReshape(int** nums, int m, int n, int r, int c, int** columnSizes, int* returnSize) {\n if (r * c != m * n) {\n r = m;\n c = n;\n }\n\n *returnSize = r;\n int** result = (int**) malloc(r * sizeof(int*));\n *columnSizes = (int*) malloc(r * sizeof(int));\n for (int i = 0; i < r; ++i) {\n result[i] = (int*) malloc(c * sizeof(int));\n (*columnSizes)[i] = c;\n }\n \n for (int i = 0; i < m * n; ++i)\n result[i/c][i%c] = nums[i/n][i%n];\n\n return result;\n}\n```\n\nMost of the code is for creating the data structure, not for writing the real contents into it. This must be fun for masochists :-). I just did this because of @leaf2's [question about C solutions](https://discuss.leetcode.com/topic/88089/anyone-has-c-solution-of-this-question) and similar questions I've seen occasionally. Was a little challenge.\n\nThings to notice:\n- If the requested shape is invalid, we can't just return `nums` (which is what the problem text somewhat sounds like). Think about what the judge is probably doing. Probably it uses and frees all the result data (the data pointed to by the `return` value as well as what we write in `returnSize` and `columnSizes`). So we should create an independent *copy* of the input matrix with all its own data. I do this by simply changing `r` and `c` to the input shape and then continuing as otherwise. Can also be done like this:\n\n if (r * c != m * n)\n return matrixReshape(nums, m, n, m, n, columnSizes, returnSize);\n\n- The "sizes" we must write to are the numbers of rows and columns, not the malloc sizes (i.e., not multiplied with `sizeof(...)`). I found that unclear in the specification, but on the other hand, it makes more sense if you think about what the judge code probably looks like.\n- I renamed `numsRowSize` and `numsColSize` to the standard matrix size names `m` and `n`. Can't stand those awfully long and nonstandard names. | 46 | 4 | [] | 5 |
reshape-the-matrix | Easy-to-understand python solution | easy-to-understand-python-solution-by-pe-0l7q | \nclass Solution(object):\n def matrixReshape(self, nums, r, c):\n """\n :type nums: List[List[int]]\n :type r: int\n :type c: in | peterwu | NORMAL | 2017-06-03T12:16:03.449000+00:00 | 2018-09-29T06:42:06.460468+00:00 | 4,732 | false | ```\nclass Solution(object):\n def matrixReshape(self, nums, r, c):\n """\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n """\n if len(nums) * len(nums[0]) != r * c:\n return nums\n \n ans = [[]]\n for i in range(len(nums)):\n for j in range(len(nums[0])):\n k = nums[i][j]\n if len(ans[-1]) < c:\n ans[-1].append(k)\n else:\n ans.append([k])\n return ans\n``` | 44 | 1 | ['Python'] | 9 |
reshape-the-matrix | Very Easy || 100% || Fully Explained || Java, C++, Python, JavaScript, Python3 | very-easy-100-fully-explained-java-c-pyt-7gwt | Java Solution:\n\n// Runtime: 1 ms, faster than 92.33% of Java online submissions for Reshape the Matrix.\n// Time Complexity : O(r*c)\n// Space Complexity : O( | PratikSen07 | NORMAL | 2022-08-26T18:00:17.806842+00:00 | 2022-08-26T18:00:17.806887+00:00 | 6,172 | false | # **Java Solution:**\n```\n// Runtime: 1 ms, faster than 92.33% of Java online submissions for Reshape the Matrix.\n// Time Complexity : O(r*c)\n// Space Complexity : O(r*c)\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n // If transformation doesn\'t occur, return mat...\n if (mat.length * mat[0].length != r * c) {\n return mat;\n }\n // Otherwise create a output matrix and fill the cells...\n int[][] output = new int[r][c];\n // Traverse the matrix through the loop... \n for (int idx = 0; idx < r * c; idx++) {\n // idx % c will give us the current column number...\n // idx / c will give us how many rows we have completely filled...\n output[idx/c][idx % c] = mat[idx / mat[0].length][idx % mat[0].length];\n }\n return output; // Return the output matrix...\n }\n}\n```\n\n# **C++ Solution:**\n```\n// Time Complexity : O(r*c)\n// Space Complexity : O(r*c)\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n // If transformation doesn\'t occur, return mat...\n if (mat.size() * mat[0].size() != r * c) {\n return mat;\n }\n // Otherwise create a output matrix and fill the cells...\n vector<vector<int>> output(r, vector<int>(c));\n // Traverse the matrix through the loop... \n for (int idx = 0; idx < r * c; idx++) {\n // idx % c will give us the current column number...\n // idx / c will give us how many rows we have completely filled...\n output[idx/c][idx % c] = mat[idx / mat[0].size()][idx % mat[0].size()];\n }\n return output; // Return the output matrix...\n }\n};\n```\n\n# **Python/Python3 Solution:**\n```\n# Time Complexity : O(r*c)\n# Space Complexity : O(r*c)\nclass Solution(object):\n def matrixReshape(self, mat, r, c):\n # Base case...\n if not mat: return mat\n # If transformation doesn\'t occur, return mat...\n if len(mat) * len(mat[0]) != r * c:\n return mat\n # Otherwise create a output matrix and fill the cells...\n output = [[0 for i in range(c)] for i in range(r)]\n idx = 0\n # Traverse the matrix through the loop... \n while idx < r * c:\n # idx % c will give us the current column number...\n # idx / c will give us how many rows we have completely filled...\n output[idx // c][ idx % c] = mat[idx // len(mat[0])][idx % len(mat[0])]\n idx += 1\n return output # Return the output matrix...\n```\n \n# **JavaScript Solution:**\n```\n// Time Complexity : O(r*c)\n// Space Complexity : O(r*c)\nvar matrixReshape = function(mat, r, c) {\n // If transformation doesn\'t occur, return mat...\n if (mat.length * mat[0].length != r * c) {\n return mat;\n }\n // Otherwise create a output matrix and fill the cells...\n const output = new Array(r).fill(0).map(() => new Array(c).fill(0));\n // Traverse the matrix through the loop... \n for (let idx = 0; idx < r * c; idx++) {\n // idx % c will give us the current column number...\n // idx / c will give us how many rows we have completely filled...\n output[Math.floor(idx/c)][idx % c] = mat[Math.floor(idx / mat[0].length)][idx % mat[0].length];\n }\n return output; // Return the output matrix...\n};\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 39 | 2 | ['Array', 'C', 'Matrix', 'Simulation', 'Python', 'Java', 'Python3', 'JavaScript'] | 4 |
reshape-the-matrix | [C++] [Java] Clean Code - 5 lines (2 Solution) | c-java-clean-code-5-lines-2-solution-by-tyv4v | Java\n\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int m = nums.length, n = nums[0].length, o = m * n;\n i | alexander | NORMAL | 2017-04-30T03:08:34.543000+00:00 | 2018-09-06T06:57:20.812361+00:00 | 10,619 | false | **Java**\n```\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int m = nums.length, n = nums[0].length, o = m * n;\n if (r * c != o) return nums;\n int[][] res = new int[r][c];\n for (int i = 0; i < o; i++) res[i / c][i % c] = nums[i / n][i % n];\n return res; \n }\n}\n```\n**C++**\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size(), n = nums[0].size(), o = m * n;\n if (r * c != o) return nums;\n vector<vector<int>> res(r, vector<int>(c, 0));\n for (int i = 0; i < o; i++) res[i / c][i % c] = nums[i / n][i % n];\n return res;\n }\n};\n```\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size(), n = nums[0].size();\n if (m * n != r * c) {\n return nums;\n }\n\n vector<vector<int>> res(r, vector<int>(c, 0));\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int k = i * n + j;\n res[k / c][k % c] = nums[i][j];\n }\n }\n\n return res;\n }\n};\n``` | 39 | 1 | [] | 6 |
reshape-the-matrix | Python, Simple with Explanation | python-simple-with-explanation-by-awice-xuuz | Collect the values of the array A, and then put them into the answer of size nR x nC.\n\n\ndef matrixReshape(self, A, nR, nC):\n if len(A) * len(A[0]) != nR | awice | NORMAL | 2017-04-30T03:02:39.101000+00:00 | 2017-04-30T03:02:39.101000+00:00 | 6,497 | false | Collect the values of the array A, and then put them into the answer of size ```nR x nC```.\n\n```\ndef matrixReshape(self, A, nR, nC):\n if len(A) * len(A[0]) != nR * nC:\n return A\n \n vals = (val for row in A for val in row)\n return [[vals.next() for c in xrange(nC)] for r in xrange(nR)]\n```\n\nAlternative solution without generators:\n```\ndef matrixReshape(self, A, nR, nC):\n if len(A) * len(A[0]) != nR * nC:\n return A\n \n vals = [val for row in A for val in row]\n ans = [[None] * nC for _ in xrange(nR)]\n i = 0\n for r in xrange(nR):\n for c in xrange(nC):\n ans[r][c] = vals[i]\n i += 1\n return ans | 37 | 2 | [] | 5 |
reshape-the-matrix | Python - One Line, Two Line, Yield, Generator, Circular Index, Numpy - with explaination(#556) | python-one-line-two-line-yield-generator-xiip | Solution #1: Using Numpy\nBelow is the one line code which makes use of numpy.reshape method provided by numpy.\npython\nimport numpy\nclass Solution:\n def | abhira0 | NORMAL | 2021-07-05T08:49:17.626368+00:00 | 2021-07-05T17:01:42.547471+00:00 | 2,068 | false | # Solution #1: Using Numpy\nBelow is the one line code which makes use of numpy.reshape method provided by numpy.\n```python\nimport numpy\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n return numpy.reshape(mat,(r,c)) if r*c==len(mat)*len(mat[0]) else mat\n```\n## Lets look into the breadcrumbs!!\n> NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.\n> [<<\\<Wikipedia\\>>>](https://en.wikipedia.org/wiki/NumPy)\n```python\nreturn A if B else C\n```\nThis kind of statement is similar to ternary operator. Returns `A` if `B` evaluates to `True`, if not return `C`.\n```python\nnumpy.reshape(matrix, (row,col))\n```\n> Above method gives a new shape to an array without changing its data.\n> [<<\\<NumPy Docs\\>>>](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html)\n```python\nif r*c==len(mat)*len(mat[0])\n```\nCondition: Check if the size of matrix is equals to the size of the matrix which is to be returned.\n```\nlen(mat) # gives the number of rows\nlen(mat[0]) # gives the number of columns\n```\n-------------------------\n\n# Solution #2: Using Queue\nBelow solution doesnt use any other libraries. But its written in two lines and makes use of another list/queue to build a matrix.\n```python\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n queue = [cell for row in mat for cell in row] if r*c==len(mat)*len(mat[0]) else []\n return [[queue.pop(0) for _ in range(c)] for _ in range(r)] if queue else mat\n```\n## Lets look into the breadcrumbs!!\n```python\nqueue = [cell for row in mat for cell in row] if r*c==len(mat)*len(mat[0]) else []\n```\n`queue` contains the flattened matrix (flattening from 2D to 1D, using [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order)). However speaking of memory, matrix is stored as 1D array in memory.\n`queue` will be empty if the size of given matrix and matrix supposed to be created does not match.\n```python\n [[queue.pop(0) for _ in range(c)] for _ in range(r)] if queue else mat\n```\nUsing row-major itself, we are creating a new matrix with new row_no and col_no, and finally return it.\n\n-----------------------------\n# Solution #3: Using Circular Index\nAnother two line solution which does not use any extra space or extrnal packages.\n```python\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n if r*c!=len(mat)*(cols:=len(mat[0])): return mat\n return [[mat[(i*c+j)//cols][(i*c+j)%cols] for j in range(c)] for i in range(r)]\n```\n## Lets look into the breadcrumbs!!\nAny 2D matrix will be stored as stated below on machines follwing row-major order.\n\n[<<\\<Image Source\\>>>](https://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays)\n[To know more, please make use of this webpage](https://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays)\n```python\nif r*c!=len(mat)*(cols:=len(mat[0])): return mat\n```\nReturn the given matrix if the size does not match\n```python\n(cols:=len(mat[0]) # this is an assignment expression\n```\nTo know more on assignment expressions, [click here](https://realpython.com/lessons/assignment-expressions/ "Real Python")\nWe are assigning `cols` the number of columns available in given matrix and returning the same value in one single line.\n```python\n(i*c+j) # conversion from row,column to offset\n(i*c+j)//cols # gives the row number of old matrix\n(i*c+j)%cols # givens the column number of old matrix\nmat[(i*c+j)//cols][(i*c+j)%cols] # gives you the value at specified row and column\n```\n\n-----------------------------\n# Solution #4: Using Yield\n```python\nclass Solution:\n def getCell(self, mat):\n for row in mat:\n for cell in row:\n yield cell\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n gen = self.getCell(mat)\n return [[next(gen) for _ in range(c)] for _ in range(r)] if len(mat) * len(mat[0]) == r * c else mat\n```\n## Lets look into the breadcrumbs!!\n```python\ndef getCell(self, mat):\n\tfor row in mat:\n\t\tfor cell in row:\n\t\t\tyield cell\n```\n`getCell()` is a generator method which returns the next element in the original/old matrix.\nTo know about generators, [click here](https://realpython.com/introduction-to-python-generators/)\n```python\n[[next(gen) for _ in range(c)] for _ in range(r)] if len(mat) * len(mat[0]) == r * c else mat\n```\nCreate a new matrix and return it if the condition of size satisfies, else return the old matrix.\n\n-----------------------------\n# Solution #5: Using Generator\n```python\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n gen = (cell for row in mat for cell in row)\n return [[next(gen) for _ in range(c)] for _ in range(r)] if len(mat) * len(mat[0]) == r * c else mat\n```\n## Lets look into the breadcrumbs!!\n```python\ngen = (cell for row in mat for cell in row)\n```\nIn the above solution (Solution#4), we used a generator method to generate next elements. Instead of writing a function, lets use generator expression. The only difference between Solution#4 and Solution#5 is that, 4 uses generator method and 5 uses generator expression.\n\n---------\nI hope this is helpful to you :)\n\n-------- | 29 | 1 | ['Queue', 'Python', 'Python3'] | 6 |
reshape-the-matrix | Python Beginner Solution - Beats 82% | python-beginner-solution-beats-82-by-lov-33de | ```\ndef rotate(nums, r, c):\n flat_list = []\n matrix = []\n\n for sublist in nums:\n for item in sublist:\n flat_list.append(item)\ | lovefishly | NORMAL | 2020-03-09T15:25:28.946178+00:00 | 2020-03-09T16:35:45.216072+00:00 | 2,965 | false | ```\ndef rotate(nums, r, c):\n flat_list = []\n matrix = []\n\n for sublist in nums:\n for item in sublist:\n flat_list.append(item)\n\n if len(flat_list) != r * c:\n return nums\n else:\n for i in range(0,len(flat_list),c):\n matrix.append(flat_list[i:i+c])\n return matrix | 29 | 0 | ['Python', 'Python3'] | 4 |
reshape-the-matrix | Java in one pass ,faster than 100% | java-in-one-pass-faster-than-100-by-rohi-49jv | Please UpVote if you like the solution Happy Coding !!!\n\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int m = nums.le | rohitkumarsingh369 | NORMAL | 2021-07-05T08:45:46.679606+00:00 | 2021-07-05T18:19:35.178708+00:00 | 1,112 | false | *Please **UpVote** if you like the solution **Happy Coding** !!!*\n```\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int m = nums.length, n = nums[0].length;\n if (r * c != m * n)\n return nums;\n int[][] reshaped = new int[r][c];\n for (int i = 0; i < r * c; i++)\n reshaped[i/c][i%c] = nums[i/n][i%n];\n return reshaped;\n }\n}\n``` | 21 | 0 | ['Java'] | 3 |
reshape-the-matrix | ✅ Reshape the Matrix | One-Loop Clean and Easy Solution | reshape-the-matrix-one-loop-clean-and-ea-ulhs | There\'s nothing much to this problem - Just check if total elements in both matrices will be same and then transform. I have mentioned two approaches below.\n\ | archit91 | NORMAL | 2021-07-05T07:34:34.589125+00:00 | 2021-07-05T08:53:11.441556+00:00 | 1,643 | false | There\'s nothing much to this problem - Just check if total elements in both matrices will be same and then transform. I have mentioned two approaches below.\n\n\u2714\uFE0F ***Solution (Row-First Approach)***\n\nIterate each row column-by-column, wrap around when you reach the end on one row and move to the next row. Here, we are copying all elements of one row and then moving on to the next row.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat;\n vector<vector<int>> ans(r, vector<int>(c));\n for(int i = 0; i < total; i++) \n ans[i / c][i % c] = mat[i / n][i % n];\n return ans;\n }\n};\n```\n\n<blockquote>\n<details>\n<summary><b>\u2714\uFE0F Commented Solution</b></summary>\n\n\nIf the above appraoch was not clear, you can refer the below commented code -\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat; // return if total elements don\'t match\n vector<vector<int>> ans(r, vector<int>(c));\n int i = 0, j = 0, new_i = 0, new_j = 0; // i, j iterates over old matrix | new_i, new_j iterates over new matrix\n while(total--) {\n ans[new_i][new_j] = mat[i][j]; \n j++, new_j++; // move to next column in both matrix\n if(j == n) j = 0, i++; // start from beginning of next row when you reach the end of row in old matrix\n if(new_j == c) new_j = 0, new_i++; // start from beginning of next row when you reach the end of row in new matrix\n }\n return ans;\n }\n};\n```\n\n</details>\n</blockquote>\n\n***Time Complexity :*** `O(r*c)`\n***Space Complexity :*** `O(r*c)`\n\n\n---\n\n\u2714\uFE0F ***Solution - II (Column-First Appraoch)***\n\nAll other posts have mentioned the first approach. It might be a good follow-up to try implementing it using column-first approach.\n\nIterate each column row-by-row, wrap around when you reach the end on one column and then move to the next column. Here, we are copying all elements of one column and then moving on to the next column.\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat; \n vector<vector<int>> ans(r, vector<int>(c));\n for(int col = 0; col < n; col++) {\n for(int row = 0; row < m; row++) {\n int new_row = (n * row + col) / c;\n int new_col = (n * row + col) % c;\n ans[new_row][new_col] = mat[row][col]; \n }\n }\n return ans;\n }\n};\n```\n\n<blockquote>\n<details>\n<summary><b>\u2714\uFE0F Single-Loop Solution</b></summary>\n\nIf anyone figures out a cleaner code than the following version, please let me know :)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat; \n vector<vector<int>> ans(r, vector<int>(c));\n for(int i = 0; i < total; i++) \n ans[(i%m * n + i/m) / c][(i%m * n + i/m) % c] = mat[i % m][i / m];\n return ans;\n }\n};\n```\n\n\n</details>\n</blockquote>\n\n***Time Complexity :*** `O(r*c)`\n***Space Complexity :*** `O(r*c)`\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n--- | 20 | 4 | ['C'] | 3 |
reshape-the-matrix | [Python] One pass solution, explained | python-one-pass-solution-explained-by-db-p8y1 | First approach is to reshape to line and then reshape it to new shape. However we can do smarter: just iterate over all elements line by line and use res[count/ | dbabichev | NORMAL | 2021-07-05T07:51:54.472515+00:00 | 2021-07-05T07:51:54.472543+00:00 | 844 | false | First approach is to reshape to line and then reshape it to new shape. However we can do smarter: just iterate over all elements line by line and use `res[count//c][count\\%c] = nums[i][j]` to fill element by element. \n\n#### Complexity\nTime complexity is `O(mn)`, space complexity is `O(mn)`, but in fact it is `O(1)` if we do not count output array.\n\n#### Code\n```python\nclass Solution:\n def matrixReshape(self, nums, r, c):\n m, n, count = len(nums), len(nums[0]), 0\n if m*n != r*c: return nums\n res = [[0] * c for _ in range(r)]\n for i, j in product(range(m), range(n)):\n res[count//c][count%c] = nums[i][j]\n count += 1 \n return res\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 19 | 2 | ['Math', 'Matrix'] | 1 |
reshape-the-matrix | Beats 100% || Simple and easy to understand || C++ | beats-100-simple-and-easy-to-understand-2h8k8 | \n\n# Code\n\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = mat.size() , n= mat[0] | Amit_2001 | NORMAL | 2023-01-17T21:23:35.727203+00:00 | 2023-01-17T21:23:35.727246+00:00 | 3,232 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = mat.size() , n= mat[0].size();\n vector<vector<int>>v(r,vector<int>(c));\n queue<int>q;\n if(m*n == r*c){\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n q.push(mat[i][j]);\n }\n }\n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n v[i][j] = q.front();\n q.pop();\n }\n }\n return v;\n }\n return mat;\n }\n};\n``` | 18 | 0 | ['C++'] | 0 |
reshape-the-matrix | [C++] Easy Implementation: For Beginners | c-easy-implementation-for-beginners-by-r-gni8 | Approach: Firstly, check the dimensions required to reshape the matrix. If the multiplication of rows and columns of the original matrix is not equal to the mul | rsgt24 | NORMAL | 2021-07-05T07:32:48.605372+00:00 | 2021-07-06T06:13:14.969942+00:00 | 921 | false | **Approach:** Firstly, check the dimensions required to reshape the matrix. If the multiplication of rows and columns of the original matrix is not equal to the multiplication of rows and columns of the required matrix, just return the given matrix.\n\nOtherwise,\nInitialise a variable **col as 0** and increment it till it reaches **c** i.e., number of columns required to reshape.\nAs soon as the variable **col** reaches **c**, all the elements we came across so far will be considered as a **row** and initialise **col as 0** again.\n\nKeep doing the process until the end which is **n * m** where **n is size of the row** and **m is size of the column** of the given matrix and return the **modified / reshaped** matrix.\n\n\n**Solution:**\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n \n if((r * c) != (mat.size() * mat[0].size()))\n return mat;\n \n vector<vector<int>> fans;\n \n int col = 0;\n vector<int> ans;\n for(int i = 0; i < mat.size(); i++)\n {\n \n for(int j = 0; j < mat[i].size(); j++)\n {\n if(c == col)\n {\n col = 0;\n fans.push_back(ans);\n ans.clear();\n }\n ans.push_back(mat[i][j]);\n col++;\n }\n }\n \n fans.push_back(ans);\n \n return fans;\n }\n};\n```\n\n\n**Time Complexity: O(n * m)**, where n is number of rows and m is number of columns. | 16 | 6 | ['Array', 'C'] | 1 |
reshape-the-matrix | C++ Easy Solution(Two approaches) | c-easy-solutiontwo-approaches-by-sethiya-hlid | class Solution {\npublic:\n vector> matrixReshape(vector>& mat, int r, int c) {\n\t\n int m=mat.size();\n int n=mat[0].size();\n if(mn!= | sethiyashristi20 | NORMAL | 2022-04-11T15:05:07.380817+00:00 | 2022-04-11T15:08:32.391662+00:00 | 1,011 | false | class Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n\t\n int m=mat.size();\n int n=mat[0].size();\n if(m*n!=r*c)return mat;\n vector<vector<int>>newm(r,vector<int>(c));\n for(int i=0;i<m*n;i++)\n {\n newm[i/c][i%c]=mat[i/n][i%n];\n }\n return newm;\n }\n};\n2nd solution\n\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n\t\n int m=mat.size();\n int n=mat[0].size();\n int ans=m*n;\n int ans1=r*c;\n if(ans!=ans1) return mat;\n int nc=0,nr=0;\n vector<vector<int>>v(r,vector<int>(c));\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<mat[i].size();j++)\n {\n if(nc==c)\n {\n nr++;\n nc=0;\n }\n v[nr][nc]=mat[i][j];\n nc++;\n }\n }\n return v;\n \n }\n};\n**Please do upvote if it helped** | 15 | 0 | ['C'] | 1 |
reshape-the-matrix | Easy Python Solution | Faster than 99.3% (76 ms) | With Comments | easy-python-solution-faster-than-993-76-6gqfi | Easy Python Solution | Faster than 99.3% (76 ms) | With Comments\nRuntime: 76 ms, faster than 99.30% of Python3 online submissions for Reshape the Matrix.\nMemo | the_sky_high | NORMAL | 2021-11-02T13:43:02.033982+00:00 | 2022-05-10T13:52:39.049697+00:00 | 1,754 | false | # Easy Python Solution | Faster than 99.3% (76 ms) | With Comments\n**Runtime: 76 ms, faster than 99.30% of Python3 online submissions for Reshape the Matrix.\nMemory Usage: 15 MB**\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n rw = len(mat)\n cl = len(mat[0])\n old = rw * cl\n new = r * c\n\t\t\n\t\t# checking if number of elements remains the same\n if old != new:\n return mat\n\n old = [ i for e in mat for i in e]\n new = []\n\n a = 0\n for i in range(r):\n temp = []\n for j in range(c):\n temp.append(old[a])\n a += 1\n new.append(temp)\n\n return new\n```\n | 15 | 0 | ['Python', 'Python3'] | 1 |
reshape-the-matrix | C++ solutions | c-solutions-by-infox_92-szmq | \nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size(), n = nums[0].size();\ | Infox_92 | NORMAL | 2022-11-08T03:52:43.689355+00:00 | 2022-11-08T03:52:43.689400+00:00 | 2,408 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size(), n = nums[0].size();\n if (m * n != r * c) {\n return nums;\n }\n\n vector<vector<int>> res(r, vector<int>(c, 0));\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int k = i * n + j;\n res[k / c][k % c] = nums[i][j];\n }\n }\n\n return res;\n }\n};\n``` | 14 | 0 | ['C', 'C++'] | 1 |
reshape-the-matrix | [JavaScript] JS 3 liner - 90% faster solution | javascript-js-3-liner-90-faster-solution-b10j | \nvar matrixReshape = function(mat, r, c) {\n const flat = mat.flat()\n if (flat.length !== r*c) return mat;\n return [...Array(r)].map(() => flat.spli | gnktgc | NORMAL | 2021-09-27T06:24:44.064418+00:00 | 2021-09-27T06:24:44.064464+00:00 | 1,075 | false | ```\nvar matrixReshape = function(mat, r, c) {\n const flat = mat.flat()\n if (flat.length !== r*c) return mat;\n return [...Array(r)].map(() => flat.splice(0,c)) \n};\n``` | 14 | 0 | ['JavaScript'] | 0 |
reshape-the-matrix | ✅ Reshape the Matrix | Simple Solution | reshape-the-matrix-simple-solution-by-sh-74pw | Solution:(Accepted)\n\nAs the question is very easy to follow but we need to keep these condition in mind,\n1) If number of elements in current matrix != r * c | shivaye | NORMAL | 2021-07-05T10:21:43.343593+00:00 | 2021-07-05T10:29:36.108472+00:00 | 266 | false | ***Solution:(Accepted)***\n```\nAs the question is very easy to follow but we need to keep these condition in mind,\n1) If number of elements in current matrix != r * c (Invalid case) then we have to return the current matrix.\n2) we will take two iterators to fill out new matrix ,\n\tRow iterator: ri\n\tCol iterator: ci\n3) if at any point our ci==c (It means we successfully covered the row), then we have to increment our row counter,\n\ti.e, ri++,\n\t--> As for the next row ci should start with 0 , so we make ci=0 also,\n4) We follow the same process (step 2 and 3) until every element is added to new matrix.\n\nPlease find the solution below:\n```\n**C++:**\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) \n {\n int m=mat.size();\n int n=mat[0].size();\n if(m*n!=r*c)\n return mat;\n vector<vector<int>> res(r);\n int ri=0,ci=0;\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(ci==c)\n {\n ri=ri+1;\n ci=0;\n }\n res[ri].push_back(mat[i][j]);\n ci=ci+1;\n }\n }\n return res;\n }\n};\n```\n***\n**if you found the post useful then do consider it for Upvotes :), Happy coding**\n***\n\n | 14 | 4 | [] | 1 |
reshape-the-matrix | A few JavaScript solutions | a-few-javascript-solutions-by-loctn-a5q3 | The intuitive way:\n\nvar matrixReshape = function(nums, h, w) {\n const m = nums.length, n = nums[0].length;\n if (m * n !== h * w) return nums;\n con | loctn | NORMAL | 2017-07-14T18:59:04.751000+00:00 | 2017-07-14T18:59:04.751000+00:00 | 1,539 | false | The intuitive way:\n```\nvar matrixReshape = function(nums, h, w) {\n const m = nums.length, n = nums[0].length;\n if (m * n !== h * w) return nums;\n const res = [];\n for (let i = 0, r = 0; r < m; r++) {\n for (let c = 0; c < n; c++, i++) {\n let rr = Math.floor(i / w);\n if (!res[rr]) res.push([]);\n res[rr].push(nums[r][c]);\n }\n }\n return res;\n};\n```\nOne loop:\n```\nvar matrixReshape = function(nums, h, w) {\n const m = nums.length, n = nums[0].length;\n if (m * n !== h * w) return nums;\n const res = [];\n for (let i = 0; i < m * n; i++) {\n let r = Math.floor(i / w);\n if (!res[r]) res.push([]);\n res[r].push(nums[Math.floor(i / n)][i % n]);\n }\n return res;\n};\n```\nTwo-liner:\n```\nvar matrixReshape = function(nums, h, w) {\n const all = nums.reduce((all, row) => [...all, ...row], []);\n return all.length === h * w ? new Array(h).fill(0).map((row, r) => all.slice(r * w, r * w + w)) : nums;\n};\n``` | 14 | 1 | ['JavaScript'] | 1 |
reshape-the-matrix | C++ || Reshape the Matrix || Easy understanding | c-reshape-the-matrix-easy-understanding-a2b27 | \nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n \n int m = mat.size();\n int | Sharan_k | NORMAL | 2022-01-28T13:18:05.409257+00:00 | 2022-01-28T13:18:05.409296+00:00 | 888 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n \n int m = mat.size();\n int n = mat[0].size();\n \n if(m * n != r * c) {\n return mat;\n }\n \n vector<vector<int>> res(r, vector<int>(c));\n int row = 0, col = 0;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n res[row][col] = mat[i][j];\n col += 1;\n if(col == c) {\n row += 1;\n col = 0;\n }\n }\n }\n return res;\n }\n};\n```\nPlease **UpVote**, if you understood the problem. | 12 | 0 | ['C', 'Matrix', 'C++'] | 1 |
reshape-the-matrix | C++ || EASY TO UNDERSTAND || FAST || 3 methods | c-easy-to-understand-fast-3-methods-by-a-q2sz | Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are alwa | aarindey | NORMAL | 2021-09-09T19:17:10.843524+00:00 | 2021-09-09T19:30:21.621495+00:00 | 985 | false | **Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are always welcome**\n\n**1st method**\n```\nclass Solution{\n public:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int n=mat.size(),m=mat[0].size();\n int all=n*m;\n if(all!=r*c)\n return mat; \n vector<vector<int>> ans(r,vector<int>(c,0));\n for(int i=0;i<all;i++)\n {\n ans[i/c][i%c]=mat[i/m][i%m];\n }\n return ans; \n }\n};\n```\n**2nd method**\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int n=mat.size(),m=mat[0].size(),k=0;\n if(c*r!=n*m)\n return mat;\n vector<vector<int>> ans;\n vector<int> v;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n v.push_back(mat[i][j]);\n k++;\n if(k==c)\n {\n k=0; \n ans.push_back(v); \n v.clear(); \n }\n }\n }\n return ans;\n }\n};\n```\n**Likewise,**\n```\nclass Solution{\n public:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int n=mat.size(),m=mat[0].size();\n if(m*n!=r*c)\n return mat;\n vector<vector<int>> ans(r, vector<int>(c, 0));\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n int k=m*i+j;\n ans[k/c][k%c]=mat[i][j];\n }\n }\n return ans;\n }\n};\n``` | 12 | 0 | ['C'] | 1 |
reshape-the-matrix | Java 0ms 100% Faster - 🍍 vs🍍🍍 Loops - Detailed Explanation | java-0ms-100-faster-vs-loops-detailed-ex-rsbl | \n\nHere are two solutions to this problem. One uses two loops, the other uses a single loop. The winner is announced at the end.\n# 2 Loops \uD83C\uDF4D\uD83C\ | mfeliciano | NORMAL | 2022-10-20T04:58:09.173512+00:00 | 2022-10-20T05:36:34.124259+00:00 | 1,002 | false | \n\nHere are two solutions to this problem. One uses two loops, the other uses a single loop. The winner is announced at the end.\n# 2 Loops \uD83C\uDF4D\uD83C\uDF4D \n```\n/**\n * Reshape the Matrix\n * In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new\n * one with a different size r x c keeping its original data.\n *\n * You are given an m x n matrix mat and two integers r and c representing the number of rows and\n * the number of columns of the wanted reshaped matrix.\n *\n * The reshaped matrix should be filled with all the elements of the original matrix in the same\n * row-traversing order as they were.\n *\n * If the reshape operation with given parameters is possible and legal, output the new reshaped\n * matrix; Otherwise, output the original matrix.\n * \n * Constraints:\n * m == mat.length\n * n == mat[i].length\n * 1 <= m, n <= 100\n * -1000 <= mat[i][j] <= 1000\n * 1 <= r, c <= 300\n */\nclass Solution {\n /*\n * To fill in the reshaped \'ret\' matrix, this algorithm has two loops. The outer loop\n * iterates over the rows of mat; the inner loop iterates over the cols of mat.\n *\n * Example:\n *\n * row 0 1\n * col ---------\n * row 0 1 2 0 | a | b |\n * col ------------ |-------|\n * 0 | a | b | c | 1 | c | d |\n * |-----------| -------> |-------|\n * 1 | d | e | f | 2 | e | f |\n * ----------- |-------|\n *\n * mat matrix ret matrix\n * mr = 1, mc = 3 r = 3, c = 2\n *\n *\n * -------- mat -------------- ------- ret ----------------\n * i j k mat[i][j] ret[k/c][k%c]\n * - - - --------------------------- ----------------------------\n * 0 0 0 mat[0,0] = a --> ret[0/2][0/2] = ret[0][0]\n * 0 1 1 mat[0,1] = b --> ret[1/2][1/2] = ret[0][1]\n * 0 2 2 mat[0,2] = c --> ret[2/2][2/2] = ret[1][0]\n * 1 0 3 mat[1,0] = d --> ret[3/2][3/2] = ret[1][1]\n * 1 1 4 mat[1,1] = e --> ret[4/2][4/2] = ret[2][0]\n * 1 2 5 mat[1,2] = f --> ret[5/2][5/2] = ret[2][1]\n *\n * The total number of division operations of the two loops is n * 2,\n * where n = mr * mc. This is half as many division operations as the\n * single-loop version below.\n */\n\tpublic int[][] matrixReshape(final int[][] mat, final int r, final int c) {\n final int mr = mat.length;\n final int mc = mat[0].length;\n final int n = mr * mc;\n\n // check arguments\n if (r * c != n) {\n return mat;\n }\n\n // create reshaped matrix\n final int[][] ret = new int[r][c];\n int k = 0; // number of cells filled in so far\n for (int i = 0; i < mr; i++) {\n for (int j = 0; j < mc; j++) {\n ret[k / c][k % c] = mat[i][j]; // see explanation above\n k++;\n }\n }\n return ret;\n }\n```\n---\n# Single Loop \uD83C\uDF4D\n```\n/*\n * To fill in the reshaped \'ret\' matrix, this algorithm iterates over n elements\n * where n is the rows multiplied by the columns.\n *\n * Example:\n *\n * row 0 1\n * col ---------\n * row 0 1 2 0 | a | b |\n * col ------------ |-------|\n * 0 | a | b | c | 1 | c | d |\n * |-----------| -------> |-------|\n * 1 | d | e | f | 2 | e | f |\n * ----------- |-------|\n *\n * mat matrix ret matrix\n * mr = 1, mc = 3 r = 3, c = 2\n *\n *\n * ----------- mat ------------ ----------- mat ------------\n * i mat[i/mc][i%mc] ret[i/c][i%c]\n * - ---------------------------- ----------------------------\n * 0 mat[0/3][0%3] = mat[0,0] = a --> ret[0/2][0/2] = ret[0][0]\n * 1 mat[1/3][1%3] = mat[0,1] = b --> ret[1/2][1/2] = ret[0][1]\n * 2 mat[2/3][2%3] = mat[0,2] = c --> ret[2/2][2/2] = ret[1][0]\n * 3 mat[3/3][3%3] = mat[1,0] = d --> ret[3/2][3/2] = ret[1][1]\n * 4 mat[4/3][4%3] = mat[1,1] = e --> ret[4/2][4/2] = ret[2][0]\n * 5 mat[5/3][5%3] = mat[1,2] = f --> ret[5/2][5/2] = ret[2][1]\n *\n * The total number of division operations of the single loop is n * 4,\n * where n = mr * mc. This is twice as many division operations as the\n * double-loop version above.\n */\n public int[][] matrixReshape(final int[][] mat, final int r, final int c) {\n final int mr = mat.length;\n final int mc = mat[0].length;\n final int n = mr * mc;\n\n // check arguments\n if (r * c != n) {\n return mat;\n }\n\n // create reshaped matrix\n final int[][] ret = new int[r][c];\n for (int i = 0; i < n; i++) {\n ret[i / c][i % c] = mat[i / mc][i % mc]; // see explanation above\n }\n return ret;\n }\n}\n```\n---\n# Comparison\uD83C\uDF4Dvs \uD83C\uDF4D\uD83C\uDF4D\n\nBoth solutions iterate over n = r * c elements. The first solution pays the cost of having additional int variables j and k, but that allows it to save 2 division operations per iteration as compared to the second solution. Also, the first solution has less cognitive complexity imo. Based on these two factors, the winner is \uD83E\uDD41... 2 fruit loops!\n\n\n | 11 | 0 | ['Java'] | 0 |
reshape-the-matrix | ✅ Reshape Matrix | Python | reshape-matrix-python-by-iamuday-5khf | Approach:\n\n1) At first we will chech weather the given dimension matrix can be created or not. (i.e mn == rc)\n2) We will be storing all the matrix elements i | IamUday | NORMAL | 2021-07-05T11:44:48.442343+00:00 | 2021-07-05T11:44:48.442374+00:00 | 630 | false | ### ***Approach***:\n\n1) At first we will chech weather the given dimension matrix can be created or not. ***(i.e mn == rc)***\n2) We will be **storing all** the matrix elements in a **1-d array** .\n3) We will initilize a empty matrix of given size (r,c) .\n4) We will Fill the initilize matrix row wise from that 1-d array\n\n### ***Code***\n```\nclass Solution:\n def matrixReshape(self, mat: list[list[int]], r: int, c: int) -> list[list[int]]:\n m = len(mat)\n n = len(mat[0])\n\t\t# Check weather the matrix can be made by using the given r,c values.\n if m*n != r*c:\n return mat\n\t\t# Storing in 1-d Array.\n arr = [0 for i in range(m*n)]\n count=0\n for i in range(m):\n for j in range(n):\n arr[count] = mat[i][j]\n count+=1\n\t\t# Initilize a new Matrix with given Dimensions\n new_matrix = [[0 for i in range(c)] for j in range(r)]\n count =0\n for i in range(r):\n for j in range(c):\n new_matrix[i][j]=arr[count]\n count+=1\n return new_matrix\n```\n\n***Time Complexity*** : O(RxC) \n***Space Complexity*** : O(RxC) where R,C are Row and Column .\n\nNote: This might not the be the best or the only approach , this is just my implementation, and I wanted to make it as simple as possible.\n\nIf you like it Please **Upvote** it. | 11 | 2 | ['Python'] | 1 |
reshape-the-matrix | [Python] SHORT, Easy List Comprehension | python-short-easy-list-comprehension-by-n4i6f | Reshape the Matrix\nIdea\n Fisrt we check if the matrix can be transformed\n Form one Dimension matrix OneD from given matrix mat by traversing row-wise\n Then | aatmsaat | NORMAL | 2021-07-05T09:27:53.368323+00:00 | 2021-07-05T09:32:51.210876+00:00 | 705 | false | # Reshape the Matrix\n**Idea**\n* Fisrt we check if the matrix can be transformed\n* Form one Dimension matrix `OneD` from given matrix **mat** by traversing row-wise\n* Then enter elements in the result of dimensions `r*c` one by one \xA0 \xA0 \xA0\n\n**Complexity**\n* *Time Complexity* :- `O(m*n)`\n* *Space Complexity* :- `O(m*n)`\n\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n if not m*n == r*c: return mat\n OneD = [mat[i][j] for i in range(m) for j in range(n)]\n return [OneD[i*c:(i+1)*c] for i in range(r)]\n```\n\n*Please upvote if you like the solution and comment if have any queries*. \xA0 \xA0 \xA0 \xA0 | 11 | 1 | ['Python'] | 1 |
reshape-the-matrix | Python solution | python-solution-by-yifanli1112-ai8m | I know that the code looks ugly, but it is good enough for a beginner like me :)\n\nclass Solution(object):\n def matrixReshape(self, nums, r, c):\n " | yifanli1112 | NORMAL | 2017-04-30T17:22:19.978000+00:00 | 2017-04-30T17:22:19.978000+00:00 | 1,396 | false | I know that the code looks ugly, but it is good enough for a beginner like me :)\n```\nclass Solution(object):\n def matrixReshape(self, nums, r, c):\n """\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n """\n nrows = len(nums)\n ncols = len(nums[0])\n \n if nrows * ncols == r * c:\n onedArray = []\n reshaped = [[0] * c for i in range(r)]\n for x in nums:\n onedArray += x\n for index, item in enumerate(onedArray):\n placeRow = index / c\n placeCol = index % c\n reshaped[placeRow][placeCol] = item\n return reshaped\n else:\n return nums\n``` | 11 | 0 | [] | 1 |
reshape-the-matrix | 6 Lines of Code ----> python | 6-lines-of-code-python-by-ganjinaveen-9rsd | \n# please upvote me it would encourage me alot\n\n\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n | GANJINAVEEN | NORMAL | 2023-03-19T18:36:38.699424+00:00 | 2023-03-19T18:36:38.699466+00:00 | 1,232 | false | \n# please upvote me it would encourage me alot\n\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n list1,matrix=list(chain.from_iterable(mat)),[]\n if len(mat)*len(mat[0])!=r*c:\n return mat\n for i in range(0,len(list1),c):\n matrix.append(list1[i:i+c])\n return matrix\n \n```\n# please upvote me it would encourage me alot\n | 10 | 0 | ['Python3'] | 0 |
reshape-the-matrix | Simple java solution | simple-java-solution-by-kushguptacse-soam | \npublic int[][] matrixReshape(int[][] mat, int r, int c) {\n int n=mat[0].length;\n if(r*c!=mat.length*n) {\n return mat;\n }\n | kushguptacse | NORMAL | 2022-11-01T17:21:39.852323+00:00 | 2022-11-01T17:21:39.852366+00:00 | 1,024 | false | ```\npublic int[][] matrixReshape(int[][] mat, int r, int c) {\n int n=mat[0].length;\n if(r*c!=mat.length*n) {\n return mat;\n }\n int[][] ans = new int[r][c];\n for(int i=0;i<r*c;i++) {\n ans[i/c][i%c]=mat[i/n][i%n];\n }\n return ans;\n }\n``` | 10 | 0 | ['Java'] | 1 |
reshape-the-matrix | [Java] Simple Solution in O(mn) time | java-simple-solution-in-omn-time-by-alan-ttj7 | \n\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if(r*c != mat.length*mat[0].length) return mat;\n int[][] re | alan24 | NORMAL | 2021-07-05T17:53:42.316824+00:00 | 2021-07-05T17:53:42.316872+00:00 | 910 | false | \n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if(r*c != mat.length*mat[0].length) return mat;\n int[][] res = new int[r][c];\n int ri = 0, cj = 0;\n for(int i=0; i<mat.length; ++i){\n for(int j=0; j<mat[0].length; ++j){\n //System.out.println(ri+" "+cj);\n res[ri][cj++] = mat[i][j];\n if(cj >= res[0].length){\n cj = 0;\n ri++;\n }\n }\n }\n return res;\n }\n}\n```\nplease leave a like if you found this helpful\nand leave a comment if you have any question\nhappy coding : ) | 10 | 1 | ['Java'] | 0 |
reshape-the-matrix | C++ Two Simple and Easy Solutions (6-Lines) | c-two-simple-and-easy-solutions-6-lines-614cx | First Solution - Intuitive:\nJust loop with nested loop through the original matrix, and keep track of the row and col in the new matrix.\n\nclass Solution {\np | yehudisk | NORMAL | 2021-07-05T07:30:50.313216+00:00 | 2021-07-05T07:34:14.562780+00:00 | 711 | false | **First Solution - Intuitive:\nJust loop with nested loop through the original matrix, and keep track of the row and col in the new matrix.**\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int area = mat.size() * mat[0].size();\n if (area != r * c) return mat;\n \n vector<vector<int>> res(r, vector<int>(c));\n int row = 0, col = 0;\n \n for (int i = 0; i < mat.size(); i++) {\n for (int j = 0; j < mat[i].size(); j++) {\n \n res[row][col] = mat[i][j];\n col++;\n \n if (col == c) {\n col = 0; \n row++;\n }\n }\n }\n \n return res;\n }\n};\n```\n**Second Solution - Shorter:\nSame idea, just with only one loop, using the same iterator to figure out where we are up to in both matrices.**\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int area = mat.size() * mat[0].size();\n if (area != r * c) return mat;\n \n vector<vector<int>> res(r, vector<int>(c));\n \n for (int i = 0; i < area; i++) {\n res[i/c][i%c] = mat[i/mat[0].size()][i%mat[0].size()];\n }\n\n return res;\n }\n};\n```\n**Like it? please upvote!** | 10 | 0 | ['C'] | 1 |
reshape-the-matrix | Easy to understand 😊 | easy-to-understand-by-sagarsindhu36-3lwq | Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to reshape the input matrix mat into a new matrix with r rows and c columns | sagarsindhu36 | NORMAL | 2024-01-29T06:52:36.080688+00:00 | 2024-01-29T06:53:00.427488+00:00 | 1,450 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to reshape the input matrix mat into a new matrix with r rows and c columns. The reshaping operation should be performed only if the total number of elements in the input matrix is equal to the total number of elements in the desired output matrix (i.e., **mat.length * mat[0].length == r * c)**.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **First, a new matrix \'s\' with dimensions \'r\' x \'c\' is created to store the reshaped matrix.**\n2. **Two variables, \'x\' and \'y\', are used to keep track of the current position in the new matrix \'s\'**.\n3. **If the total number of elements in the input matrix is equal to the total number of elements in the desired output matrix, the reshaping is possible. In that case:**\n - A nested loop is used to iterate through each element of the input matrix.\n - If the column index \'y\' reaches the desired number of columns \'c\', it means the current row is complete, so \'x\' is incremented, and \'y\' is reset to \'0\'.\n - The value of the current element in the input matrix \'mat\' is assigned to the corresponding position in the new matrix \'s\'.\n - The column index \'y\' is incremented.\n4. **If the reshaping is not possible (i.e., the total number of elements does not match), the original matrix \'mat\' is returned unchanged.**\n\n\n# Complexity\n- Time complexity: ***O(m * n)***\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: ***O(r * c)***\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n int[][] s = new int[r][c];\n int x = 0;\n int y = 0;\n if(mat.length * mat[0].length == r * c){\n for(int i =0; i<mat.length; i++){\n for(int j = 0; j<mat[0].length; j++){\n if(y==c){\n x++;\n y = 0;\n }\n s[x][y] = mat[i][j];\n y++;\n }\n }\n return s;\n }\n return mat;\n }\n}\n```\n```python []\nclass Solution:\n def matrixReshape(self, mat, r, c):\n s = [[0] * c for _ in range(r)]\n x, y = 0, 0\n\n if len(mat) * len(mat[0]) == r * c:\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n if y == c:\n x += 1\n y = 0\n s[x][y] = mat[i][j]\n y += 1\n return s\n return mat\n```\n```cpp []\n#include <vector>\n\nclass Solution {\npublic:\n std::vector<std::vector<int>> matrixReshape(std::vector<std::vector<int>>& mat, int r, int c) {\n std::vector<std::vector<int>> s(r, std::vector<int>(c, 0));\n int x = 0, y = 0;\n\n if (mat.size() * mat[0].size() == r * c) {\n for (int i = 0; i < mat.size(); ++i) {\n for (int j = 0; j < mat[0].size(); ++j) {\n if (y == c) {\n x++;\n y = 0;\n }\n s[x][y] = mat[i][j];\n y++;\n }\n }\n return s;\n }\n return mat;\n }\n};\n``` | 8 | 0 | ['Python', 'C++', 'Java'] | 4 |
reshape-the-matrix | ✔️ C++ solution | c-solution-by-coding_menance-9fea | Time complexity: O(rc) where r & c are the given variables for new matrix\n\nSpace complexity: O(rc) as we have a matric of size r*c to return\n\nThis my soluti | coding_menance | NORMAL | 2022-10-30T08:11:33.798089+00:00 | 2022-10-30T08:11:33.798113+00:00 | 995 | false | **Time complexity**: $$O(rc)$$ where r & c are the given variables for new matrix\n\n**Space complexity**: $$O(rc)$$ as we have a matric of size r*c to return\n\nThis my solution for the question:\n\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int r0 = mat.size(), c0 = mat[0].size();\n if (r0*c0 != r*c) return mat;\n\n vector<int> v0(c);\n vector<vector<int>> v(r, v0);\n\n // this is a approach to reduce the no of lines of code\n // as i iterates through 0 to r*c, dividing i by column would get you the row number\n // and the remainder would give you the current column number\n for (int i=0; i<r0*c0; ++i) {\n v[i/c][i%c] = mat[i/c0][i%c0];\n }\n\n return v;\n }\n};\n```\n\n## Upvote the solution if it helped you! Happy coding :) | 8 | 0 | ['C++'] | 0 |
reshape-the-matrix | ✅O(M*N) || Single For loop || Easy-understanding | omn-single-for-loop-easy-understanding-b-u4q4 | \nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total | Arpit507 | NORMAL | 2022-10-07T09:50:26.160843+00:00 | 2022-10-16T07:17:59.334089+00:00 | 1,288 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = size(mat), n = size(mat[0]), total = m * n;\n if(r * c != total) return mat;\n vector<vector<int>> ans(r, vector<int>(c));\n for(int i = 0; i < total; i++) \n ans[i / c][i % c] = mat[i / n][i % n];\n return ans;\n }\n};\n``` | 8 | 0 | ['C', 'Matrix'] | 1 |
reshape-the-matrix | JavaScript Two Pointer - Easy To Read (Notes) | javascript-two-pointer-easy-to-read-note-3jdu | \nvar matrixReshape = function(mat, r, c) {\n const result = [];\n \n // Detect if the matrices can\'t map\n if (r * c !== mat.length * mat[0].lengt | ashblue | NORMAL | 2021-12-17T06:19:59.565831+00:00 | 2021-12-17T06:19:59.565861+00:00 | 801 | false | ```\nvar matrixReshape = function(mat, r, c) {\n const result = [];\n \n // Detect if the matrices can\'t map\n if (r * c !== mat.length * mat[0].length) return mat;\n \n // Create pointers to track the original matrix\n let pR = 0;\n let pC = 0;\n \n for (let row = 0; row < r; row++) {\n // Build a row to store the columns\n const target = [];\n result.push(target);\n \n for (let col = 0; col < c; col++) {\n // Push the new column\n target.push(mat[pR][pC]);\n \n // Update the pointer to look at the next matrix item\n pC++;\n \n // If we\'ve hit undefined we\'re overflowing, move to the next row and reset the columns\n if (mat[pR][pC] === undefined) {\n pR++;\n pC = 0;\n }\n }\n }\n \n return result;\n};\n``` | 8 | 0 | ['Two Pointers', 'JavaScript'] | 0 |
reshape-the-matrix | Short simple C++ solution with explanation | short-simple-c-solution-with-explanation-htoz | Time Complexity: O(m x n), where m is no of rows, n is no of columns in inital matrix\nSpace Complexity: O(1)\n\nIntution: Consider a 2D matrix arr of size m x | mayank01ms | NORMAL | 2021-09-20T13:51:28.246699+00:00 | 2021-09-20T13:51:50.960649+00:00 | 292 | false | **Time Complexity:** O(m x n), where m is no of rows, n is no of columns in inital matrix\n**Space Complexity:** O(1)\n\n**Intution:** Consider a 2D matrix arr of size m x n, and a counter, let\'s say **t** to count the elements linearly and using it we can visualise this 2D matrix as 1D matrix. Now to convert it back to 2D matrix (which will be the solution) we can use this formula:\n\n**arr[i][j]** = **arr[t/no_of_columns][t%no_of_columns]**, where i, j points to particular valid index\n\nand it will map to the required index in the solution matirx. Try with 3-4 2D matrix of different sizes and it will become more clear.\n\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n// count of rows & columns of initial matrix \n int m = mat.size(), n = mat[0].size();\n \n// Checking if matrix can be reshaped or not\n if ((m*n) != (r*c)) return mat;\n \n// pointer to insert values in the new / reshaped matrix\n int t = 0;\n \n// vector to store the new matrix\n vector<vector<int>> res(r, vector<int> (c)); \n \n for(int i = 0; i < m; i++){\n for(int j = 0; j < n; j++){\n res[t/c][t%c] = mat[i][j];\n t++;\n }\n }\n return res;\n }\n};\n```\n\nIf you liked the solution, please consider upvoting. | 8 | 0 | ['Array', 'C'] | 1 |
reshape-the-matrix | Rust: 4ms | rust-4ms-by-seandewar-gk0m | rust\nimpl Solution {\n pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {\n let (r, c) = (r as usize, c as usize);\n | seandewar | NORMAL | 2021-07-05T10:31:34.567827+00:00 | 2021-07-05T10:34:31.564479+00:00 | 287 | false | ```rust\nimpl Solution {\n pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {\n let (r, c) = (r as usize, c as usize);\n let (m, n) = (mat.len(), mat[0].len());\n if r * c != m * n {\n mat\n } else {\n mat.iter()\n .flat_map(|r| r.iter().copied())\n .collect::<Vec<_>>()\n .chunks(c)\n .map(|r| r.to_vec())\n .collect()\n }\n }\n}\n``` | 8 | 0 | ['Rust'] | 0 |
reshape-the-matrix | Java || Matrix || 0ms || beats 100% || T.C - O(m*n) S.C - O(m*n) | java-matrix-0ms-beats-100-tc-omn-sc-omn-u3gnj | \n\n\t// O(mn) O(mn)\n\tpublic int[][] matrixReshape(int[][] mat, int r, int c) {\n\n\t\tint m = mat.length, n = mat[0].length;\n\t\tif (m * n != r * c)\n\t\t\t | LegendaryCoder | NORMAL | 2021-07-05T08:10:32.341173+00:00 | 2021-07-05T08:10:32.341226+00:00 | 343 | false | \n\n\t// O(m*n) O(m*n)\n\tpublic int[][] matrixReshape(int[][] mat, int r, int c) {\n\n\t\tint m = mat.length, n = mat[0].length;\n\t\tif (m * n != r * c)\n\t\t\treturn mat;\n\n\t\tint[][] ans = new int[r][c];\n\t\tint x = 0, y = 0;\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tans[x][y] = mat[i][j];\n\t\t\t\ty++;\n\t\t\t\tif (y == c) {\n\t\t\t\t\tx++;\n\t\t\t\t\ty = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn ans;\n\t} | 8 | 3 | [] | 0 |
reshape-the-matrix | C++ || 98.54% solution | c-9854-solution-by-anonymous_kumar-sw8k | Runtime: 16 ms, faster than 98.54% of C++ online submissions for Reshape the Matrix.\nMemory Usage: 11.3 MB, less than 77.01% of C++ online submissions for Resh | anonymous_kumar | NORMAL | 2020-06-26T19:24:38.238994+00:00 | 2020-06-26T19:24:38.239106+00:00 | 726 | false | ***Runtime: 16 ms, faster than 98.54% of C++ online submissions for Reshape the Matrix.\nMemory Usage: 11.3 MB, less than 77.01% of C++ online submissions for Reshape the Matrix.***\n\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int rows = nums.size();\n int cols = nums[0].size();\n if(rows * cols != r * c || ( rows == r && cols == c)){\n return nums;\n }\n vector<vector<int>> result(r,vector<int>(c,0));\n int current = 0;\n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n int x = current / cols;\n int y = current % cols;\n result[i][j] = nums[x][y];\n current ++;\n }\n }\n return result;\n }\n};\n```\n\n | 8 | 0 | ['C', 'C++'] | 0 |
reshape-the-matrix | ✅[C#][Go] Detailed Explanation✅ | cgo-detailed-explanation-by-shukhratutab-qhgd | Get the number of rows n and columns m of the input matrix mat.\nCheck if n * m is equal to the number of elements in the new matrix, i.e., r * c. If they are n | shukhratutaboev | NORMAL | 2023-04-13T05:59:59.109003+00:00 | 2023-04-13T05:59:59.109042+00:00 | 428 | false | Get the number of rows n and columns m of the input matrix mat.\nCheck if `n * m` is equal to the number of elements in the new matrix, i.e., `r * c`. If they are not equal, return the original matrix mat.\nCreate a new matrix arr of dimensions `r x c` using a nested for loop.\nIterate over the elements of mat using a nested for loop and fill in the elements of arr in row-major order. To do this, use the formula `l = i * m + j` to calculate the linear index of each element in mat, and the formula `arr[l / c][l % c] = mat[i][j]` to assign the element to the appropriate position in arr.\nReturn the reshaped matrix arr.\n\n# Complexity\n- Time complexity: $$O(r * c)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(r * c)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n##### Go\n```\nfunc matrixReshape(mat [][]int, r int, c int) [][]int {\n\tn := len(mat)\n\tm := len(mat[0])\n\tif m * n != r * c {\n\t\treturn mat\n\t}\n\tarr := make([][]int, r)\n\tfor i := 0; i < r; i++ {\n\t\tarr[i] = make([]int, c)\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tfor j := 0; j < m; j++ {\n\t\t\tl := i*m + j\n\t\t\tarr[l/c][l%c] = mat[i][j]\n\t\t}\n\t}\n\n\treturn arr\n}\n```\n##### C#\n```\npublic class Solution {\n\tpublic int[][] MatrixReshape(int[][] mat, int r, int c) {\n\t\tint n = mat.Length;\n\t\tint m = mat[0].Length;\n\t\t\n\t\tif (m * n != r * c) {\n\t\t\treturn mat;\n\t\t}\n\t\t\n\t\tint[][] arr = new int[r][];\n\t\tfor (int i = 0; i < r; i++) {\n\t\t\tarr[i] = new int[c];\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tint l = i * m + j;\n\t\t\t\tarr[l / c][l % c] = mat[i][j];\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn arr;\n\t}\n}\n```\n | 7 | 0 | ['Array', 'Math', 'Matrix', 'Go', 'C#'] | 0 |
reshape-the-matrix | Java Solution, 0 ms, Beats 100% | java-solution-0-ms-beats-100-by-abstract-3iuf | Java Code\n\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int n = nums.length, m = nums[0].length;\n if (r * | abstractConnoisseurs | NORMAL | 2023-02-18T19:56:58.803330+00:00 | 2023-02-18T19:56:58.803366+00:00 | 1,251 | false | # Java Code\n```\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int n = nums.length, m = nums[0].length;\n if (r * c != n * m) return nums;\n int[][] res = new int[r][c];\n for (int i = 0; i < r * c; i++)\n res[i / c][i % c] = nums[i / m][i % m];\n return res;\n }\n}\n``` | 7 | 0 | ['Array', 'Matrix', 'Simulation', 'Java'] | 1 |
reshape-the-matrix | [Python] - Clean & Simple - O(m*n) Solution | python-clean-simple-omn-solution-by-yash-q8d8 | Complexity\n- Time complexity: O(mn)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(mn)\n Add your space complexity here, e.g. O(n) \n\n# | yash_visavadia | NORMAL | 2023-02-15T19:47:17.735023+00:00 | 2023-02-15T19:47:17.735059+00:00 | 2,069 | false | # Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n m = len(mat)\n n = len(mat[0])\n\n if m * n != r * c :\n return mat \n\n cnt = 0\n ans = []\n row = []\n for i in range(m):\n for j in range(n):\n row.append(mat[i][j])\n cnt+=1\n if cnt == c:\n ans.append(row)\n row = []\n cnt = 0\n return ans\n```\n## Numpy:\n```\nimport numpy as np\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n try:\n return np.reshape(mat, (r, c)).tolist()\n except:\n return mat\n``` | 7 | 0 | ['Python3'] | 0 |
reshape-the-matrix | Best python solution easy to understand!!! | best-python-solution-easy-to-understand-pqfn6 | \n# Approach\n Describe your approach to solving the problem. First we should check if it is possible to reshape the given matrix to asked one. Then we make on | Firdavs3 | NORMAL | 2023-02-10T13:35:24.697563+00:00 | 2023-02-10T13:35:24.697631+00:00 | 993 | false | \n# Approach\n<!-- Describe your approach to solving the problem. --> First we should check if it is possible to reshape the given matrix to asked one. Then we make one dimensional array from given matrix (flat). After, we add the subarrays which are defined by dividing the flat array into c, r times .\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n if r*c!=len(mat)*len(mat[0]):\n return mat\n flat,ans=[],[]\n for i in mat:\n flat+=i\n for i in range(r):\n ans+=[flat[i*c:i*c+c]]\n return ans\n \n``` | 7 | 0 | ['Python3'] | 1 |
reshape-the-matrix | [HINDI] Java - Easy to Understand (1 ms Runtime) | hindi-java-easy-to-understand-1-ms-runti-1wtm | Hindi Explanation\nPlease UpVote if you like this HINDI Explanation Happy Coding !!\n\n\n\nclass Solution {\n\n public int[][] matrixReshape(int[][] mat, int | MilindPanwar | NORMAL | 2022-08-23T07:46:08.810672+00:00 | 2022-08-23T08:37:50.238965+00:00 | 365 | false | **Hindi Explanation**\n*Please UpVote if you like this **HINDI** Explanation Happy Coding !!*\n\n\n```\nclass Solution {\n\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n int m = mat.length;\n int n = mat[0].length;\n\n if (m * n != r * c) {\n return mat; // Question mein ye rule diya hua hai 4th paragraph mein - "If the ...Otherwise, output the original matrix."\n }\n\n int[][] rc = new int[r][c];\n int row = 0; // naya variable row ke liye\n int column = 0; // naya variable column ke liye\n\n //ek simple nested "for loop", original matrix mein traverse karne ke liye\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n rc[row][column] = mat[i][j]; // value assign kardo\n\n column++;\n if (column == c) { //agar column variable row ke last column pe hai to "if" ke andar ghusjaega code\n row++; //row ko 1 se bada do taki next row ko traverse karsake hum\n column = 0; // column ko 0 set kardo taki nayi row ke 0 index se shuru ho naya traversal\n }\n }\n }\n return rc; // return kardo apna "rc" naam ka array\n }\n}\n//badhai ho aapne successfully ye code karlia hai, Jai Mata Di...\n\n```\n | 7 | 0 | ['Java'] | 2 |
reshape-the-matrix | EASY PYTHON SOLUTION || FAST ||✔✔ || beginner friendly | easy-python-solution-fast-beginner-frien-f4bc | Given a matrix mat of 3 rows * 4 columns,\nwe want reshape it into 2 rows (r = 2) * 6 columns(c = 6):\n\n\n[[0, 1, 2, 3],\n [4, 5, 6, 7], | adithya_s_k | NORMAL | 2022-07-28T17:16:49.413155+00:00 | 2022-07-28T17:16:49.413189+00:00 | 949 | false | **Given a matrix mat of 3 rows * 4 columns,**\nwe want reshape it into 2 rows (r = 2) * 6 columns(c = 6):\n\n```\n[[0, 1, 2, 3],\n [4, 5, 6, 7], -> [[0, 1, 2, 3, 4, 5],\n [8, 9, 10, 11]] [6, 7, 8, 9, 10, 11]]\n```\nStep 1: Flatten the given matrix mat to a 1-D list flatten for easier visualizations and calculations for future steps\n\n`flatten = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]`\nStep 2: Check whether the total number of given elements len(flatten) and the new shape r * c matches (i.e. whether "given parameters is possible and legal")\n```\n\nr = 2, c = 6\nr * c = 12\n```\nStep 3: Rearrange all elements in 1-D list flatten into the new_mat according to given number of row r and given number of columns c\n\n`flatten = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]`\nreshaping:\n\n\t\t\t\t [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n```\nrow_index: 0\t\t\t| c0 c1 c2 c3 c4 c5 |\nrow_index: 1 \t\t\t | c0 c1 c2 c3 c4 c5 |\n\nindex in flatten: [row_index * c : row_index * c + c])\n\n\t\t\t [0*6 : 0*6 + 6], \n\t\t\t\t\t\t\t\t\t\t [1*6 : 1*6+6]\n\t\t\t\t\t\t\t\t\t\t\t\t \n [0 : 6], \n\t\t\t\t\t\t\t\t\t\t [6 : 12]\niteration 0:row_index 0\nflatten[0 : 6] -> [0, 1, 2, 3, 4, 5]\n\nappending:\nnew_mat = [[0, 1, 2, 3, 4, 5]]\niteration 1: row_index 1\nflatten[6 : 12] -> [6, 7, 8, 9, 10, 11]\n\nappending:\nnew_mat = [[0, 1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10, 11]]\n```\n\n**Final Solution**\n\n```\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n flatten = []\n new_mat = []\n for row in mat:\n for num in row:\n flatten.append(num)\n \n if r * c != len(flatten): # when given parameters is NOT possible and legal\n return mat\n else:\n for row_index in range(r):\n new_mat.append(flatten[row_index * c : row_index * c + c])\n return new_mat\n```\n\n\n\nAs a beginner, I am writing these all out to help myself, and hopefully also help anyone out there who is like me at the same time.\n\nPlease upvote\u2B06\uFE0F if you find this helpful or worth-reading for beginners in anyway.\nYour upvote is much more than just supportive to me. \uD83D\uDE33\uD83E\uDD13\uD83E\uDD70\n\nIf you find this is not helpful, needs improvement, or is questionable, would you please leave a quick comment below to point out the problem before you decide to downvote? It will be very helpful for me (maybe also others) to learn as a beginner.\n\nThank you very much either way \uD83E\uDD13. | 7 | 1 | ['Matrix', 'Python', 'Python3'] | 2 |
reshape-the-matrix | Java - new solution using streams | java-new-solution-using-streams-by-asawa-bnaz | \nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int n = nums.length;\n int m = nums[0].length;\n if(r* | asawas | NORMAL | 2020-01-31T04:06:56.906603+00:00 | 2020-01-31T04:06:56.906638+00:00 | 512 | false | ```\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int n = nums.length;\n int m = nums[0].length;\n if(r*c != n*m || r == n) return nums;\n int[][] res = new int[r][c];\n \n\t\tAtomicInteger ai = new AtomicInteger();\n\t\tArrays.stream(nums)\n\t\t\t\t.flatMapToInt(Arrays::stream)\n\t\t\t\t.forEach(x -> res[ ai.get() / c ][ ai.getAndIncrement() % c ] = x);\n return res;\n }\n}\n``` | 7 | 1 | ['Java'] | 1 |
reshape-the-matrix | Java. Arrays. Matrix reshape | java-arrays-matrix-reshape-by-red_planet-6oei | \n\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if (mat.length * mat[0].length != r * c)\n return mat;\n | red_planet | NORMAL | 2023-04-27T12:34:42.242417+00:00 | 2023-04-27T12:34:42.242449+00:00 | 1,443 | false | \n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if (mat.length * mat[0].length != r * c)\n return mat;\n int[][] answ = new int[r][c];\n for(int i = 0; i < r * c; i++)\n answ[i / c][i % c] = mat[i / mat[0].length][i % mat[0].length];\n return answ;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
reshape-the-matrix | Beats 100%|| 1 ms || easy Java Solution | beats-100-1-ms-easy-java-solution-by-amm-xb9i | *mat [ index / no. of column ] [ index % no. of column ]* for both the input and output matrix can be used to insert element \n\nclass Solution {\n public in | ammar_saquib | NORMAL | 2023-03-18T17:29:18.406354+00:00 | 2023-03-18T17:29:18.406398+00:00 | 941 | false | ****mat [ index / no. of column ] [ index % no. of column ]**** for both the input and output matrix can be used to insert element \n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n int m=mat.length;\n int n=mat[0].length;\n if(r*c!=m*n)\n return mat;\n int [][] ans=new int[r][c];\n for(int i=0;i<r*c;i++)\n ans[i/c][i%c]=mat[i/n][i%n];\n return ans;\n }\n}\n``` | 6 | 0 | ['Java'] | 1 |
reshape-the-matrix | 566: Solution with step by step explanation | 566-solution-with-step-by-step-explanati-y89l | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. First, check if it is possible to reshape the matrix by comparing the | Marlen09 | NORMAL | 2023-03-15T05:24:13.057138+00:00 | 2023-03-15T05:24:13.057195+00:00 | 1,100 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First, check if it is possible to reshape the matrix by comparing the product of the number of rows and columns of the original matrix with the product of the number of rows and columns of the desired reshaped matrix. If they are not equal, return the original matrix.\n2. Create a new matrix of size r x c using nested list comprehension.\n3. Traverse the original matrix in row-major order using a single index that starts at 0.\n4. For each element in the new matrix, calculate its row and column indices in the original matrix using integer division and modulo operations on the index, and then fill in the corresponding value from the original matrix.\n5. Increment the index by 1 for each iteration.\n6. Return the new matrix.\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 matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n # Check if it is possible to reshape the matrix\n m, n = len(mat), len(mat[0])\n if m * n != r * c:\n return mat\n \n # Create a new matrix of size r x c\n new_mat = [[0] * c for _ in range(r)]\n \n # Traverse the original matrix in row-major order\n index = 0\n for i in range(r):\n for j in range(c):\n # Fill in the values of the new matrix\n row, col = divmod(index, n)\n new_mat[i][j] = mat[row][col]\n index += 1\n \n return new_mat\n\n``` | 6 | 0 | ['Array', 'Matrix', 'Simulation', 'Python', 'Python3'] | 0 |
reshape-the-matrix | Easy Solution Java in Single for loop: | easy-solution-java-in-single-for-loop-by-v1rm | 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 | Mr_Daker | NORMAL | 2023-02-02T15:45:46.974562+00:00 | 2023-02-02T15:45:46.974603+00:00 | 1,532 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(r*c)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(r*c)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if(mat.length * mat[0].length != r*c){\n return mat;\n }\n \n int rshape[][] = new int [r][c];\n \n for (int i = 0;\n i < c*r; i++) {\n \n\n int row1 = i / mat[0].length;\n int col1 = i % mat[0].length;\n int row2 = i / c;\n int col2 = i % c;\n\n rshape[row2][col2] = mat[row1][col1];\n \n }\n \n return rshape;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
reshape-the-matrix | Java Simple solution with 100% | java-simple-solution-with-100-by-bunjon-8uax | Code\n\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if (mat.length * mat[0].length != r * c) return mat;\n\n | bunjon | NORMAL | 2023-01-13T04:14:16.537853+00:00 | 2023-01-13T04:14:16.537899+00:00 | 805 | false | # Code\n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if (mat.length * mat[0].length != r * c) return mat;\n\n int[][] arr = new int[r][c];\n int k = 0, l = 0;\n for (int i = 0; i < mat.length; i++) {\n for (int j = 0; j < mat[i].length; j++) {\n arr[k][l] = mat[i][j];\n l++;\n if (l == c) {\n l = 0;\n k++;\n }\n }\n }\n\n return arr;\n }\n}\n``` | 6 | 0 | ['Java'] | 2 |
reshape-the-matrix | Simple Java Solution with 100% Faster | simple-java-solution-with-100-faster-by-24p3g | \n\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if(mat.length * mat[0].length != r*c){\n return mat;\n | Sarthak_Singh_ | NORMAL | 2022-12-30T16:53:57.461931+00:00 | 2022-12-30T16:53:57.461996+00:00 | 1,850 | false | \n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if(mat.length * mat[0].length != r*c){\n return mat;\n }\n int[][] newMatrix= new int[r][c];\n int sr = 0;\n int sc = 0;\n\n for(int i=0;i<mat.length;i++){\n for(int j=0 ; j<mat[0].length;j++){\n if(sc==c){\n sr++;\n sc=0;\n }\n newMatrix[sr][sc] = mat[i][j];\n sc++;\n }\n }\n return newMatrix;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
reshape-the-matrix | C++ Solution | c-solution-by-pranto1209-yb3q | Code\n\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size(), n = nums[0].si | pranto1209 | NORMAL | 2022-12-23T06:15:47.377673+00:00 | 2023-03-14T08:09:55.691285+00:00 | 1,399 | false | # Code\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size(), n = nums[0].size();\n if(m * n != r * c) return nums;\n vector<vector<int>> ans(r, vector<int>(c));\n int row = 0, col = 0;\n for(int i = 0; i < r; i++) {\n for(int j = 0; j < c; j++) {\n ans[i][j] = nums[row][col++];\n if(col == n) col = 0, row++;\n }\n }\n return ans;\n }\n};\n``` | 6 | 0 | ['C++'] | 1 |
reshape-the-matrix | Reshape the Matrix | Python Solution | reshape-the-matrix-python-solution-by-no-1w1p | \nclass Solution:\n def matrixReshape(self, mat, r, c):\n rows=len(mat)\n cols=len(mat[0])\n newMat=[]\n val=0\n if rows*c | noob_coder_799 | NORMAL | 2022-05-31T14:17:20.272824+00:00 | 2022-05-31T14:17:20.272879+00:00 | 157 | false | ```\nclass Solution:\n def matrixReshape(self, mat, r, c):\n rows=len(mat)\n cols=len(mat[0])\n newMat=[]\n val=0\n if rows*cols!=r*c:\n return mat\n for i in range(r):\n newMat.append([])\n for _ in range(c):\n newMat[i].append(mat[val//cols][val%cols])\n val+=1\n return newMat\n``` | 6 | 0 | [] | 0 |
reshape-the-matrix | Rust | 0ms | 2.3mb | rust-0ms-23mb-by-astroex-ntz3 | Runtime: 0 ms, faster than 100.00% of Rust online submissions for Reshape the Matrix.\nMemory Usage: 2.3 MB, less than 23.40% of Rust online submissions for Res | astroex | NORMAL | 2022-01-30T21:46:36.385682+00:00 | 2022-01-30T21:47:00.455376+00:00 | 117 | false | Runtime: 0 ms, faster than 100.00% of Rust online submissions for Reshape the Matrix.\nMemory Usage: 2.3 MB, less than 23.40% of Rust online submissions for Reshape the Matrix.\n\n```\nimpl Solution {\n pub fn matrix_reshape(mut mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {\n let (row, col) = (mat.len(), mat[0].len());\n if row * col != (r * c) as usize { return mat } \n mat.concat().chunks(c as usize).map(|r| r.to_vec()).collect()\n }\n}\n``` | 6 | 0 | [] | 0 |
reshape-the-matrix | ✅ Reshape the Matrix || CPP/C++ || Implementation and Explanation | reshape-the-matrix-cppc-implementation-a-vz6k | Solution 1\n1. The simple and brute force way is to put all the matrix elements into the 1D array.\n2. Create a 2D aray of size rXc and initialize with 0 & push | thisisnitish | NORMAL | 2021-07-05T14:32:31.847236+00:00 | 2021-10-15T19:14:26.901227+00:00 | 316 | false | **Solution 1**\n1. The simple and brute force way is to put all the matrix elements into the 1D array.\n2. Create a 2D aray of size rXc and initialize with 0 & push all the elements of 1D array\ninto the new matrix\n* And, by the way the base condition is something very intuitive. Just think about for a sec.\nif `m*n != r*c` then it is clear that new matrix can\'t accommodate all elements, so just\nreturn the same matrix otherwise calculate the calculate the new one.\n```\nclass Solution {\npublic:\n //Time: O(mxn + rxc), Space: O(sizeof(oneDArray) + rxc)\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = mat.size();\n int n = mat[0].size();\n\n //base condition\n if(m*n != r*c) return mat;\n \n //convert the matrix to 1d array\n vector<int> oneDArray;\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n oneDArray.push_back(mat[i][j]);\n }\n }\n \n //put all the elements from 1d array to new matrix\n vector<vector<int>> newMatrix(r, vector<int>(c, 0));\n int idx=0;\n for(int i=0; i<r; i++){\n for(int j=0; j<c; j++){\n newMatrix[i][j] = oneDArray[idx];\n idx++;\n }\n }\n return newMatrix;\n }\n};\n```\n\n**Solution 2**\nAnother method is like one pass of the current matrix, and create new matrix initialize with \n0, put the previous elements into the new matrix according to the rxc dimension.\nRemember the base condition from the previous solution, we need to apply here also.\n```\nclass Solution {\npublic:\n //Time: O(mxn), Space: O(rxc)\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = mat.size();\n int n = mat[0].size();\n \n //base condition\n if(m*n != r*c) return mat;\n \n //creating the new matrix with rxc dimension\n vector<vector<int>> newMatrix(r, vector<int>(c, 0));\n \n //put all the elements to the new matrix\n int newRow = 0, newColumn = 0;\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n \n //if newColumn is equal to the c then increase the newRow by 1 and set \n //newColumn to 0\n if(newColumn == c){\n newRow++;\n newColumn = 0;\n }\n newMatrix[newRow][newColumn] = mat[i][j];\n newColumn++;\n }\n }\n return newMatrix;\n }\n};\n``` | 6 | 0 | ['Array', 'C', 'C++'] | 1 |
reshape-the-matrix | C++ Clean Solution | c-clean-solution-by-pranshul2112-2eyd | \nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size();\n if (m == 0) | pranshul2112 | NORMAL | 2020-10-15T06:54:47.204226+00:00 | 2020-10-15T06:54:47.204271+00:00 | 635 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n int m = nums.size();\n if (m == 0){\n return nums;\n }\n \n int n = nums[0].size();\n \n if (m * n != r * c) return nums;\n \n \n vector<vector<int>> res (r, vector<int> (c));\n \n int row = 0, col = 0;\n for (int i = 0; i < m; i++){\n for (int j = 0; j < n; j++){\n res[row][col] = nums[i][j];\n col += 1;\n \n \n if (col == c){\n row += 1;\n col = 0;\n }\n }\n \n }\n \n return res;\n }\n};\n```\n | 6 | 1 | ['C', 'C++'] | 2 |
reshape-the-matrix | Best Solution in JAVA beats 100% JAVA solutions in RUN TIME ✅✅ | best-solution-in-java-beats-100-java-sol-7pus | Intuition\n Describe your first thoughts on how to solve this problem. \nCheck if the matrix can fit in new matrix or not and copy elements to the new one. \n# | ErAdityaAkash | NORMAL | 2023-07-15T10:17:35.504627+00:00 | 2023-07-15T10:17:35.504648+00:00 | 273 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck if the matrix can fit in new matrix or not and copy elements to the new one. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Check if the matrix can fit in new matrix if true copy elements to the new one. Else return old one.\n2. Make two new variable x,y to be used as index of new matrix.\n3. Run nested for loop for coping data from the old matrix and paste it in new matrix using the variables x,y.\n4. For indexing of new variable use \n5. y++;\n if(y == c){\n y = 0;\n x++;\n }\nIf you Understand the Solution\'s Approch do Upvote \uD83D\uDE4F\uD83C\uDFFB\uD83D\uDE4F\uD83C\uDFFB\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(m * n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(r * c)\n# Code\n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n int m = mat.length;\n int n = mat[0].length;\n\n if(m*n != r*c){\n return mat;\n } \n \n \n\n int x = 0;\n int y = 0;\n int res[][] = new int[r][c];\n for(int i = 0; i < m; i++){\n for(int j = 0; j < n; j++){\n res[x][y] = mat[i][j];\n y++;\n if(y == c){\n y = 0;\n x++;\n }\n }\n }\n return res;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
reshape-the-matrix | c++ solution | With explanation | c-solution-with-explanation-by-harshil_s-agsd | Here, it states that the matrix should remain constant if the sizes of r and c differ from the original matrix.As a result, we can create a base case that uses | harshil_sutariya | NORMAL | 2023-04-20T14:09:57.451632+00:00 | 2023-04-20T14:09:57.451670+00:00 | 841 | false | Here, it states that the matrix should remain constant if the sizes of r and c differ from the original matrix.As a result, we can create a base case that uses multiplication to verify that the real matrix size matches the specified size in this instance.\n\nHere, we create a new matrix with size r*c, and we create two variables, k (row) and l (coloum), for iterating in the matrix. Here, we also need to check if the l reach the last element of the first row, in which case we need to initialise l with 0 to indicate the first coloum and increment k++ to indicate the second raw so that this type of logic can easily create new matrix.\n\n\n**Complexity**\n\nTime complexity: O(N)\n\nSpace complexity: O(1)\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n if(mat.size()* mat[0].size()!= r * c) {\n return mat;\n } \n vector<vector<int>>v(r,vector<int>(c));\n int k = 0;\n int l = 0;\n\n for(int i = 0; i < mat.size(); i++) {\n for(int j = 0; j < mat[0].size(); j++) {\n if(l == v[0].size()) {\n l = 0;\n k++;\n }\n\n v[k][l++] = mat[i][j];\n }\n }\n return v;\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
reshape-the-matrix | Solution | solution-by-deleted_user-nibi | C++ []\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int row = mat.size();\n int c | deleted_user | NORMAL | 2023-04-11T14:26:39.602045+00:00 | 2023-04-11T15:26:54.293623+00:00 | 863 | false | ```C++ []\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int row = mat.size();\n int col = mat[0].size();\n if (row * col != r * c) return mat;\n \n vector<vector<int>> result;\n int index = c;\n for (int i = 0; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (index == c) {\n result.push_back({});\n index = 0;\n }\n result[result.size() - 1].push_back(mat[i][j]);\n index += 1;\n }\n }\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n\n m=len(mat)\n n=len(mat[0])\n if m*n != r*c:\n return mat\n flat=[]\n for i in mat:\n flat.extend(i)\n \n output=[]\n for i in range(r):\n output.append(flat[i*c:(i+1)*c])\n return output\n```\n\n```Java []\nclass Solution {\n public int[][] matrixReshape(int[][] nums, int r, int c) {\n int n = nums.length, m = nums[0].length;\n if (r * c != n * m) return nums;\n int[][] res = new int[r][c];\n for (int i = 0; i < r * c; i++)\n res[i / c][i % c] = nums[i / m][i % m];\n return res;\n }\n}\n```\n | 5 | 0 | ['C++', 'Java', 'Python3'] | 2 |
reshape-the-matrix | Simple Java Solution with 0ms runtime || Beats 100% 🔥 | simple-java-solution-with-0ms-runtime-be-176o | Stats\n- RunTime: 0ms (Beats 100%)\n\n# Code\npublic int[][] matrixReshape(int[][] mat, int r, int c) {\n int rows = mat.length, cols = mat[0].length;\n\n | Abhinav-Bhardwaj | NORMAL | 2023-02-27T04:45:27.730071+00:00 | 2023-04-12T19:31:53.090725+00:00 | 1,443 | false | # Stats\n- **RunTime**: *0ms* (**Beats 100%**)\n\n# Code\npublic int[][] matrixReshape(int[][] mat, int r, int c) {\n int rows = mat.length, cols = mat[0].length;\n\n if((r == rows && c == cols) || (rows * cols != r * c)) {\n return mat;\n }\n\n int newMat [][] = new int [r][c], rIndex = 0, cIndex = 0;\n\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if(cIndex == c) {\n rIndex++;\n cIndex = 0;\n }\n\n newMat[rIndex][cIndex++] = mat[row][col];\n }\n }\n\n return newMat;\n}\n```\n<br/>\n<br/>\n<br/>\n\nAuthor :- [*Abhinav Bhardwaj*](https://abhinavbhardwaj.in) | 5 | 0 | ['Java'] | 1 |
reshape-the-matrix | Memory beats 95.4% of Java | memory-beats-954-of-java-by-satorugodjo-ovp0 | 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 | SatoruGodjo | NORMAL | 2023-01-21T09:03:10.737487+00:00 | 2023-01-21T09:03:10.737575+00:00 | 786 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n if (r * c != mat.length * mat[0].length){\n return mat;\n }\n int ans[][] = new int[r][c];\n ArrayList<Integer> arr = new ArrayList<>();\n for (int[] i: mat){\n for (int j: i){\n arr.add(j);\n }\n }\n int a = 0;\n for (int i = 0; i < r; i++){\n for (int j = 0; j < c; j++){\n ans[i][j] = arr.get(a);\n a++;\n }\n }\n return ans;\n }\n}\n``` | 5 | 0 | ['Java'] | 2 |
reshape-the-matrix | java modulo arthimatic | java-modulo-arthimatic-by-ansharya-p1ad | 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 | ansharya | NORMAL | 2022-12-20T09:58:09.273070+00:00 | 2022-12-20T09:58:09.273106+00:00 | 597 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n int n = mat.length , m = mat[0].length;\n int arr[][] = new int[r][c];\n if(m*n != r*c) return mat;\n for(int i = 0; i < c*r; i++){\n arr[i/c][i%c] = mat[i/m][i%m];\n }\n return arr;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
reshape-the-matrix | 3ms simple solution | 3ms-simple-solution-by-corejake609-0deb | Runtime: 3 ms, faster than 91.95% of Rust online submissions for Reshape the Matrix.\nMemory Usage: 2.4 MB, less than 32.18% of Rust online submissions for Resh | corejake609 | NORMAL | 2022-06-14T13:41:04.791732+00:00 | 2022-06-14T13:41:04.791773+00:00 | 189 | false | Runtime: 3 ms, faster than 91.95% of Rust online submissions for Reshape the Matrix.\nMemory Usage: 2.4 MB, less than 32.18% of Rust online submissions for Reshape the Matrix.\n```\nimpl Solution {\n pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {\n if (r*c) as usize != mat.len()*mat[0].len(){\n mat //illegal matrix return\n } else{\n mat\n .concat() //combine\n .chunks(c as usize) //devide\n .map(|row| row.to_vec())\n .collect() //restructure\n }\n }\n}\n`` | 5 | 0 | ['Rust'] | 0 |
reshape-the-matrix | Easy Solution Using C++ | easy-solution-using-c-by-kamboj_935-i5e1 | ```\nclass Solution {\npublic:\n vector> matrixReshape(vector>& mat, int r, int c) {\n vectormatri;\n int m=mat.size(), n=mat[0].size();\n\t\t | kamboj_935 | NORMAL | 2022-04-01T06:19:21.389167+00:00 | 2022-04-01T06:19:21.389193+00:00 | 196 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n vector<int>matri;\n int m=mat.size(), n=mat[0].size();\n\t\t if(r*c !=m*n){\n return mat;\n }\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n matri.push_back(mat[i][j]);\n }\n }\n \n vector<vector<int>>ans(r, vector<int>(c,0));\n int k=0;\n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n ans[i][j]=matri[k];\n k++;\n }\n }\n return ans;\n }\n};\n//If the solution helped you then dont forget to upvote!! | 5 | 0 | ['C'] | 0 |
reshape-the-matrix | C++ easy implementation | c-easy-implementation-by-tejas702-u449 | \nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n vector<vector<int>> vc(r,vector<int>(c));\ | tejas702 | NORMAL | 2021-07-05T13:11:26.557319+00:00 | 2021-07-05T13:11:26.557357+00:00 | 242 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n vector<vector<int>> vc(r,vector<int>(c));\n if((r*c)!=(mat.size()*mat[0].size())) return mat;\n vector<int> y;\n for(int p=0;p<mat.size();p++){\n for(int q=0;q<mat[0].size();q++){\n y.push_back(mat[p][q]);\n }\n } \n auto it = y.begin();\n for(int i=0;i<r;i++){\n for(int j = 0;j<c;j++){\n vc[i][j]=*it;\n it++;\n }\n }\n return vc;\n }\n};\n``` | 5 | 2 | ['C', 'Iterator'] | 0 |
reshape-the-matrix | [C++] Simple 2 Pointer Solution Explained, ~100% Time, ~95% Space | c-simple-2-pointer-solution-explained-10-jv0n | Nice warm up for the week, this is a nice problem to solve in one simple go.\n\nFirst of all, we are going create a few support variables:\n mr and mc will stor | ajna | NORMAL | 2021-07-05T10:07:21.490319+00:00 | 2021-07-05T10:07:21.490357+00:00 | 406 | false | Nice warm up for the week, this is a nice problem to solve in one simple go.\n\nFirst of all, we are going create a few support variables:\n* `mr` and `mc` will store the number of rows and columns in the provided matrix;\n* `nx` and `ny` are 2 pointers we will use with our newly created array.\n\nWe will then check if the calls we are getting is either illegal (ie: the total number of elements in the new matrix does not match) or if the provided coordinates are identical to the existing one - in either case returning `mat`.\n\nIf that is not the case, we will then create another variable, `res`, a vector of vectors of `r` rows and `c` columns.\n\nNext, we will populate `res` looping with `cy` and `cx` through `mat` and:\n* assigning the currently pointed value (`mat[cy][cx]`) to the matching cell in the new matrix (`res[ny][nx++]`);\n* advance `ny` and reset `nx` to `0` every time we reach the end of the row in the `res` (ie: `nx == c`).\n\nOnce done, we can return `res` :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n // support variables\n int mr = mat.size(), mc = mat[0].size(), nx = 0, ny = 0;\n // detecting illegal calls and when the new matrix has the same size\n if (mr * mc != r * c || mr == r && mc == c) return mat;\n vector<vector<int>> res(r, vector<int>(c));\n // populating ress\n for (int cy = 0; cy < mr; cy++) {\n for (int cx = 0; cx < mc; cx++) {\n res[ny][nx++] = mat[cy][cx];\n // updating nx and ny when we reached the end of a row\n if (nx == c) nx = 0, ny++;\n }\n }\n return res;\n }\n};\n``` | 5 | 0 | ['Array', 'Two Pointers', 'C', 'C++'] | 1 |
reshape-the-matrix | Reshape Matrix || C++ || python || explained solution | reshape-matrix-c-python-explained-soluti-vsmm | \n\nvector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = mat.size(), n=mat[0].size();\n if(m*n != r*c)return mat; | aynburnt | NORMAL | 2021-07-05T08:40:15.231186+00:00 | 2021-07-05T08:54:19.456766+00:00 | 81 | false | \n```\nvector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {\n int m = mat.size(), n=mat[0].size();\n if(m*n != r*c)return mat; // base case\n if(r==m)return mat; // same dimension as mat \n vector<vector<int>> ans(r);\n int tmp=0; \n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(ans[tmp].size() == c)tmp++; // if no. of element in the current row is equal to c ( required ) move to next line\n ans[tmp].push_back(mat[i][j]);\n }\n }\n return ans;\n }\n```\n\n**Python**\n```\ndef matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n m = len(mat)\n n = len(mat[0])\n if(m*n != r*c):\n return mat\n tmp = 0\n ans = [[]]\n for x in mat:\n for y in x:\n if(len(ans[tmp])==c):\n ans.append([])\n tmp += 1\n ans[tmp].append(y)\n return ans\n```\n\n**If you find it helpful plz upvote** | 5 | 5 | ['C'] | 0 |
reshape-the-matrix | Easy Python | 100% Speed | Yield Method | easy-python-100-speed-yield-method-by-ar-hc1r | Easy Python | 100% Speed | Yield Method\n\nClean Python algorithm building the output array in a very easy way :)\n\n\nclass Solution:\n def yielder(self,A): | aragorn_ | NORMAL | 2020-09-30T18:31:55.484091+00:00 | 2020-09-30T18:44:03.435637+00:00 | 801 | false | **Easy Python | 100% Speed | Yield Method**\n\nClean Python algorithm building the output array in a very easy way :)\n\n```\nclass Solution:\n def yielder(self,A):\n for row in A:\n for x in row:\n yield x\n def matrixReshape(self, A, r, c):\n if not A:\n return []\n if len(A)*len(A[0]) != r*c:\n return A\n #\n gen = self.yielder(A)\n return [ [ next(gen) for _ in range(c) ] for _ in range(r) ]\n```\n\n**PS. Circular Index Method**\n\nThe Yield Method works amazingly well in Python. However, implementing anything resembling the Yield functionality is low-level languages is very cumbersome (if at all possible). The Circular Index Method is a much cleaner algorithm compatible with all programming languages:\n```\nclass Solution:\n def matrixReshape(self, A, r, c):\n if not A:\n return []\n m,n = len(A),len(A[0])\n if m*n != r*c:\n return A\n #\n B = []\n for i in range(r):\n row = []\n for j in range(c):\n k = i*c + j\n row.append( A[k//n][k%n] )\n B.append( row )\n return B\n```\n | 5 | 0 | ['Python', 'Python3'] | 0 |
reshape-the-matrix | 3 Python sol. based on list comprehension, generator, and index transform 80%+ [ With explanation ] | 3-python-sol-based-on-list-comprehension-imo6 | 3 Python sol. based on list comprehension, generator, and index transform.\n\n---\n\nMethod_#1: based on list comprehension\n\n\nclass Solution:\n def matrix | brianchiang_tw | NORMAL | 2020-01-15T06:00:15.922344+00:00 | 2020-03-11T15:36:36.874930+00:00 | 750 | false | 3 Python sol. based on list comprehension, generator, and index transform.\n\n---\n\nMethod_#1: based on list comprehension\n\n```\nclass Solution:\n def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:\n \n ori_rows, ori_cols = len(nums), len(nums[0])\n \n if ori_rows * ori_cols != r * c or (ori_rows, ori_cols) == (r, c):\n # Quick response:\n # \n # mismatch of total number of elements\n # or\n # dimension is the same as original\n \n return nums\n \n else:\n \n # flatten nums to 1D array\n flatten_array = [ element for rows in nums for element in rows ]\n \n # construct reshape_arr by list comprehension\n reshape_arr = [ flatten_array[ y*c : y*c+c ] for y in range(r) ]\n \n return reshape_arr\n```\n\n---\n\nMethod_#2: based on generator\n\n```\nclass Solution:\n \n def element_generator( self, matrix ):\n \n rows, cols = len( matrix), len( matrix[0])\n \n for index_serial in range( rows*cols):\n y = index_serial // cols\n x = index_serial % cols\n yield matrix[y][x]\n \n \n\n \n def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:\n \n ori_rows, ori_cols = len(nums), len(nums[0])\n \n if ori_rows * ori_cols != r * c or (ori_rows, ori_cols) == (r, c):\n # Quick response:\n # mismatch of total number of elements\n # or\n # dimension is the same as original\n \n \n return nums\n \n else:\n \n \n reshape_arr = [[ 0 for x in range (c)] for y in range(r) ]\n \n element_gen = self.element_generator( nums )\n \n for y in range(r):\n for x in range(c):\n \n reshape_arr[y][x] = next(element_gen)\n \n \n return reshape_arr\n```\n\n---\n\nMethod_#3: based on index transform\n\n```\nclass Solution:\n\n def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:\n \n ori_rows, ori_cols = len(nums), len(nums[0])\n \n if ori_rows * ori_cols != r * c or (ori_rows, ori_cols) == (r, c):\n # Quick response:\n # mismatch of total number of elements\n # or\n # dimension is the same as original\n \n \n return nums\n \n else:\n \n reshape_arr = [[ 0 for x in range (c)] for y in range(r) ]\n \n for y in range(r):\n for x in range(c):\n \n # index transform\n serial_index = y * c + x\n\n src_y = serial_index // ori_cols\n src_x = serial_index % ori_cols\n \n reshape_arr[y][x] = nums[src_y][src_x]\n \n \n return reshape_arr\n``` | 5 | 0 | ['Math', 'Python', 'Python3'] | 0 |
reshape-the-matrix | C# Simple Solution | c-simple-solution-by-ashkap-corh | \npublic int[][] MatrixReshape(int[][] nums, int r, int c) {\n int curRows = nums.Length;\n int curColumns = nums[0].Length;\n \n if | ashkap | NORMAL | 2019-10-14T02:02:37.337100+00:00 | 2019-10-14T02:02:37.337135+00:00 | 766 | false | ```\npublic int[][] MatrixReshape(int[][] nums, int r, int c) {\n int curRows = nums.Length;\n int curColumns = nums[0].Length;\n \n if((curRows * curColumns) == (r * c)){\n int[][] result = new int[r][];\n \n for(int i = 0; i < r; i++) //this loop is because i cant just declare int [][] transpose = new int[m][n]... c# things\n {\n result[i] = new int[c];\n }\n int x =0, y =0;\n for(int i =0; i < r; i++){\n for(int j =0; j< c; j++){\n if((x < curRows) || (y < curColumns)){\n if(y >= curColumns){\n y = 0;\n x++; \n }\n result[i][j] = nums[x][y++];\n } \n }\n }\n return result; \n }\n \n return nums;\n \n }\n``` | 5 | 0 | [] | 1 |
reshape-the-matrix | javascript | javascript-by-yinchuhui88-tu46 | \nvar matrixReshape = function(nums, r, c) {\n const r0 = nums.length, c0 = nums[0].length, result = [];\n if(r * c != r0 * c0) {\n return nums;\n | yinchuhui88 | NORMAL | 2018-11-11T03:55:18.209346+00:00 | 2018-11-11T03:55:18.209389+00:00 | 566 | false | ```\nvar matrixReshape = function(nums, r, c) {\n const r0 = nums.length, c0 = nums[0].length, result = [];\n if(r * c != r0 * c0) {\n return nums;\n }\n let array = [];\n for(let i = 0; i < r0; i++) {\n for(let j = 0; j < c0; j++) {\n array.push(nums[i][j]);\n }\n }\n while(array.length) {\n result.push(array.splice(0, c));\n }\n return result;\n};\n``` | 5 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.