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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
first-completely-painted-row-or-column | JAVA Solution Using (1).Array [15ms] || (2).HashMap [25ms] | java-solution-using-1array-15ms-2hashmap-5rm2 | IntuitionThe challenge is to track how many elements of each row and column have been processed efficiently. This can be achieved by mapping the elements of mat | Prem_Chandu_Palivela | NORMAL | 2025-01-20T03:06:50.900011+00:00 | 2025-01-20T03:06:50.900011+00:00 | 31 | false | # Intuition
The challenge is to track how many elements of each row and column have been processed efficiently. This can be achieved by mapping the elements of mat to their positions by using HashMap or Array.And then we traverse the array maintaining frequency arrays of rows and columns. And we return the index of arr where the frequency of that index in rows = columns length or vice versa .
# Approach
**1.Preprocessing the Matrix (mp array):**
Create a mapping mp where:
mp[val] stores the row and column indices of the value val in mat.
This allows you to directly access the position of any element in
O(1) time.
**2.Tracking Rows and Columns:**
Use rows[i] to track the count of filled cells in the i-th row.
Use cols[j] to track the count of filled cells in the j-th column.
**3.Processing the Array (arr):**
For each element in arr, find its position using the mp array.
Increment the count for the corresponding row and column.
Check if the current row or column is completely filled:
If rows[i] == m, it means the i-th row is completely filled.
If cols[j] == n, it means the j-th column is completely filled.
Return the index of the current element in arr as soon as a row or column is completed.
**4.Dummy Return:**
Return -1.
# Complexity
- Time complexity: O(n⋅m+arr.length)
- Space complexity: o(n.m)
# Using Array
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int n=mat.length;
int m=mat[0].length;
int[][] mp = new int[m*n+1][2];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
mp[mat[i][j]]=new int[]{i,j};
}
}
int[] rows = new int[n];
int[] cols = new int[m];
for(int i=0;i<arr.length;i++){
int[] pos = mp[arr[i]];
rows[pos[0]]++;
cols[pos[1]]++;
if((rows[pos[0]]==m)||(cols[pos[1]]==n)){
return i;
}
}
return -1;
}
}
```
# Using HashMap
# Complexity
- Time complexity: O(n⋅m+arr.length)
- Space complexity: o(n.m)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
```
java
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
HashMap<Integer,int[]> mp = new HashMap<>();
int n=mat.length;
int m=mat[0].length;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
mp.put(mat[i][j],new int[]{i,j});
}
}
int[] rows = new int[n];
int[] cols = new int[m];
for(int i=0;i<arr.length;i++){
int[] pos = mp.get(arr[i]);
rows[pos[0]]++;
cols[pos[1]]++;
if((rows[pos[0]]==m)||(cols[pos[1]]==n)){
return i;
}
}
return -1;
}
}
``` | 2 | 0 | ['Array', 'Hash Table', 'Java'] | 0 |
first-completely-painted-row-or-column | Simple by traversal || Easy Intuition || HashMap || TC: O(n* m + k) | simple-by-traversal-easy-intuition-hashm-yhu2 | IntuitionIn this simply we will map the indexes so that it can be easily accessible in O(1). Once we get all the index mapped we will take a counter for each co | hamza_18 | NORMAL | 2025-01-20T02:34:06.194873+00:00 | 2025-01-20T02:34:06.194873+00:00 | 16 | false | # Intuition
In this simply we will map the indexes so that it can be easily accessible in O(1). Once we get all the index mapped we will take a counter for each col and each row (1D array) and for each row and col we will keep track of the number of elements painted in the curr row or col at present. as soon as we get any row count == m or any col count == n then that row or col is full we can return that index.
# Approach
- Mapping the Numbers to Their Positions:
- - Use a map idxs to store the position (row, column) of each number in the matrix.
This allows you to find the position of any number in O(1) time
- Maintain two arrays:
- row[n]: Tracks how many elements of each row have been encountered so far.
- col[m]: Tracks how many elements of each column have been encountered so far.
Processing Numbers in arr:
- For each number in arr:
- - Find its position (x, y) in the matrix using idxs.
Increment the count of elements seen in row[x] and col[y].
Check if row[x] equals the total number of columns 𝑚
m or col[y] equals the total number of rows 𝑛
- - If true, return the current index, because either a row or a column is completely filled.
- Return Result:
- The first index where a row or column is completely filled is the answer.
# Complexity
- Time complexity:
O(n*m + k)
- Space complexity:
O(n*m)
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
unordered_map<int,pair<int,int>> idxs;
int n = mat.size();
int m = mat[0].size();
for(int i =0 ; i<n;i++){
for(int j = 0;j<m;j++){
idxs[mat[i][j]] = {i,j};
}
}
vector<int> row(n,0);
vector<int> col(m,0);
int ans;
for(int i = 0;i<arr.size();i++){
auto [x,y] = idxs[arr[i]];
row[x]++;
if(row[x] == m) {
ans = i;
break;
}
col[y]++;
if(col[y] == n){
ans = i;
break;
}
}
return ans;
}
};
``` | 2 | 0 | ['Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | Hash Map Solution | Clean Code | hash-map-solution-clean-code-by-attentio-85sm | Approacharr and mat both contain all integers in the range [1, m * n]. So we:
Use a map posMap to store every integer's position in mat.
Use two arrays rowsCnt | Attention2000 | NORMAL | 2025-01-20T01:12:35.223521+00:00 | 2025-01-20T01:12:35.223521+00:00 | 13 | false | # Approach
<!-- Describe your approach to solving the problem. -->
`arr` and `mat` both contain all integers in the range `[1, m * n]`. So we:
1. Use a map `posMap` to store every integer's position in `mat`.
2. Use two arrays `rowsCnt` and `colsCnt` to record how many cells in a row and a column are colored separately.
3. Once a row or column is colored fully, return the index `i`.
# Complexity
- Time complexity: $$O(mn)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(mn)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
unordered_map<int, pair<int, int>> posMap;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
posMap[mat[i][j]] = {i, j};
}
}
vector<int> rowsCnt(m, 0), colsCnt(n, 0);
for (int i = 0; i < m * n; ++i) {
auto [row, col] = posMap[arr[i]];
++rowsCnt[row];
++colsCnt[col];
if (rowsCnt[row] == n || colsCnt[col] == m) return i;
}
return m * n - 1;
}
};
``` | 2 | 0 | ['Hash Table', 'C++'] | 0 |
first-completely-painted-row-or-column | Python 3 solution - Easy to understand | python-3-solution-by-iloabachie-bc2h | IntuitionFirst, I created 3 dictionaries.
Dictionary with row numbers as key and count of elements in the row as values.
Dictionary with col numbers as key and | iloabachie | NORMAL | 2025-01-20T01:10:14.680403+00:00 | 2025-01-20T01:22:06.308427+00:00 | 270 | false | # Intuition
First, I created 3 dictionaries.
1. Dictionary with row numbers as key and count of elements in the row as values.
2. Dictionary with col numbers as key and count of elements in the column as values.
3. Dictionary with each number in the matrix as key and a list containing its row number and column number as values.
Dictionary 3 is created using dictionary comprehension which is the same as the code below:
```py
position = {}
for r in range(m):
for c in range(n):
position[mat[r][c]] = [r, c]
```
Next I iterated through the arr and for each number, I would get its row and column from dictionary 3 and reduce the count in dictionary's 1 and 2 by 1.
Finally I would check if any row or column count was 0 and if yes, then I would return the index of that number in the array.
# Code
```python []
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
rows = dict.fromkeys(range(m), n)
cols = dict.fromkeys(range(n), m)
position = {mat[r][c]: [r, c] for r in range(m) for c in range(n)}
for i, n in enumerate(arr):
r, c = position[n]
rows[r] -= 1
cols[c] -= 1
if not rows[r] or not cols[c]:
return i
``` | 2 | 0 | ['Python3'] | 1 |
first-completely-painted-row-or-column | Best solution in C++ . O(n*m) time and space complexity. | best-solution-in-clinear-time-and-space-f8rfp | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Shahriar22 | NORMAL | 2025-01-20T00:27:53.127821+00:00 | 2025-01-20T00:41:45.692318+00:00 | 151 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
// Map to store the position (row, col) of each value in the matrix
unordered_map<int, pair<int, int>> posMap;
int rCount = mat.size(); // Number of rows
int cCount = mat[0].size(); // Number of columns
// Populate the map with matrix values and their positions
for (int r = 0; r < rCount; r++) {
for (int c = 0; c < cCount; c++) {
posMap[mat[r][c]] = {r, c};
}
}
vector<int> colFill(cCount, 0); // Tracks filled cells in each column
vector<int> rowFill(rCount, 0); // Tracks filled cells in each row
// Iterate through the array to find the first complete row or column
for (int i = 0; i < arr.size(); i++) {
// Get the row and column of the current value
int row = posMap[arr[i]].first;
int col = posMap[arr[i]].second;
// Increment the fill counts
colFill[col]++;
rowFill[row]++;
// Check if the row or column is fully filled
if (colFill[col] == rCount || rowFill[row] == cCount) {
return i; // Return the index where the first complete row/column is found
}
}
return 0;
}
};
``` | 2 | 0 | ['C++'] | 0 |
first-completely-painted-row-or-column | Simple and clear solution. O(n*m) | simple-and-clear-solution-onm-by-xxxxkav-qijo | null | xxxxkav | NORMAL | 2025-01-20T00:17:28.977201+00:00 | 2025-01-20T00:17:50.313705+00:00 | 239 | false | ```
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
cnt_row, cnt_col = [0] * m, [0] * n
dict_mat = [0] * (m*n+1)
for i, j in product(range(m), range(n)):
dict_mat[mat[i][j]] = (i, j)
for ind, num in enumerate(arr):
i, j = dict_mat[num]
cnt_row[i] += 1
cnt_col[j] += 1
if cnt_row[i] == n or cnt_col[j] == m:
return ind
return -1
``` | 2 | 0 | ['Python3'] | 0 |
first-completely-painted-row-or-column | Simple | ✅ | simple-by-shadab_ahmad_khan-n2ta | Code\n\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n HashMap<Integer,int[]> map=new HashMap<>();\n HashMap<Inte | Shadab_Ahmad_Khan | NORMAL | 2023-12-14T09:15:23.725040+00:00 | 2023-12-14T09:15:23.725064+00:00 | 38 | false | # Code\n```\nclass Solution {\n public int firstCompleteIndex(int[] arr, int[][] mat) {\n HashMap<Integer,int[]> map=new HashMap<>();\n HashMap<Integer,Integer> row=new HashMap<>();\n HashMap<Integer,Integer> col=new HashMap<>();\n for(int i=0; i<mat.length; i++){\n for(int j=0; j<mat[0].length; j++){\n map.put(mat[i][j], new int[]{i,j});\n }\n }\n for(int i=0; i<arr.length; i++){\n int[] temp=map.get(arr[i]);\n int r=temp[0];\n int c=temp[1]; \n row.put(r, row.getOrDefault(r, 0) + 1);\n col.put(c, col.getOrDefault(c, 0) + 1);\n if(row.get(r)==mat[0].length || col.get(c)==mat.length){\n return i;\n }\n }\n return -1;\n }\n}\n```\n______________________________________\n\n# **Up Vote if Helps**\n\n______________________________________ | 2 | 0 | ['Array', 'Hash Function', 'Java'] | 0 |
first-completely-painted-row-or-column | Unordered Map , C++ ✅✅ | unordered-map-c-by-deepak_5910-mxv1 | Approach\n Describe your approach to solving the problem. \nThink brute force, but optimize brute force by tracking colored cells using a hash table.\n# Complex | Deepak_5910 | NORMAL | 2023-06-20T09:09:30.883791+00:00 | 2023-09-16T12:58:12.716006+00:00 | 50 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nThink brute force, but optimize brute force by tracking colored cells using a hash table.\n# Complexity\n- Time complexity:O(N*M)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N*M)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n int n,m;\n unordered_map<int,pair<int,int>> pos;\n unordered_map<int,int> rows,cols;\n\n bool fillup(int x,int y)\n {\n rows[x]++;\n cols[y]++;\n\n if(rows[x]>=m || cols[y]>=n)\n return true;\n\n return false;\n }\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n n = mat.size(),m = mat[0].size();\n\n for(int i = 0;i<n;i++)\n {\n for(int j = 0;j<m;j++)\n pos[mat[i][j]] = {i,j};\n }\n\n for(int i = 0;i<arr.size();i++)\n {\n int x = pos[arr[i]].first,y = pos[arr[i]].second;\n\n if(fillup(x,y))\n return i;\n }\n return 0;\n }\n};\n```\n\n | 2 | 0 | ['Hash Table', 'C++'] | 0 |
first-completely-painted-row-or-column | scala easy solution | scala-easy-solution-by-lyk4411-rw4h | 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 | lyk4411 | NORMAL | 2023-05-13T12:38:32.304819+00:00 | 2023-05-13T12:38:32.304877+00:00 | 31 | 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```\nobject Solution {\n def firstCompleteIndex(arr: Array[Int], mat: Array[Array[Int]]): Int = {\n val all = arr.zipWithIndex.toMap\n val cols = mat.map(_.map(all.getOrElse(_, Int.MaxValue)).max)\n val rows = mat.transpose.map(_.map(all.getOrElse(_, Int.MaxValue)).max)\n cols.min min rows.min\n }\n}\n``` | 2 | 0 | ['Scala'] | 0 |
first-completely-painted-row-or-column | ✅C++ || Hash Table✅ | c-hash-table-by-deepak_2311-k592 | 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 | godmode_2311 | NORMAL | 2023-04-30T07:51:18.561636+00:00 | 2023-04-30T07:59:54.807143+00:00 | 89 | false | # Complexity\n- Time complexity:`O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:`O(n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n int row_Size , col_Size;\n\n bool isFilled(vector<int>&rows,int curr_Row , vector<int>&columns , int curr_Col){\n\n if(rows[curr_Row] == col_Size || columns[curr_Col] == row_Size) return true;\n return false;\n \n }\n\n int firstCompleteIndex(vector<int>& nums, vector<vector<int>>& mat) {\n \n // length of 1D array\n int n = nums.size();\n\n\n // length of row & column in matrix\n row_Size = mat.size();\n col_Size = mat[0].size();\n \n\n // vectors for tracking row & column are filled or not\n vector<int>rows(row_Size,0);\n vector<int>columns(col_Size,0);\n \n\n // maps values with location in matrix\n unordered_map<int,pair<int,int>>mp;\n \n\n for(int i=0;i<row_Size;i++){\n for(int j=0;j<col_Size;j++){\n\n int value = mat[i][j]; // value\n pair<int,int>location = {i,j}; // location\n\n mp[value] = location; // mapping value with location\n\n }\n }\n \n\n for(int i=0;i<n;i++){\n \n int curr_Row = mp[nums[i]].first; // getting current row\n int curr_Col = mp[nums[i]].second; // getting current column\n \n rows[curr_Row]++; // filling current row \n columns[curr_Col]++; // filling current column \n \n // return index if current row or column is filled\n if(isFilled(rows,curr_Row,columns,curr_Col)) return i; \n \n }\n \n // dummy index\n return -1;\n \n }\n};\n``` | 2 | 0 | ['Array', 'Hash Table', 'Matrix', 'C++'] | 0 |
first-completely-painted-row-or-column | Map solution for C# (explanation + complexity) | map-solution-for-c-explanation-complexit-23f6 | Approach\nThe problem can be divided into two sub-problems:\n1. How to find the value in the matrix in a fast way\n2. How to understand that a row or column is | deleted_user | NORMAL | 2023-04-30T06:44:13.114444+00:00 | 2023-05-07T04:41:26.304082+00:00 | 41 | false | # Approach\nThe problem can be divided into two sub-problems:\n1. How to find the value in the matrix in a fast way\n2. How to understand that a row or column is completely painted\n\nSo,\n1. To solve the first problem, we will create a dictionary with cell values as a key and row/column indices as a value. It will cost us some space, but it allows us to get information about the cell for O(1) time.\n2. Create two arrays assigned for each rows/columns indices and increase their values during traversal of the arr array.\n\nWhen we fill a row or column, we can return the result.\n\n# Complexity\n- Time complexity: O(m*n)\n- Space complexity: O(m*n)\n\n# Code\n```\npublic int FirstCompleteIndex(int[] arr, int[][] mat)\n{\n var dict = new Dictionary<int, Tuple<int, int>>();\n\n for (var i = 0; i < mat.Length; ++i)\n {\n for (var j = 0; j < mat[i].Length; ++j)\n {\n dict.Add(mat[i][j], new Tuple<int, int>(i, j));\n }\n }\n\n if (dict.Count == 0)\n {\n return -1;\n }\n\n var rows = new int[mat.Length];\n var cols = new int[mat[0].Length];\n\n for (var i = 0; i < arr.Length; ++i)\n {\n var item = dict[arr[i]];\n\n rows[item.Item1]++;\n cols[item.Item2]++;\n if (rows[item.Item1] == mat[0].Length || cols[item.Item2] == mat.Length)\n {\n return i;\n }\n }\n\n return -1;\n}\n``` | 2 | 0 | ['C#'] | 0 |
first-completely-painted-row-or-column | C++ || Easy | c-easy-by-shrikanta8-mahs | \nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int r = mat.size(),c= mat[0].size();\n vec | Shrikanta8 | NORMAL | 2023-04-30T04:05:12.761218+00:00 | 2023-04-30T04:13:12.397418+00:00 | 93 | false | ```\nclass Solution {\npublic:\n int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n int r = mat.size(),c= mat[0].size();\n vector<pair<int,int> > ind(r*c+1);\n \n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n ind[mat[i][j]] = {i,j};\n }\n }\n \n vector<int> szRow(r),szCol(c);\n for(int i=0;i<r*c;i++){\n int num = arr[i];\n int x= ind[num].first,y=ind[num].second;\n \n szRow[x]++;\n szCol[y]++;\n if(szRow[x] == c || szCol[y] == r)\n return i;\n }\n return -1;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
first-completely-painted-row-or-column | Using HashMap by Storing the Index values || Beats 90% of Java Code | using-hashmap-by-storing-the-index-value-ycw4 | IntuitionApproachComplexity
Time complexity:O(m*n)
Space complexity: O(m*n)
Code | zeeshan312 | NORMAL | 2025-01-27T20:33:51.131955+00:00 | 2025-01-27T20:33:51.131955+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(m*n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(m*n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m=mat.length; //no of rows
int n=mat[0].length;
int[] rowCount=new int[m]; //to check whether any row
int[] colCount= new int[n];// col is equal to m|n.
HashMap<Integer,int[]>lookupMap =new HashMap<>(); // to store the index of value
for(int i=0;i<m;i++){ //storing the values in lookupMap along with index
for(int j=0;j<n;j++){
lookupMap.put(mat[i][j],new int[]{i,j});
}
}
int[]temp;
int row,col;
for(int i=0;i<arr.length;i++){
temp=lookupMap.get(arr[i]);
row=temp[0];
col=temp[1];
rowCount[row]++;
colCount[col]++;
if(rowCount[row]==n || colCount[col]==m) // a whole row will be painted when it's all col is visited
return i;
}
return -1;
}
}
``` | 1 | 0 | ['Hash Table', 'Java'] | 0 |
first-completely-painted-row-or-column | Beat 92.2% C++. O(m*n) easy solution. | beat-922-c-omn-easy-solution-by-vikasnir-9dpj | IntuitionFocus on reducing time complexity by using hash arrays.ApproachStep 1 : Create a hash vector to store the row and col of the values given in the matrix | VikasNiranjan | NORMAL | 2025-01-22T12:50:56.727087+00:00 | 2025-01-22T12:50:56.727087+00:00 | 6 | false | # Intuition
Focus on reducing time complexity by using hash arrays.
# Approach
**Step 1 :** Create a hash vector to store the row and col of the values given in the matrix to get row and col in O(1).
**Step 2 :** Create a rowHash and a colHash to count the number of cells painted in that particular row and col.
**Step3 :** Traverse the array---> find row, col using hash ---> increase the number of painted cells in the row and col.
**Step 4 :** Once the row or painted is painted return index (i).
# Complexity
- Time complexity:
$$O(m*n)$$
- Space complexity:
$$O(m*n) + O(m) + O(n)$$
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat)
{
int m = mat.size(), n = mat[0].size();
vector<pair<int,int>>hash(m*n+1,{0,0});
vector<int>rowHash(m,0) , colHash(n,0);
for(int i=0 ; i<m ; i++)
{
for(int j=0 ; j<n ; j++)
{
int val = mat[i][j];
hash[val]= {i,j};
}
}
for(int i=0; i<arr.size(); i++)
{
int val = arr[i];
int row = hash[val].first, col = hash[val].second;
rowHash[row]++, colHash[col]++;
if(rowHash[row]==n || colHash[col]==m)
{
return i;
}
}
return 0;
}
};
``` | 1 | 0 | ['Hash Table', 'C++'] | 0 |
first-completely-painted-row-or-column | ✅ 🌟 JAVA SOLUTION ||🔥 BEATS 100% PROOF🔥|| 💡 CONCISE CODE ✅ || 🧑💻 BEGINNER FRIENDLY | java-solution-beats-100-proof-concise-co-02l8 | Complexity
Time complexity:O(m * n)
Space complexity:O(m * n)
Code | Shyam_jee_ | NORMAL | 2025-01-21T18:55:22.584290+00:00 | 2025-01-21T18:55:22.584290+00:00 | 4 | false | # Complexity
- Time complexity:O(*m* * *n*)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(*m* * *n*)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
// Map to store the index of each number in the arr
Map<Integer, int[]> pos=new HashMap<>();
int n=mat.length;
int m=mat[0].length;
for(int row=0;row<n;row++)
{
for(int col=0;col<m;col++)
{
pos.put(mat[row][col], new int[]{row, col});
}
}
int[] rowCount=new int[n];
int[] colCount=new int[m];
for(int i=0;i<arr.length;i++)
{
int[] idx=pos.get(arr[i]);
int row=idx[0];
int col=idx[1];
rowCount[row]++;
colCount[col]++;
if(rowCount[row]==m || colCount[col]==n)
{
return i;
}
}
return -1;
}
}
``` | 1 | 0 | ['Array', 'Hash Table', 'Matrix', 'Java'] | 0 |
first-completely-painted-row-or-column | Easy to understand C++ approach | easy-to-understand-c-approach-by-itsme_s-r3mt | IntuitionHere our intuition is that we will have to keep track of the number of elements coloured for each row and each column so that we can figure out when a | itsme_S | NORMAL | 2025-01-21T06:04:16.208183+00:00 | 2025-01-21T06:04:16.208183+00:00 | 13 | false | # Intuition
Here our intuition is that we will have to keep track of the number of elements coloured for each row and each column so that we can figure out when a full row or column has been coloured. If we do it in a brute force way, then it will take a lot of time which we do not want. So we need to think of another approach.
# Approach
The approach begins by creating a map to store the positions of all elements in the grid (mat) as (row, column) pairs. This allows us to quickly locate an element's position without repeatedly searching through the grid. Next, we initialize two arrays, rowsele and colsele, to count how many elements have been marked in each row and column, respectively. The sizes of these arrays match the number of rows and columns in the grid. We then iterate through the array arr and, for each element, use the map to find its position in the grid. We increment the corresponding counts in rowsele and colsele and keep track of the maximum counts for any row or column. If at any point, a row or column is fully marked (i.e., the count matches the total number of columns or rows), we return the current index of arr as the result. If no row or column is fully marked by the end of the array, we return -1.
Note that here if I could have returned anything instead of -1 because that line would never have been executed. The line return -1 is included as a fallback because the function requires a return value in all cases. However, in the context of this specific problem, it will never actually be executed.
# Complexity
- Time complexity:
O(m * n)
- Space complexity:
O(m * n)
# Code
```cpp []
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int rownum = mat.size(), colnum = mat[0].size();
int rowsize = mat[0].size(), colsize = mat.size();
vector<int> rowsele(rownum, 0), colsele(colnum, 0);
unordered_map<int, pair<int, int>> mp;
for( int i = 0; i < mat.size(); i++ ){
for( int j = 0; j < mat[0].size(); j++ ){
mp[mat[i][j]] = {i, j};
}
}
int maxrow = -1, maxcol = -1;
for( int i = 0; i < arr.size(); i++ ){
int row = mp[arr[i]].first, col = mp[arr[i]].second;
rowsele[row]++;
colsele[col]++;
maxrow = max(maxrow, rowsele[row]);
maxcol = max(maxcol, colsele[col]);
if(maxrow == rowsize || maxcol == colsize){
return i;
}
}
return -1;
}
};
``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | [Java/C++/Python] Index of 1 and n | javacpython-index-of-1-and-n-by-lee215-ivn3 | Explanation\nIf index of 1 is i,\n1 needs i swaps to be the first.\n\nIf index of n is j,\nn needs n - 1 - j swaps to be the first.\n\nIf i < j,\nres is i + (n | lee215 | NORMAL | 2023-06-04T04:28:19.435006+00:00 | 2023-06-04T04:28:19.435040+00:00 | 1,931 | false | # **Explanation**\nIf index of `1` is `i`,\n`1` needs `i` swaps to be the first.\n\nIf index of `n` is `j`,\n`n` needs `n - 1 - j` swaps to be the first.\n\nIf `i < j`,\n`res` is `i + (n - 1 - j)`.\n\nIf `i > j`,\n`res` is `i + (n - 1 - j) - 1`,\nsave one swap when swap `1` and `n`.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int semiOrderedPermutation(int[] A) {\n int n = A.length, i = 0, j = 0;\n for (int k = 0; k < n; k++) {\n if (A[k] == 1) i = k;\n if (A[k] == A.length) j = k;\n }\n return i + n - 1 - j - (i > j ? 1 : 0);\n }\n```\n\n**C++**\n```cpp\n int semiOrderedPermutation(vector<int>& A) {\n int n = A.size(), i = find(A.begin(), A.end(), 1) - A.begin(), j = find(A.begin(), A.end(), n) - A.begin();\n return i + n - 1 - j - (i > j);\n }\n```\n\n**Python**\n```py\n def semiOrderedPermutation(self, A: List[int]) -> int:\n n = len(A)\n i, j = A.index(1), A.index(n)\n return i + n - 1 - j - (i > j)\n```\n | 24 | 0 | ['C', 'Python', 'Java'] | 6 |
semi-ordered-permutation | Python 3 || 2 lines, w/ brief explanation || T/S: 99% / 63% | python-3-2-lines-w-brief-explanation-ts-ysw6p | Here\'s the plan:\n\n- We determine the indices mnandmxof two numbers being migrated to the ends of the list.\n- We count the number of steps required to move e | Spaulding_ | NORMAL | 2023-06-04T16:54:41.140523+00:00 | 2024-11-02T06:40:51.060592+00:00 | 746 | false | Here\'s the plan:\n\n- We determine the indices `mn`and`mx`of two numbers being migrated to the ends of the list.\n- We count the number of steps required to move each, which are `mn` and `n-mx-1`. \n- We check whether `mn > mx`, in which case the two migrations share a step and we then correct by decrementing the sum by one.\n\n- We return this sum.\n```\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n \n mn, mx = nums.index(1) , nums.index(n:= len(nums)) \n return mn - mx + n - 1 - (mn > mx)\n```\n[https://leetcode.com/problems/semi-ordered-permutation/submissions/1440532226/](https://leetcode.com/problems/semi-ordered-permutation/submissions/1440532226/)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~`len(nums)`. | 16 | 0 | ['Python3'] | 2 |
semi-ordered-permutation | Find Positions | find-positions-by-votrubac-m4q2 | C++\ncpp\nint semiOrderedPermutation(vector<int>& n) {\n int first = find(begin(n), end(n), 1) - begin(n);\n int last = find(begin(n), end(n), n.size()) - | votrubac | NORMAL | 2023-06-04T04:01:47.388959+00:00 | 2023-06-04T04:01:47.389002+00:00 | 1,420 | false | **C++**\n```cpp\nint semiOrderedPermutation(vector<int>& n) {\n int first = find(begin(n), end(n), 1) - begin(n);\n int last = find(begin(n), end(n), n.size()) - begin(n);\n return first + (n.size() - last - 1) - (first > last);\n}\n``` | 13 | 1 | ['C'] | 1 |
semi-ordered-permutation | Long but easy solution :) | long-but-easy-solution-by-movsar-k1gy | \n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst semiOrderedPermutation = function (nums) {\n const n = nums.length\n if (nums[0] === 1 & | movsar | NORMAL | 2023-06-04T04:03:38.167103+00:00 | 2023-06-04T04:03:38.167148+00:00 | 1,303 | false | ```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nconst semiOrderedPermutation = function (nums) {\n const n = nums.length\n if (nums[0] === 1 && nums[n - 1] === n) return 0\n \n let cn = 0\n \n let i = nums.indexOf(1)\n while (nums[0] !== 1 && i >= 0) {\n const curr = nums[i - 1]\n \n nums[i - 1] = nums[i]\n nums[i] = curr\n \n i -= 1\n cn += 1\n }\n \n if (nums[0] === 1 && nums[n - 1] === n) return cn\n i = nums.indexOf(n)\n while (nums[n - 1] !== n && i < n) {\n const curr = nums[i]\n \n nums[i] = nums[i + 1]\n nums[i + 1] = curr\n \n i += 1\n cn += 1\n }\n \n return cn\n};\n``` | 8 | 0 | ['JavaScript'] | 2 |
semi-ordered-permutation | Explained - iteration || Very simple and easy to understand | explained-iteration-very-simple-and-easy-1u03 | Approach\n1. Find the ith index of min val 1 => we need to do i operation to move 1 to first position\n2. Find the ith index of the max val n => we need to do ( | kreakEmp | NORMAL | 2023-06-04T04:19:03.574853+00:00 | 2023-06-04T14:22:51.622828+00:00 | 2,981 | false | ## Approach\n1. Find the ith index of min val 1 => we need to do i operation to move 1 to first position\n2. Find the ith index of the max val n => we need to do (n - i - 1) operation to take it to last position\n3. Take the sum of above two as the answer. Only corner case is when the ith index of 1 is larger than ith index of n - in this case we need to reduce the ans by 1 as the 1 & n cna be swapped at the same time so that we count it as 1 operation in place of 2.\n \n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int imin = 0, imax = nums.size(), n = nums.size();\n for(int i = 0; i < n; ++i){\n if(nums[i] == 1) imin = i;\n if(nums[i] == n) imax = i;\n }\n if(imin < imax) return (imin + n - imax - 1);\n return (imin + n - imax - 1) - 1;\n }\n};\n``` | 7 | 0 | ['C++'] | 2 |
semi-ordered-permutation | python3 Solution | python3-solution-by-motaharozzaman1996-ez5s | \n\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n n=len(nums)\n i=nums.index(1)\n j=nums.index(n)\n | Motaharozzaman1996 | NORMAL | 2023-06-04T12:45:44.714687+00:00 | 2023-06-04T12:45:44.714727+00:00 | 621 | false | \n```\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n n=len(nums)\n i=nums.index(1)\n j=nums.index(n)\n ans=i+n-1-j-(i>j)\n return ans\n``` | 6 | 0 | ['Python', 'Python3'] | 0 |
semi-ordered-permutation | Java | Easy solution | 5 lines | java-easy-solution-5-lines-by-judgementd-51p4 | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co | judgementdey | NORMAL | 2023-06-04T04:04:48.261498+00:00 | 2023-06-04T04:09:18.636911+00:00 | 1,376 | false | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int n = nums.length, a = 0, b = 0;\n \n for (var i=0; i<n; i++) {\n if (nums[i] == 1) a = i;\n if (nums[i] == n) b = i;\n }\n return a + (n-1-b) - (a > b ? 1 : 0);\n }\n}\n``` | 6 | 0 | ['Array', 'Java'] | 1 |
semi-ordered-permutation | Find C++ | find-c-by-harsh_negi_07-h7l4 | Intuition\nFind Position of 1 and n\nResult = ind_one + (n - ind_n + 1) (Calculating Swaps)\nBut if ind_one is on left of ind_n, it means you one swap operation | negiharsh12 | NORMAL | 2023-06-04T04:02:36.968333+00:00 | 2023-06-04T04:09:54.247898+00:00 | 1,156 | false | # Intuition\n**Find Position of ```1``` and ```n```**\n**```Result = ind_one + (n - ind_n + 1)```** (Calculating Swaps)\n**But if ind_one is on left of ind_n, it means you one swap operation will be common for both i.e ```swap(1, n)``` so will do ```Result - 1```**\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n int ind_One = find(nums.begin(), nums.end(), 1) - nums.begin(), ind_N = find(nums.begin(), nums.end(), n) - nums.begin();\n int Result = ind_One + n - (ind_N + 1);\n if(ind_One > ind_N) // One on left of N\n return Result - 1;\n return Result;\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
semi-ordered-permutation | GET INDEX OF 1 & n || C++ | get-index-of-1-n-c-by-ganeshkumawat8740-jmyh | get index 1 and n\na = index of 1;\nb = index of n\nif(index of 1 < index of n)\n than return a+n-1-b;\nelse return a+n-1-b-n//there is we substracte previou | ganeshkumawat8740 | NORMAL | 2023-06-04T06:41:41.697889+00:00 | 2023-06-04T06:41:41.697935+00:00 | 1,246 | false | get index 1 and n\na = index of 1;\nb = index of n\nif(index of 1 < index of n)\n than return a+n-1-b;\nelse return a+n-1-b-n//there is we substracte previous ans by 1 because here one case is possible that we swap(1,n)\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int a,b,i,n=nums.size();\n for(i = 0; i < n; i++){\n if(nums[i]==1)a = i;\n else if(nums[i]==n)b = i;\n }\n if(a<b){\n return a+n-1-b;\n }else{\n return a+n-1-b-1;\n }\n }\n};\n``` | 4 | 0 | ['C++'] | 2 |
semi-ordered-permutation | C++ || easy solution | c-easy-solution-by-gauravtripathi310-6ir9 | Intuition\n Describe your first thoughts on how to solve this problem. \nFind the position of 1 and the n in the nums which will take o(n)\ni have used find but | gauravtripathi310 | NORMAL | 2023-06-05T14:16:05.425210+00:00 | 2023-06-05T14:16:05.425245+00:00 | 53 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind the position of 1 and the n in the nums which will take o(n)\ni have used find but simple iteration can also be done to find the pos of both the elements \n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find the pos of both the element using simple iteration or find \n2. Their are only two case which we have to see now \n i.pos_1 < pos_2\n ii. pos_1 > pos_2\n3. For case i we simple add the no of swaps need for both the element to reach their respective position \n4. for case ii we do the same as for case i but subtract 1 from it as when we were swaping elements for 1 as the pos_2 < pos_1 then the n element must have shifted by one toward its destination so -1 to the ans\n# Complexity\n- Time complexity:\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n int pos_1 = find(nums.begin(),nums.end(),1) - nums.begin();\n int pos_2 = find(nums.begin(),nums.end(),n) - nums.begin();\n return (pos_1<pos_2) ?(pos_1 + n-1-pos_2):(pos_1 + (n-1 - pos_2) - (1));\n\n\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
semi-ordered-permutation | [C++] ✅Easy O(n) Solution w/ Intuition + Code [Finding index] | c-easy-on-solution-w-intuition-code-find-m3zt | Intuition\nMy intuition for this problem was to know the number of swaps to change the position of a number. Our task is to move the smallest number to the star | nipunrautela | NORMAL | 2023-06-04T05:35:51.190442+00:00 | 2023-06-04T05:37:17.809836+00:00 | 95 | false | # Intuition\nMy intuition for this problem was to know the number of swaps to change the position of a number. Our task is to move the smallest number to the start and the largest number to the end of the array.\nTo move a number from index `i=5` to `j=0`, we need `i-j` swaps. So to move the minimum number from any index to the `0th index` we need as many number of swaps as the index of the min. number.\nNow we need `n-1-i` swaps to move the largest number(positioned at $$i^{th}$$ index) to the `n-1 index` but there\'s a catch if we do this after moving the min number.\n\nWe need to consider the fact that the largest number can come before the smallest number and that moving the smallest number has moved the largest number towards it\'s desired location. So if the largest number\'s index comes before the minimum number\'s index, we use `n-1-i - 1` to indicate that it has to do one less swap itself. \n\n# Approach\nThe approach is simple, we just find:\n- index of minimum number `minIdx`\n- index of maximum number `maxIdx`\n\nAnd use what we derived above:\n- Swaps for moving minimum number, `smin`: `minIdx`\n- Swaps for moving maximum number, `smax`: \n1. `n-1-maxIdx` if `minIdx<maxIdx`\n2. `n-1-maxIdx - 1` if `minIdx>maxIdx`\n\nSo, Total number of swaps (our answer): `smin + smax`\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int minIdx{0};\n int maxIdx{0};\n for(int i=0; i<nums.size(); i++) {\n if (nums[i] < nums[minIdx])\n minIdx = i;\n if (nums[i] > nums[maxIdx])\n maxIdx = i;\n }\n int res{0};\n res += minIdx;\n res += nums.size()-1-maxIdx-(maxIdx<minIdx);\n return res;\n }\n};\n```\n\n# Complexity\n- Time complexity: $$O(n)$$\nBecause we\'re traversing the array once to find the indices of the minimum and the maximum number.\n- Space complexity: $$O(1)$$\n\n\n> ### Note\n> - Upvote if you liked my solution\n> - Drop a comment if you have any doubt | 3 | 0 | ['C++'] | 1 |
semi-ordered-permutation | Simple Java O(n) Solution | simple-java-on-solution-by-shashankbhat-cr1w | Approach\n- Get the index of 1 and N\n- Number of swaps would be sum of difference between index of 1 and 0 and difference between index of N and last index.\n- | shashankbhat | NORMAL | 2023-06-04T04:44:47.024424+00:00 | 2023-06-04T07:15:12.671190+00:00 | 648 | false | # Approach\n- Get the index of 1 and N\n- Number of swaps would be sum of difference between index of 1 and 0 and difference between index of N and last index.\n- If position of N is before 1, then we require 1 less swap\n\n# Code\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int indexOne = -1;\n int indexN = -1;\n \n for(int i=0; i<nums.length; i++) {\n if(nums[i] == 1)\n indexOne = i;\n if(nums[i] == nums.length)\n indexN = i;\n }\n \n int count = 0;\n if(indexOne > indexN)\n count--;\n \n count += indexOne + (nums.length - 1 - indexN);\n return count;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Python 3 || Easy Solution || Compare Min and Max index | python-3-easy-solution-compare-min-and-m-v7wh | 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 | SarahDong | NORMAL | 2023-06-04T04:17:30.986764+00:00 | 2023-06-04T04:17:30.986804+00:00 | 621 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\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 semiOrderedPermutation(self, nums: List[int]) -> int:\n \n if nums[0] == 1 and nums[len(nums) - 1] == len(nums):\n return 0\n \n op = 0\n min_idx = nums.index(min(nums))\n max_idx = nums.index(max(nums))\n if min_idx < max_idx:\n op = min_idx + (len(nums) - 1 - max_idx)\n if min_idx > max_idx:\n op = min_idx + (len(nums) - 1 - max_idx) - 1\n \n return op\n\n\n \n``` | 3 | 0 | ['Python3'] | 2 |
semi-ordered-permutation | Solution in C | solution-in-c-by-akcyyix0sj-unxt | Code | vickyy234 | NORMAL | 2025-01-05T04:46:01.469512+00:00 | 2025-01-05T04:46:01.469512+00:00 | 57 | false | # Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
int index1, index2;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == 1)
index1 = i;
if (nums[i] == numsSize)
index2 = i;
}
if (index1 < index2)
return index1 + ((numsSize - 1) - index2);
return index1 + (((numsSize - 1) - index2)) - 1;
}
``` | 2 | 0 | ['C'] | 0 |
semi-ordered-permutation | i/p o/p analyze kro ho jayega :D | ip-op-analyze-kro-ho-jayega-d-by-yesyese-04pe | 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 | yesyesem | NORMAL | 2024-08-26T09:06:06.675161+00:00 | 2024-08-26T09:06:06.675180+00:00 | 42 | 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```cpp []\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n=nums.size();\n if(nums[0]==1&&nums[n-1]==n)\n return 0;\n\n auto it=find(nums.begin(),nums.end(),1);\n int i=distance(nums.begin(),it);\n \n it=find(nums.begin(),nums.end(),n);\n int j=distance(nums.begin(),it);\n\n if(i<j)\n {\n return (i-0)+(n-1-j);\n }\n else if(i>j)\n {\n return (i-0)+(n-1-j)-1;\n }\n\n\n return -1;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Java ⭐️ || Beginner Friendly Solution ✅ || 100% beats ✈️ || Fully Explained 💯 | java-beginner-friendly-solution-100-beat-5hom | Approach\n\nTo convert the given permutation nums into a semi-ordered permutation, we need to perform swaps to move the number 1 to the first position and the n | akobirswe | NORMAL | 2023-08-06T14:40:27.564305+00:00 | 2023-08-06T14:40:27.564333+00:00 | 70 | false | # Approach\n\nTo convert the given permutation `nums` into a semi-ordered permutation, we need to perform swaps to move the number `1` to the first position and the number `n` to the last position. We can achieve this by finding the indices of `1` and `n` in the array and then calculating the number of operations required to move `1` to the first position and `n` to the last position.\n\n**Logic:**\n1. Initialize two variables `count` and `idx` to keep track of the number of operations and the index of `1` in the array, respectively.\n2. Loop through the array to find the index of the number `1`. Set `idx` to this index.\n3. Calculate the number of operations required to move `1` to the first position. Set `count` to `idx`.\n4. While the number at the first position is not `1`, swap the elements at indices `idx` and `idx-1` to move `1` towards the first position. Decrement `idx` by 1 after each swap.\n5. Loop through the array again to find the index of the number `n`. Set `idx` to this index.\n6. Calculate the number of operations required to move `n` to the last position. Return `count + n - idx - 1`, which represents the total number of operations needed to make `nums` a semi-ordered permutation.\n\n**Pseudocode:**\n```plaintext\nFunction semiOrderedPermutation(nums):\n n = length of nums\n count = 0\n idx = 0\n \n # Find the index of 1 in nums\n for i = 0 to n-1:\n if nums[i] == 1:\n idx = i\n break\n \n # Calculate the number of operations to move 1 to the first position\n count = idx\n \n # Move 1 to the first position using swaps\n while nums[0] != 1:\n swap nums[idx] and nums[idx-1]\n idx = idx - 1\n \n # Find the index of n in nums\n for i = 0 to n-1:\n if nums[i] == n:\n idx = i\n break\n \n # Calculate the number of operations to move n to the last position\n return count + n - idx - 1\n```\n\n**Final Remarks:**\nThe provided solution follows the above approach and logic to solve the problem. It efficiently moves the number `1` to the first position and the number `n` to the last position, minimizing the number of swaps needed. The solution is clear and concise, making it easy for beginners to understand and implement.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int n = nums.length;\n int count = 0;\n int idx = 0;\n \n for (int i = 0; i < n; i++) {\n if (nums[i] == 1) {\n idx = i;\n break;\n }\n }\n \n count = idx;\n\n while (nums[0] != 1) {\n nums[idx] = nums[idx - 1];\n nums[idx - 1] = 1;\n idx--;\n }\n \n for (int i = 0; i < n; i++) {\n if (nums[i] == n) {\n idx = i;\n break;\n }\n }\n\n return count + n - idx - 1;\n }\n}\n``` | 2 | 0 | ['Array', 'Simulation', 'Java', 'C#'] | 0 |
semi-ordered-permutation | [C++/Java] Determining the Positions of 1 and N | cjava-determining-the-positions-of-1-and-wahp | \nDetermine the locations of 1 and N, labelled as one_index and n_index respectively. The number of swaps needed to reposition 1 at the start is equivalent to o | xiangcan | NORMAL | 2023-06-06T18:53:09.231527+00:00 | 2023-06-06T18:54:01.276138+00:00 | 87 | false | \nDetermine the locations of `1` and `N`, labelled as `one_index` and `n_index` respectively. The number of swaps needed to reposition `1` at the start is equivalent to `one_index`, and similarly, to move `N` to the final position, `N - 1 - n_index` swaps are required. \n\nHowever, should `1` be located to the right of `N`, then as `1` is moved towards the 0th position, it would swap places with `N`, thereby bringing `N` a step closer to its desired final position. This would therefore require one less swap, i.e., `N - 1 - n_index - 1` to relocate `N` to the end. Consequently, if `1` is to the right of `N`, we need to subtract 1 from the total swap count.\n\nC++:\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n int one_index = 0, n_index = 0;\n for (int i = 0; i < n; i++) {\n if (nums[i] == 1) one_index = i;\n else if (nums[i] == n) n_index = i;\n }\n return one_index + n - 1 - n_index - (one_index < n_index ? 0 : 1);\n }\n};\n```\n\nJava:\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int n = nums.length;\n int oneIndex = 0, nIndex = 0;\n for (int i = 0; i < n; i++) {\n if (nums[i] == 1) oneIndex = i;\n else if (nums[i] == n) nIndex = i;\n }\n return oneIndex + n - 1 - nIndex - (oneIndex < nIndex ? 0 : 1);\n }\n}\n``` | 2 | 0 | ['C', 'Java'] | 0 |
semi-ordered-permutation | Easy Solution || C++ | easy-solution-c-by-dcoder_53-vf6i | 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 | Dcoder_53 | NORMAL | 2023-06-05T05:24:02.158455+00:00 | 2023-06-05T11:02:13.916377+00:00 | 190 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int mini=0;\n int maxi=0;\n int n=nums.size();\n for(int i=0 ; i < n ; i++){\n if(nums[i]==1){\n mini=i;\n }\n else if(nums[i]==n){\n maxi=i;\n }\n }\n if(mini>maxi){\n maxi=(n-1)-(maxi+1);\n }\n else{\n maxi=(n-1)-maxi;\n }\n return mini+maxi;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Python Easy Solution | python-easy-solution-by-sumedh0706-8zte | Code\n\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n a=nums.index(min(nums))\n b=nums.index(max(nums))\n | Sumedh0706 | NORMAL | 2023-06-04T07:25:15.323235+00:00 | 2023-06-04T07:25:15.323277+00:00 | 82 | false | # Code\n```\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n a=nums.index(min(nums))\n b=nums.index(max(nums))\n if b<a:\n return a+(len(nums)-1-b)-1\n else:\n return a+(len(nums)-1-b)\n \n``` | 2 | 0 | ['Python3'] | 0 |
semi-ordered-permutation | ✔️ Python3 Solution | Find Position | python3-solution-find-position-by-satyam-r66t | Intuition\nFind the position of 1 and n in the nums let say l and r resp., no. of swaps required to make l the first-number is l since we need to swap all the e | satyam2001 | NORMAL | 2023-06-04T04:43:27.110340+00:00 | 2023-06-04T04:43:27.110377+00:00 | 390 | false | # Intuition\nFind the position of 1 and n in the nums let say l and r resp., no. of swaps required to make l the first-number is `l` since we need to swap all the elements with 1 from index l to 0, Similarly for n be the last-number we required `n - r - 1` swaps.\nBut there\'s a catch if the index of n is less than 1 than we need to `subtract 1` from ans, as 1 swap is counted twice. When 1 and n are adjacent to each other after some operation\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n n = len(nums)\n l, r = nums.index(1), nums.index(n)\n return l + n - r - 1 - (1 if r < l else 0)\n``` | 2 | 0 | ['Python', 'Python3'] | 0 |
semi-ordered-permutation | O(n) || Very easy || Java | on-very-easy-java-by-shyamchadha34-889d | Approach\n Describe your approach to solving the problem. \n Just find the idex of 1 and the index of maximum number. \n If the index of 1 > index of max | shyamchadha34 | NORMAL | 2023-06-04T04:13:46.628440+00:00 | 2023-06-04T04:13:46.628465+00:00 | 131 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n Just find the idex of 1 and the index of maximum number. \n If the index of 1 > index of max number, it will take one swap less \n if(idx1>idx){\n idx1=idx1-1;\n }\n The answer will be (nums.length-1-idx) + idx1\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int max=Integer.MIN_VALUE;\n int idx=0,idx1=0;\n for(int i=0;i<nums.length;i++){\n if(nums[i]>max){\n max=nums[i];\n idx=i;\n }\n if(nums[i]==1){\n idx1=i;\n }\n }\n if(idx1>idx){\n idx1=idx1-1;\n }\n return (nums.length-1-idx) + idx1;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Simple || Clean || Java Solution | simple-clean-java-solution-by-himanshubh-ngcs | \njava []\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int opr = 0, j = 0;\n// finding 1\n for(int i=0; i<nums | HimanshuBhoir | NORMAL | 2023-06-04T04:03:12.424852+00:00 | 2023-06-04T04:03:12.424898+00:00 | 148 | false | \n```java []\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int opr = 0, j = 0;\n// finding 1\n for(int i=0; i<nums.length; i++) \n if(nums[i] == 1) j = i;\n// operating 1 to start index\n while(j > 0){\n nums[j] = nums[j-1];\n nums[j-1] = 1;\n opr++;\n j--;\n }\n// finding n\n for(int i=0; i<nums.length; i++) \n if(nums[i] == nums.length) j = i;\n// operating n to last index\n while(j < nums.length-1){\n nums[j] = nums[j+1];\n nums[j+1] = nums.length;\n opr++;\n j++;\n } \n return opr;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
semi-ordered-permutation | cpp 🤩 | easy solution | cpp-easy-solution-by-varuntyagig-b563 | Complexity
Time complexity:
O(n)
Space complexity:
O(1)
Code | varuntyagig | NORMAL | 2025-03-24T09:14:39.172930+00:00 | 2025-03-24T09:14:39.172930+00:00 | 12 | false | # Complexity
- Time complexity:
$$O(n)$$
- Space complexity:
$$O(1)$$
# Code
```cpp []
class Solution {
public:
int semiOrderedPermutation(vector<int>& nums) {
// Step-1
// find 1
int one = -1;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == 1) {
one = i;
break;
}
}
int beforeOne = one - 1;
int count = 0;
while (beforeOne != -1) {
swap(nums[one--], nums[beforeOne--]);
count++;
}
// Step-2
// find n
int findn = -1;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == nums.size()) {
findn = i;
break;
}
}
int findnPlus = findn + 1;
while (findnPlus != nums.size()) {
swap(nums[findn++], nums[findnPlus++]);
count++;
}
return count;
}
};
``` | 1 | 0 | ['Array', 'Two Pointers', 'C++'] | 0 |
semi-ordered-permutation | Easy C solution | easy-c-solution-by-aswath_1192-681a | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Aswath_1192 | NORMAL | 2025-01-04T14:11:55.693620+00:00 | 2025-01-04T14:11:55.693620+00:00 | 22 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
int semiOrderedPermutation(int* nums, int n) {
int a = -1,e = -1;
for(int i = 0;i<n;i++){
if(nums[i]==1){
a = i;
}
if(nums[i]==n){
e = i;
}
}
int c = (n-1)-e;
if(a<e){
return a+c;
}else{
return a+c-1;
}
}
``` | 1 | 0 | ['C'] | 0 |
semi-ordered-permutation | Simple C solution | simple-c-solution-by-pavithrav25-tyac | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | pavithrav25 | NORMAL | 2025-01-02T13:21:22.876917+00:00 | 2025-01-02T13:21:22.876917+00:00 | 13 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
int pos1=0,posN=0;
for(int i=0;i<numsSize;i++){
if(nums[i]==1){
pos1=i;
}
if(nums[i]==numsSize){
posN=i;
}
}
int swaps1=pos1;
int swapsN=numsSize-1-posN;
if (pos1 > posN)
return swaps1 + swapsN - 1;
else
return swaps1 + swapsN;
}
``` | 1 | 0 | ['C'] | 0 |
semi-ordered-permutation | Easy Solution in C | easy-solution-in-c-by-sathurnithy-ft6o | Code | Sathurnithy | NORMAL | 2024-12-31T10:17:26.985681+00:00 | 2024-12-31T10:17:26.985681+00:00 | 12 | false |
# Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
if(nums[0] == 1 && nums[numsSize - 1] == numsSize) return 0;
int posOne = -1;
int posSize = -1;
for(int i=0; i<numsSize; i++){
if(nums[i] == 1) posOne = i;
else if(nums[i] == numsSize) posSize = i;
if(posOne != -1 && posSize != -1) break;
}
return ((posOne < posSize) ? (posOne - posSize + numsSize - 1) : (posOne - posSize + numsSize - 2));
}
// [2, 4, 1, 3]
// ee = 1
// ss = 2
``` | 1 | 0 | ['C'] | 0 |
semi-ordered-permutation | Answer | answer-by-reddyshavva198-r2mx | \n# Code\npython3 []\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n n=len(nums)\n mn, mx = nums.index(1) , nums | ReddyShavva198 | NORMAL | 2024-10-02T10:59:23.831956+00:00 | 2024-10-02T10:59:23.831989+00:00 | 18 | false | \n# Code\n```python3 []\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n n=len(nums)\n mn, mx = nums.index(1) , nums.index(n) \n return mn - mx + n - 1 - (mn > mx)\n``` | 1 | 0 | ['Python3'] | 0 |
semi-ordered-permutation | C++ could we grind 1 swap? | c-could-we-grind-1-swap-by-the_ghuly-s1cv | \nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int first = -1;\n int last = -1;\n for(int i = 0;i<nums. | the_ghuly | NORMAL | 2024-06-21T10:12:04.171340+00:00 | 2024-06-21T10:12:04.171374+00:00 | 3 | false | ```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int first = -1;\n int last = -1;\n for(int i = 0;i<nums.size();++i)\n {\n if(nums[i]==1)\n first = i;\n if(nums[i] == nums.size())\n last = i;\n }\n return first>last?first+nums.size()-1-last-1:first+nums.size()-1-last;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Simple java code 1 ms beats 100 % | simple-java-code-1-ms-beats-100-by-arobh-gega | \n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int x=-1,y=-1;\n for(int i=0;i<nums.length | Arobh | NORMAL | 2024-01-23T04:45:46.533962+00:00 | 2024-01-23T04:45:46.534003+00:00 | 13 | false | \n# Complexity\n- \n\n# Code\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int x=-1,y=-1;\n for(int i=0;i<nums.length;i++){\n if(nums[i]==1) x=i;\n else if(nums[i]==nums.length) y=i;\n }\n if(x<y) return x+(nums.length-1-y);\n return x+(nums.length-1-y)-1;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
semi-ordered-permutation | 2hrs | 2hrs-by-zaharkhach-fkni | 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 | ZaharKhach | NORMAL | 2023-10-02T14:56:20.558341+00:00 | 2023-10-02T14:56:20.558362+00:00 | 32 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar semiOrderedPermutation = function (nums) {\n let counter = 0\n while (nums[0] !== 1) {\n for (let i = 0; i < nums.length; i++) {\n if (nums[i + 1] == 1) {\n const temp = nums[i];\n nums[i] = nums[i + 1];\n nums[i + 1] = temp;\n counter++\n }\n }\n }\n\n while (nums[nums.length - 1] !== nums.length) {\n for (let i = 0; i < nums.length; i++) {\n if(nums[i-1] == nums.length) {\n const temp = nums[i];\n nums[i] = nums[i-1];\n nums[i-1] = temp;\n counter++\n }\n }\n }\n\n return counter\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
semi-ordered-permutation | C++ solution | c-solution-by-prparaskar-j4ih | Intuition\n Describe your first thoughts on how to solve this problem. \nFor the given 0-indexed array, we are allowed to perform swap on any two adjacent eleme | prparaskar | NORMAL | 2023-08-14T17:52:15.080828+00:00 | 2023-08-14T17:58:15.256005+00:00 | 77 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor the given 0-indexed array, we are allowed to perform swap on any two adjacent elements unit we make array nums a semi-ordered permutation.\nwe can perform swap on element valued 1 till it reaches index 0.\nSimilarly, we perform swap on element valued n (which is also the size of the array nums) till it reaches the last index that is (n-1).\nWe return the number of swaps required in this process.\n\n\n<!-- Describe your approach to solving the problem. -->\n\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n=nums.size();\n int cnt=0;\n bool f=false;\n while(f==false){\n for(int i=0;i<n;i++){\n if(nums[i]==n & i!=(n-1)){\n swap(nums[i],nums[i+1]);\n cnt++;\n }\n if(nums[i]==1 && i!=0){\n swap(nums[i], nums[i-1]);\n cnt++;\n }\n }\n if(nums[0]==1 && nums[n-1]==n){\n f=true;\n }\n\n }\n return cnt;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
semi-ordered-permutation | 2 C++ solutions || Beginner-friendly approach || With and without vector.find() | 2-c-solutions-beginner-friendly-approach-3ayq | \n# Code\n\n// Soution 1 (With find())\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& A) {\n int n = A.size();\n int i = | prathams29 | NORMAL | 2023-06-23T08:22:51.770588+00:00 | 2023-06-23T08:23:32.136769+00:00 | 36 | false | \n# Code\n```\n// Soution 1 (With find())\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& A) {\n int n = A.size();\n int i = find(A.begin(), A.end(), 1) - A.begin(); \n int j = find(A.begin(), A.end(), n) - A.begin();\n return i + n - 1 - j - (i > j);\n }\n}\n\n// Solution 2 (Without find())\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n=nums.size(), count=0;\n for(int i=0; i<n; i++)\n {\n if(nums[i]==1){\n count+=i;\n for(int j=i; j>0; j--)\n swap(nums[j], nums[j-1]); // we swap the numbers so that the later considering the case when 1 comes after n-1 because count will get repeated for such cases\n break;\n }\n }\n for(int i=0; i<n; i++)\n {\n if(nums[i]==n){ \n count+=(n-1)-i;\n break;\n }\n }\n return count;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | simple code C++ | simple-code-c-by-vips80091-zahi | \n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n | vips80091 | NORMAL | 2023-06-23T07:40:03.591728+00:00 | 2023-06-23T07:40:03.591752+00:00 | 15 | false | \n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int start,end;\n int n = nums.size();\n for(int i = 0; i<nums.size(); i++){\n if(nums[i] == 1)\n start = i;\n if(nums[i] == n)\n end = i;\n }\n if(start > end)\n return start + n - end - 2;\n else \n return start + n - end-1;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | [C++] 2 Pointer Solution, 7ms, 46.3MB | c-2-pointer-solution-7ms-463mb-by-ajna2-pwkw | For this problem we have to just find the indexes of 1 and the value matching length of nums, then check how far they are from being in the first and in the las | Ajna2 | NORMAL | 2023-06-23T05:23:19.647653+00:00 | 2023-06-23T05:23:19.647684+00:00 | 16 | false | For this problem we have to just find the indexes of `1` and the value matching length of `nums`, then check how far they are from being in the first and in the last position - with a caveat: if the first position is `>` than the last one, when we start swapping one of the indexes we will put the latter closer to its position, so we need to take that into account.\n\nNow, to code our solution, let\'s start with declaring our support variables:\n* `len` will store the length of `nums`;\n* `p1` and `p2` will be where we store the positions of the values `1` and `len` respectively, both initially set to be `-1`.\n\nWe will then loop with `i` across all the positions in `nums` until we have found both pointers (ie: `p1 == -1 || p2 == -1`) and:\n* store `nums[i]` in `n`;\n* if `n == 1`, we will set `p1` to be `i`;\n* otherwise, if `n == len`, we will set `p2` to be `i`.\n\nOnce done, we will `return` the sum of the distances of `p1` from the first position (ie: `p1 - 0`) and `p2` from the last position (ie: `len - p2 - 1`), adjusted by `-1` as we mentioned in our incipit if `p1 > p2`.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int> &nums) {\n // support variables\n int len = nums.size(), p1 = -1, p2 = -1;\n // parsing nums\n for (int i = 0, n; p1 == -1 || p2 == -1; i++) {\n n = nums[i];\n if (n == 1) p1 = i;\n else if (n == len) p2 = i;\n }\n return (p1 > p2 ? -1 : 0) + p1 + len - p2 - 1;\n }\n};\n```\n\nAlternative version of that logic, working directly with a variable result `res` and a boolean flag `foundOne` to check if we had already found the other index before. Notice that now we need to do one less check at each loop iteration and that we use `foundOne` in the `else if` clause to decrease the value of `res` by `1` if we had found `1` before `len`; overall, this version seemed to perform a bit better:\n\n```cpp\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int> &nums) {\n // support variables\n int len = nums.size(), res = 0;\n bool foundOne = false;\n // parsing nums\n for (int i = 0, n; ; i++) {\n n = nums[i];\n if (n == 1) {\n res += i;\n if (foundOne) break;\n foundOne = true;\n }\n else if (n == len) {\n res += len - i - 1 - !foundOne;\n if (foundOne) break;\n foundOne = true;\n }\n }\n return res;\n }\n};\n``` | 1 | 0 | ['Array', 'Two Pointers', 'C++'] | 0 |
semi-ordered-permutation | simple logic!! | simple-logic-by-tanmay_jaiswal-bk3o | \nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n int i = 0, j = 0;\n for (int x = | tanmay_jaiswal_ | NORMAL | 2023-06-11T17:52:01.932796+00:00 | 2023-06-11T17:52:01.932838+00:00 | 175 | false | ```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n int i = 0, j = 0;\n for (int x = 0; x<n; x++) {\n if (nums[x] == 1) i = x;\n if (nums[x] == n) j = x;\n }\n\n if (j < i) return i + n-j-2;\n return i + n-j-1;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
semi-ordered-permutation | Formula Based Approach | formula-based-approach-by-ridamexe-amzr | Code\n\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n=nums.size();\n int mx=0, mxidx=0;\n int mn=I | ridamexe | NORMAL | 2023-06-11T05:33:15.170807+00:00 | 2023-06-11T05:33:15.170849+00:00 | 96 | false | # Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n=nums.size();\n int mx=0, mxidx=0;\n int mn=INT_MAX, mnidx;\n int count=0;\n\n for(int i=0; i<n; i++){\n mx=max(mx, nums[i]);\n if(nums[i]==mx) mxidx=i;\n\n mn=min(mn, nums[i]);\n if(nums[i]==mn) mnidx=i;\n }\n \n count=n+mnidx-mxidx-1;\n if(mnidx<mxidx) return count;\n return --count;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
semi-ordered-permutation | Easy, Clean, Python3 Solution 🔥 | easy-clean-python3-solution-by-aadyatiwa-8loe | Intuition\n Describe your first thoughts on how to solve this problem. \nIt is a very straightforward approach, we can simply, easily simulate it.\n\n# Approach | aadyatiwari | NORMAL | 2023-06-09T19:15:15.504169+00:00 | 2023-06-09T19:15:15.504210+00:00 | 79 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is a very straightforward approach, we can simply, easily simulate it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nkeep track of the given indices of 1 and the last element. Perform swaps and calculate swaps to find the required answer.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ where n is the size of nums\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n n = len(nums)\n reqd = {1:0, n:(n-1)}\n given = {1:0, n:0}\n for i in range(n):\n if nums[i] == 1:\n given[1] = i\n if nums[i] == n:\n given[n] = i\n if given == reqd: return 0\n if given[n] < given[1]:\n return n-1-given[n]+given[1]-1\n else:\n return given[1] + (n-1) - given[n]\n \n``` | 1 | 1 | ['Array', 'Hash Table', 'Simulation', 'Python3'] | 0 |
semi-ordered-permutation | Super Easy Solution with Simple Logic || Store positions | super-easy-solution-with-simple-logic-st-kyla | Intuition\nSince we have to swap adjacent numbers to fulfil the given condition ,we will store the psoiton of 1 and the last number by iterating through loop. A | varunkusabi8 | NORMAL | 2023-06-05T12:12:52.944198+00:00 | 2023-06-05T12:21:37.998236+00:00 | 27 | false | # Intuition\nSince we have to swap adjacent numbers to fulfil the given condition ,we will store the psoiton of 1 and the last number by iterating through loop. After the answer will be total number of swaps,hence we will add the number of swaps with the help of their positions.\nBut if the last number i.e. n is present before the number 1 both of the them reach their destinantion simultaneously ,hence we will decrease the answer by 1.\n\n# Approach\n- We will store the two psoitons in variables f and l.\n- We will store the answer i.e. total number of swaps in variable\n```\nint ans=f+(n-1-l);\n```\n- We will check for the condition (mentioned in Intuiton above) and decrement answer by 1 if it is there.\n```\nif(l<f)\n{\n ans=ans-1;\n}\n```\n- Return the answer.\n\n\n\n\n\n\n# Complexity\n- Time complexity:It will be O(n) because of for loop.\n\n\n- Space complexity:It wil be O(1) .\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n=nums.size();\n int f=0,l=0;\n for(int i=0;i<n;i++)\n {\n if(nums[i]==1)\n {\n f=i;\n }\n if(nums[i]==n)\n {\n l=i;\n }\n }\n int ans=f+(n-1-l);\n if(l<f)\n {\n ans=ans-1;\n }\n return ans;\n }\n};\n```\nPlease upvote if it helps! | 1 | 0 | ['Array', 'C++'] | 0 |
semi-ordered-permutation | Java Solution - Beats 100% (Using Recursion) | java-solution-beats-100-using-recursion-r0qym | 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 | ruch21 | NORMAL | 2023-06-04T16:01:07.027270+00:00 | 2023-06-04T16:01:07.027316+00:00 | 365 | 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 private int semiOrder(int nums[], int count) {\n if(nums[0]==1 && nums[nums.length-1]==nums.length) {\n return count;\n }\n else if(nums[0]==1) {\n for(int i=0; i<nums.length-1; i++) {\n if(nums[i]==nums.length) {\n nums[i]=nums[i+1];\n nums[i+1]=nums.length;\n break;\n }\n }\n }\n else {\n for(int i=1; i<nums.length; i++) {\n if(nums[i]==1) {\n nums[i]=nums[i-1];\n nums[i-1]=1;\n break;\n }\n }\n }\n return semiOrder(nums,count+1);\n }\n\n public int semiOrderedPermutation(int[] nums) {\n return semiOrder(nums, 0);\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
semi-ordered-permutation | Easiest implementation | easiest-implementation-by-chaturvedipart-utjo | Complexity\n- Time complexity : O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity : O(1)\n Add your space complexity here, e.g. O(n) \n\n# | ChaturvediParth | NORMAL | 2023-06-04T11:24:10.947815+00:00 | 2023-06-04T11:24:10.947856+00:00 | 24 | false | # Complexity\n- Time complexity : $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n int idx1,idxN;\n for(int i=0 ; i<n ; i++) {\n if(nums[i] == 1) idx1 = i;\n if(nums[i] == n) idxN = i;\n }\n \n int ans = idx1 + n-1-idxN;\n if(idxN < idx1) ans--; // one common swap\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
semi-ordered-permutation | STEP BY STEP EXPLANATION WITH EXAMPLE | step-by-step-explanation-with-example-by-pswi | Intuition\n Describe your first thoughts on how to solve this problem. \nWe just need to find the index of both the elements min element=1\nand maxelement=nums. | vijay__bhaskar | NORMAL | 2023-06-04T09:29:46.977741+00:00 | 2023-06-04T15:06:03.629189+00:00 | 81 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**We just need to find the index of both the elements min element=1\nand maxelement=nums.size();**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# There are two cases only\n1. If location of max element is right to location of minimum element like **[2,3,1,7,6,5,4]** *here 7 is at right of 1*\nin this case answer is **n-maxIndex+minindex** i.e \n**Index of 7 is 3 index of 1 is 2 and n=6 (last index of array)**\n 6-3+2=5\n\n\n2. If location of max is left of location of minimum like **[2,3,7,4,5,1,6]**\nin this case answer is **n-maxIndex+minIndex-1** i.e \n**Index of 7 is 2 index of 1 is 5 and n=6 (last index of array)**\n 6-2+5-1=8\n\n### here 1 is subtracted because when we swap max element with elements to put it at right place it will be swapped once with min elelment\n**[2,3,7,4,5,1,6]**\nhere ist swap **[2,3,4,7,5,1,6]**\nhere 2nd swap **[2,3,4,5,7,1,6]**\nhere 3rd swap **[2,3,4,5,1,7,6]**\n**Now look here the minimum element is changing it\'s postion\nSo -1 is done to count this** \n\n\n\n\n**Here 7 is max element\n 1 is min element**\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$ Constant space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n# C++\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int min=-1,max=-1,ans;\n int n=nums.size()-1;\n for(int i=0; i<nums.size(); i++){\n if(nums[i]==1)\n {\n min=i;\n } //if\n if(nums[i]==nums.size())\n {\n max=i;\n }//if\n \n if(min!=-1&&max!=-1){break;}//to break the loop \n }//for\n ans=min+(n-max);\n if(max<min) \n {\n return ans-1;\n }\n \n return ans; \n \n }\n};\n```\n# JAVA\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int max = Arrays.stream(nums).max().getAsInt();\n int indexMin=0;\n int indexMax=0;\n for(int i=0;i<nums.length;i++){\n if(nums[i]==1){\n indexMin=i;\n }\n if(nums[i]==max){\n indexMax=i;\n }\n }\n if(indexMax<indexMin){\n return indexMin + nums.length-1 -indexMax-1;\n }\n else{\n return indexMin + nums.length-1 -indexMax;\n }\n \n }\n}\n```\n# UPVOTE IF IT\'S HELPFUL\n\n | 1 | 0 | ['Array', 'Two Pointers', 'C++', 'Java'] | 0 |
semi-ordered-permutation | C++ || Simple Solution | c-simple-solution-by-deepak_2311-xdpf | \n# Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1)\n Add your space complexity here, e.g. O(n) \n\n# | godmode_2311 | NORMAL | 2023-06-04T06:02:03.137189+00:00 | 2023-06-04T06:02:03.137228+00:00 | 34 | false | \n# Complexity\n- Time complexity:`O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:`O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n \n int n = nums.size();\n \n int l = 0 , r = n - 1;\n\n for(int i=0;i<n;i++){\n\n if(nums[i] == 1) l = i;\n\n if(nums[i] == n) r = i; \n }\n\n if(r < l){\n return l + (n-1-r) - 1;\n }\n\n return l + (n-1-r);\n \n }\n};\n``` | 1 | 0 | ['Array', 'Math', 'C++'] | 0 |
semi-ordered-permutation | Positions solution for C# (explanation+complexity) | positions-solution-for-c-explanationcomp-0hze | Approach\nThe idea is to find the positions of the element with a value 1 and the element with a value n.\n The first position is the number of iterations neede | deleted_user | NORMAL | 2023-06-04T05:55:26.256096+00:00 | 2023-06-04T16:20:47.081797+00:00 | 93 | false | # Approach\nThe idea is to find the positions of the element with a value 1 and the element with a value n.\n* The first position is the number of iterations needed to move an element from its current position to the zero position.\n* The (nums.length - second position) is the number of iterations needed to move an element from its current position to the last position.\n\nThe corner case is when the first position is larger than the second one. So, we use one swap to change both elements at once.\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n```\npublic int SemiOrderedPermutation(int[] nums)\n{\n var leftIndex = -1;\n var rightIndex = -1;\n\n // Find positions\n for (var i = 0; i < nums.Length; i++)\n {\n if (nums[i] == 1)\n {\n leftIndex = i;\n }\n else if (nums[i] == nums.Length)\n {\n rightIndex = i;\n }\n else if (leftIndex != -1 && rightIndex != -1)\n {\n break;\n }\n }\n\n // Check if already semi-ordered\n if (leftIndex == 0 && rightIndex == nums.Length - 1)\n {\n return 0;\n }\n\n // Calc number of iterations\n return leftIndex + (nums.Length - rightIndex - 1) + (leftIndex > rightIndex ? -1 : 0);\n}\n``` | 1 | 0 | ['C#'] | 0 |
semi-ordered-permutation | 🤩easy understanding✅with intuition and approach and explanation✅ | easy-understandingwith-intuition-and-app-7ydz | Intuition\n Describe your first thoughts on how to solve this problem. \nI got to reach the solution with the help of some examples\nYou may understand with the | peplup_world | NORMAL | 2023-06-04T04:52:26.156844+00:00 | 2023-06-04T04:52:26.156885+00:00 | 377 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI got to reach the solution with the help of some examples\nYou may understand with the help of:-\nexample 1: arr1=[2,1,4,3]\n- first thing to observe is that the position of 1 and n are such that 1 appears before n\n- we see that we have to swap the elements [((n-1)-position of n)+(position of first-0)]number of times\n\nexample 2: arr2=[2,4,1,3]\n- first thing to observe is that the position of 1 and n are such that 1 appears after n\n- we see that we have to swap the elements [((n-1)-position of n)+(position of first-0)]number of times\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. store the index of 1 and n\n2. let us say index of 1 = first and n=last\n3. the value of ans will be=((n-1)-last)+(first-0)\n4. check if first > last\n5. if so then decrease the value of answer(because we can see that we will be swapping once less as there will be a condition when 1 and n will be swapped,so need to count this just once)\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& arr) {\n int n=arr.size();\n int first=-1,last=-1;\n //first store the index of 1 and n\n for(int i=0;i<n;i++){\n if(arr[i]==n)last=i;\n if(arr[i]==1)first=i;\n }\n //now when we observe the solution with a few examples we get to know that there are two cases\n int ans=-1;\n if(last<first){\n ans=((n-1)-last)+(first-0);\n ans--;\n }\n else{\n ans=((n-1)-last)+(first-0);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Math', 'Brainteaser', 'C++'] | 1 |
semi-ordered-permutation | 2 LINER | 2-liner-by-bariscan97-wz6n | 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 | Bariscan97 | NORMAL | 2023-06-04T04:39:20.080403+00:00 | 2023-06-04T04:39:20.080439+00:00 | 227 | 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 def semiOrderedPermutation(self, nums: List[int]) -> int:\n if nums.index(len(nums))<nums.index(1):return (len(nums)-1-nums.index(len(nums)))+nums.index(1)-1\n else:return (len(nums)-1-nums.index(len(nums)))+nums.index(1)\n \n \n``` | 1 | 0 | ['Array', 'Math', 'Python', 'Python3'] | 0 |
semi-ordered-permutation | Easy C++ Solution - Observation based | easy-c-solution-observation-based-by-baq-49js | \n\n# Code\n\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n \n int n = nums.size();\n if(nums[0] == 1 an | baquer | NORMAL | 2023-06-04T04:29:42.980678+00:00 | 2023-06-04T04:29:42.980711+00:00 | 269 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n \n int n = nums.size();\n if(nums[0] == 1 and nums[nums.size() - 1] == nums.size()) {\n return 0;\n }\n \n int pos1 = -1;\n int pos2 = -1;\n \n for(int i = 0; i < nums.size(); i++) {\n if(nums[i] == 1) {\n pos1 = i;\n }\n if(nums[i] == n) {\n pos2 = i;\n }\n }\n int ans = 0;\n if(pos1 < pos2) {\n ans = pos1 + (n - 1 - pos2); \n }\n \n if(pos1 > pos2) {\n int temp = pos1 - pos2;\n pos1 = pos2;\n pos2 = pos1 + 1;\n \n ans = pos1 + (n-1-pos2) + temp;\n }\n \n return ans;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Simplest solution in java beats 💯✅ | simplest-solution-in-java-beats-by-chint-7yec | 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 | ChinthaLalitha3 | NORMAL | 2023-06-04T04:28:30.856269+00:00 | 2023-06-04T04:28:30.856302+00:00 | 250 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int c=0;\n while(nums[0]!=1){\n for(int i=0;i<nums.length;i++){\n if(nums[i]==1){\n int t=nums[i];\n nums[i]=nums[i-1];\n nums[i-1]=t;\n c++;\n break;\n\n }\n }\n }\n while(nums[nums.length-1]!=nums.length){\n for(int i=0;i<nums.length;i++){\n if(nums[i]==nums.length){\n int t=nums[i];\n nums[i]=nums[i+1];\n nums[i+1]=t;\n c++;\n break;\n\n }\n }\n }\n return c;\n \n \n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Easy C++ Solution | easy-c-solution-by-spidy007-dss3 | \nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int idx,idx2;\n for(int i = 0;i<nums.size();i++){\n | spidy007 | NORMAL | 2023-06-04T04:26:00.548557+00:00 | 2023-06-04T04:26:00.548591+00:00 | 80 | false | ```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int idx,idx2;\n for(int i = 0;i<nums.size();i++){\n if(nums[i]==1) idx=i;\n if(nums[i]==nums.size()) idx2=i;\n }\n int ans=0;\n for(int i = idx;i>=0;i--){\n if(i==0) break;\n swap(nums[i],nums[i-1]);\n ans++;\n }\n for(int i = 0;i<nums.size();i++){\n if(nums[i]==nums.size()) idx2=i;\n }\n for(int i = idx2;i<nums.size();i++){\n if(i==nums.size()-1) break;\n swap(nums[i],nums[i+1]);\n ans++;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
semi-ordered-permutation | explained cpp solution | explained-cpp-solution-by-siya2323-29hg | Certainly! Here\'s an explanation of the code with comments:\n\ncpp\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int | Siya2323 | NORMAL | 2023-06-04T04:20:18.894407+00:00 | 2023-06-04T04:20:18.894436+00:00 | 26 | false | Certainly! Here\'s an explanation of the code with comments:\n\n```cpp\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size(); // Get the size of the input vector\n int s = 0; // Initialize variable s to store the index of value 1\n int e = 0; // Initialize variable e to store the index of value n\n\n // Loop through each element of the vector\n for (int i = 0; i < n; i++) {\n int val = nums[i]; // Get the current element\n\n // Check if the current element is equal to 1 or n\n if (val == 1 || val == n) {\n if (val == 1) {\n s = i; // If the element is 1, update s with the current index\n } else {\n e = i; // If the element is n, update e with the current index\n }\n }\n }\n\n int diff = n - e; // Calculate the difference between n and e\n diff--; // Subtract 1 from diff\n\n int ans = s + diff; // Calculate ans by adding s and diff\n\n // If s is greater than e, subtract 1 from ans\n if (s > e) {\n ans--;\n }\n\n return ans; // Return the final ans value\n }\n};\n```\n\nI hope this helps! Let me know if you have any further questions. | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | semi order permutation | semi-order-permutation-by-nikhithnaini-p6bh | 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 | nikhithnaini | NORMAL | 2023-06-04T04:18:59.206324+00:00 | 2023-06-04T04:18:59.206365+00:00 | 98 | 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)$$ -->o(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->o(1)\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n=nums.size();\n int count=0;\n int i=0;\n while(i<n){\n if(nums[0]==1){\n break;\n }\n if(nums[i]==1&&i!=0){\n swap(nums[i],nums[i-1]);\n count++;\n i--;\n }\n else i++;\n }\n int value=0;\n for(int i=0;i<n;i++){\n if(nums[i]==n)value=i;\n }\n return count+n-value-1;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | O(N) Approach || C++ ✅ | on-approach-c-by-neergx-dg76 | \n# Code\n\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n if(nums[0] == 1 && nums[n-1] = | neergx | NORMAL | 2023-06-04T04:11:47.626050+00:00 | 2023-06-04T04:11:47.626088+00:00 | 17 | false | \n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n if(nums[0] == 1 && nums[n-1] == n)\n return 0;\n int lo = 0, hi = n-1;\n for(int i = 0;i < n; i++){\n if(nums[i] == 1){\n lo = i;\n }\n if(nums[i] == n){\n hi = i;\n }\n }\n int ans;\n if(lo > hi){\n ans = lo + abs(n-1-hi-1);\n }\n else{\n ans = lo + abs(n-1-hi);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | C++||Solutions🚀||Explained Line by Line ✔✔||Easy to understand😊||Beginner Friendly🚀✔✔ | csolutionsexplained-line-by-line-easy-to-dpl2 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe code works based on the intuition that for a semi-ordered permutation, we need to b | shubh-30 | NORMAL | 2023-06-04T04:09:51.221005+00:00 | 2023-06-04T04:09:51.221051+00:00 | 166 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code works based on the intuition that for a semi-ordered permutation, we need to bring the number 1 to the front of the array and the maximum number to the end. The number of elements between these two positions represents the elements that need to be rearranged. By finding the positions of 1 and the maximum number, the code calculates the answer accordingly.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code uses two pointers, l and r, to keep track of the positions of specific numbers in the array.\n\nIt iterates over the elements of the array to find the last occurrences of the numbers 1 and the maximum number.\n\nIt calculates the answer by adding the position of the last occurrence of 1 (l) and the number of elements between the right pointer (r) and the end of the array.\n\nIf there are duplicate elements between the two pointers (l > r), it adjusts the answer by decrementing it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the code is O(n), where n is the size of the input array nums. This is because the code iterates over the array once to find the positions of 1 and the maximum number. The time taken is directly proportional to the size of the input array. Therefore, the time complexity is linear with respect to the input size.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the code is O(1), as it uses a constant amount of extra space to store the left pointer (l), the right pointer (r), and the answer. The space usage does not depend on the size of the input array.\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int l = 0, r = 0;\n for(int i = 0; i < nums.size(); i++) {\n if(nums[i] == 1)\n l = i; // Update the left pointer if the current number is 1\n if(nums[i] == nums.size())\n r = i; // Update the right pointer if the current number is equal to the size of the array\n }\n int ans = l + (nums.size() - 1 - r); // Calculate the answer by adding the left pointer position and the number of elements between the right pointer and the end of the array\n if(l > r)\n ans--; // Adjust the answer if the left pointer is greater than the right pointer\n return ans; // Return the calculated answer\n}\n};\n``` | 1 | 0 | ['C++'] | 1 |
semi-ordered-permutation | Super Easy C++ Solution | super-easy-c-solution-by-lotus18-u2gx | Code\n\nclass Solution \n{\npublic:\n int semiOrderedPermutation(vector<int>& nums) \n {\n int n=nums.size();\n if(nums[0]==1 && nums[n-1]== | lotus18 | NORMAL | 2023-06-04T04:06:20.253408+00:00 | 2023-06-04T04:06:20.253454+00:00 | 22 | false | # Code\n```\nclass Solution \n{\npublic:\n int semiOrderedPermutation(vector<int>& nums) \n {\n int n=nums.size();\n if(nums[0]==1 && nums[n-1]==n) return 0;\n int swaps=0;\n int i=0;\n for(i=0; i<n; i++)\n {\n if(nums[i]==1) break;\n }\n for(int x=i; x>=1; x--)\n {\n swap(nums[x],nums[x-1]);\n swaps++;\n }\n i=0;\n for(i=0; i<n; i++)\n {\n if(nums[i]==n) break;\n }\n for(int x=i; x<n-1; x++)\n {\n swap(nums[x],nums[x+1]);\n swaps++;\n }\n return swaps;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | java simple Solution | java-simple-solution-by-kashi_27-gxeb | 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 | Kashi_27 | NORMAL | 2023-06-04T04:04:48.380961+00:00 | 2023-06-04T04:04:48.381012+00:00 | 19 | 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 semiOrderedPermutation(int[] nums) {\n int temp=0;\n int temp2=0;\n for(int i=0;i<nums.length;i++)\n {\n if(nums[i]==1)\n {\n temp=i;\n }\n else if(nums[i]==nums.length)\n {\n temp2=i;\n }\n }\n int sum=0;\n if(temp2>temp)\n {\n sum=(nums.length-1-temp2)+temp;\n }\n else\n {\n sum=temp+(nums.length-2-temp2);\n }\n \n return sum;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Easy java fast || Brute force | easy-java-fast-brute-force-by-deveshpate-hgt2 | \nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int count=0;\n if(nums[0]==1&& nums[nums.length-1]==nums.length){\n | kanishkpatel1 | NORMAL | 2023-06-04T04:04:45.887259+00:00 | 2023-06-04T04:04:45.887299+00:00 | 47 | false | ```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int count=0;\n if(nums[0]==1&& nums[nums.length-1]==nums.length){\n return 0;\n }\n int indst=0;\n int indend=0;\n for(int i=0;i<nums.length;i++){\n if(nums[i]==1){\n indst =i;\n }\n if(nums[i]==nums.length){\n indend=i;\n }\n }\n if(indst>indend){\n count+=indst+(nums.length-2-indend);\n }\n else{\n count+=indst+nums.length-1-indend;\n }\n return count;\n }\n}\n``` | 1 | 0 | ['Array', 'Java'] | 1 |
semi-ordered-permutation | Index of 1 and n || simple solution || Java | index-of-1-and-n-simple-solution-java-by-xcsc | Code\n\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int first = 0, last = 0, n = nums.length;\n for (int i = 0; i < n; | ByteMaster_ | NORMAL | 2023-06-04T04:04:01.655514+00:00 | 2023-06-04T04:04:01.655561+00:00 | 204 | false | # Code\n```\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int first = 0, last = 0, n = nums.length;\n for (int i = 0; i < n; i++) {\n if(nums[i]==1){\n first=i;\n }\n if(nums[i]==n){\n last=i;\n }\n }\n int min = 0;\n if(first<last)\n min = (first + (n-last-1));\n else\n min = (first + (n-last-2));\n return min;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
semi-ordered-permutation | c++ easy Solution | c-easy-solution-by-madhukeshsingh-f48u | The given code represents a solution in C++ for the problem of finding the number of operations required to transform a given permutation of integers into a sem | MadhukeshSingh | NORMAL | 2023-06-04T04:02:44.644390+00:00 | 2023-06-04T04:51:46.914346+00:00 | 78 | false | The given code represents a solution in C++ for the problem of finding the number of operations required to transform a given permutation of integers into a semi-ordered permutation.\nThe variable n is assigned the size of the nums vector, which represents the length of the permutation.\n\nThe variables s and e are initialized to 0. These variables will track the indices of the first occurrence of 1 and the last occurrence of n, respectively\n\nAfter the loop, the variable diff is calculated as the difference between the total length of the permutation n and the index of the last occurrence of n e. This represents the number of elements that need to be moved to the left to transform the permutation into a semi-ordered permutation.\n\nThe variable diff is decremented by 1 to exclude the element at index e from the count of operations since it is already in its correct position.\n\nThe variable ans is calculated by adding the index of the first occurrence of 1 s and the adjusted diff. This represents the final position of the last element in the semi-ordered permutation.\n\nIf s is greater than e, it means that the first occurrence of 1 appears after the last occurrence of n. In this case, ans is decremented by 1 to account for this overlap between the two elements.\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n int n = nums.size();\n int s=0;\n int e=0;\n for (int i = 0 ; i<n;i++){\n int val = nums[i];\n if(val ==1 ||val==n){\n if (val == 1){\n s = i;\n }\n else {\n e = i;\n }\n }\n }\n int diff = n - e;\n diff--;\n int ans = s + diff;\n if(s>e){\n ans--;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Simple JS Code!!! | simple-js-code-by-abhich930-2vim | IntuitionLets find out the index of 1 and n then we can follow the linear equations to find the number of total swaps needed.ApproachlengthOfNums: Stores the le | abhich930 | NORMAL | 2025-04-09T10:54:18.805274+00:00 | 2025-04-09T10:54:18.805274+00:00 | 2 | false | # Intuition
Lets find out the index of 1 and n then we can follow the linear equations to find the number of total swaps needed.
# Approach
lengthOfNums: Stores the length of the nums array.
x: Will store the index of the number 1 in the nums array.
y: Will store the index of the largest number in the array, which is lengthOfNums (the number equal to the array length).
swap: Will store the calculated result, which is the final value returned by the function.
The loop iterates through each index i of the nums array.
If the value at nums[i] is 1, it assigns the index i to x.
If the value at nums[i] is equal to lengthOfNums, it assigns the index i to y.
Conditional (ternary) operator that calculates the value of swap:
The expression calculates the number of "swaps" (or steps) needed to move 1 and the largest number (lengthOfNums) to their correct positions in an almost sorted sequence.
The formula used for swap:
x: the index of 1 in the array.
y: the index of the largest number (lengthOfNums).
lengthOfNums - y - 1: the number of elements from the largest number to the end of the array.
x + (lengthOfNums - y - 1): the total number of steps to move both 1 and lengthOfNums to their correct positions.
The subtraction by 1 (- 1) if x > y is needed to avoid over-counting when x is ahead of y.
Finally, the swap value is returned, which represents the number of "swaps" or steps needed to semi-order the permutation.
# Complexity
- Time complexity:
O(N)
- Space complexity:
O(1)
# Code
```javascript []
/**
* @param {number[]} nums
* @return {number}
*/
var semiOrderedPermutation = function(nums) {
const lengthOfNums = nums.length
let x
let y
let swap
for(let i = 0; i<lengthOfNums; i++){
if(nums[i] === 1){
x = i
}
if(nums[i] === lengthOfNums){
y = i
}
}
x > y ? swap = x + (lengthOfNums-y-1) - 1 : swap = x + (lengthOfNums-y-1)
return swap
};
``` | 0 | 0 | ['JavaScript'] | 0 |
semi-ordered-permutation | Easy peasy solution | easy-peasy-solution-by-abhinav_gupta0007-1hz9 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Abhinav_Gupta0007 | NORMAL | 2025-04-03T04:55:55.588946+00:00 | 2025-04-03T04:55:55.588946+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int semiOrderedPermutation(vector<int>& nums) {
int n=nums.size();
int anchuu=0;
// taking 1 to 0th index
while(nums[0]!=1)
{
for(int i=1;i<n;i++)
{
if(nums[i]==1)
{
swap(nums[i],nums[i-1]);
anchuu++;
break;
}
}
}
//taking n to n-1th index
while(nums[n-1]!=n)
{
for(int i=1;i<n-1;i++)
{
if(nums[i]==n)
{
swap(nums[i],nums[i+1]);
anchuu++;
break;
}
}
}
return anchuu;
}
};
``` | 0 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Easy solution in java (O(n)) | easy-solution-in-java-on-by-kumarakash-rpzp | IntuitionTake care of 1st and last value where it is present if suppose of index of 1 is i and index of n is j.
and if i<j it means just we need to move 1 to 0 | kumarakash | NORMAL | 2025-04-02T08:17:58.621496+00:00 | 2025-04-02T08:17:58.621496+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Take care of 1st and last value where it is present if suppose of index of 1 is i and index of n is j.
and if i<j it means just we need to move 1 to 0 position and j to nth position.
else
(just we need to move 1 to 0 position and j to nth position)-1
As 1 will be common step for both.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1)
# Code
```java []
class Solution {
public int semiOrderedPermutation(int[] nums) {
int indexOfOne = -1;
int indexOfNumsLength = nums.length;
for(int i=0;i<nums.length;i++) {
if(nums[i]==1) {
indexOfOne = i;
}
if(nums[i]==nums.length) {
indexOfNumsLength = i;
}
}
if(indexOfOne<indexOfNumsLength) {
return indexOfOne + (nums.length-indexOfNumsLength-1);
}
else {
return indexOfOne + (nums.length-indexOfNumsLength-1) -1;
}
}
}
``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Easy Solution Beats 100% (C++) | easy-solution-beats-100-c-by-yl263258-w791 | IntuitionFirst, find the indexes of the elements 1 and n, where n is the length of the array. Then, find the distance from index 0 to the index of 1, and the di | liam4021 | NORMAL | 2025-03-27T14:46:36.822100+00:00 | 2025-03-27T14:46:36.822100+00:00 | 3 | false | # Intuition
First, find the indexes of the elements $1$ and $n$, where $n$ is the length of the array. Then, find the distance from index $0$ to the index of $1$, and the distance between index $n$ and the index of $n$.
# Approach
One way to solve this is by iterating over the array to find the indexes of $1$ and $n$. Once found, loop over the array a second time, this time swapping the elements until the array is semi-ordered, counting the amount of swaps and returning it. This results in $O(n)$ time complexity and takes constant space.
This solution works just fine, however, there is a few optimizations we can make. First, we can break out of the searching loop early once we have found both indexes. More importantly, we can completely avoid the second loop by just calculating the amount of moves it would take, rather than counting. To do so, add the distances from index $0$ to the index of $1$ and index $n-1$ to the index of $n$. Its important to remember that if the index of $n$ comes before the index of $1$, they either are or will be adjacent to each other while swapping elements. This means you can swap them both at once, taking once less move.
# Complexity
- Time complexity:
$$O(n)$$
- Space complexity:
$$O(1)$$
# Code
```cpp []
class Solution {
public:
int semiOrderedPermutation(vector<int>& nums) {
const int n = nums.size();
// in this case the array is already semi ordered
if(nums[0] == 1 && nums[n-1] == n) return 0;
int indexN = -1; // index of n
int index1 = -1; // index of 1
// search for indexes
for(int i = 0; i < n; ++i) {
int num = nums[i];
if(num == 1)
index1 = i;
if(num == n)
indexN = i;
// break early once both have been found
if(indexN != -1 && index1 != -1)
break;
}
int moves = 0;
moves += (n - indexN - 1); // subtract 1 here since you want the index n-1, not n
moves += (index1);
// in this case they are / will be adjacent,
// so you can make one less move by swapping both at once
if(indexN < index1)
--moves;
return moves;
}
};
```
This is my first solution, so please provide feedback! | 0 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Simple solution in Java. Beats 100 % | simple-solution-in-java-beats-100-by-kha-5yip | Complexity
Time complexity:
O(n)
Space complexity:
O(1)
Code | Khamdam | NORMAL | 2025-03-21T15:08:16.715041+00:00 | 2025-03-21T15:08:16.715041+00:00 | 2 | false | # Complexity
- Time complexity:
O(n)
- Space complexity:
O(1)
# Code
```java []
class Solution {
public int semiOrderedPermutation(int[] nums) {
int n = nums.length;
int min = nums[0];
int max = nums[0];
for (int num : nums) {
min = Math.min(min, num);
max = Math.max(max, num);
}
int minIndex = 0;
int maxIndex = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == min) {
minIndex = i;
}
if (nums[i] == max) {
maxIndex = i;
}
}
return minIndex < maxIndex ? (minIndex + (n - maxIndex - 1)) : (minIndex + (n - maxIndex - 1) - 1);
}
}
``` | 0 | 0 | ['Array', 'Java'] | 0 |
semi-ordered-permutation | 🔥✅✅ Dart Solution 📌📌 || with Explanation 👌👌 | dart-solution-with-explanation-by-nosar-9vef | Solution
Find the indices of 1 and n: Locate the positions of 1 and n in the array.
Calculate the number of swaps:
The number of swaps required to move 1 to th | NosaR | NORMAL | 2025-03-21T07:50:14.587362+00:00 | 2025-03-21T07:50:14.587362+00:00 | 1 | false | # Solution
1. **Find the indices of `1` and `n`:** Locate the positions of `1` and `n` in the array.
2. **Calculate the number of swaps:**
- The number of swaps required to move `1` to the first position is equal to its current index.
- The number of swaps required to move `n` to the last position is equal to `(n - 1) - its current index`.
3. **Adjust for Overlap:** If `1` is to the right of `n`, moving `1` to the first position will have already moved `n` one step closer to the last position. Therefore, we need to subtract `1` from the total number of swaps in this case.
### Time Complexity:
- **Finding the indices of `1` and `n`:** This takes `O(n)` time.
- **Calculating the number of swaps:** This is done in constant time `O(1)`.
- **Overall Time Complexity:** `O(n)`.
```dart
class Solution {
int semiOrderedPermutation(List<int> nums) {
int n = nums.length;
int indexOfOne = nums.indexOf(1);
int indexOfN = nums.indexOf(n);
int swapsForOne = indexOfOne;
int swapsForN = (n - 1) - indexOfN;
if (indexOfOne > indexOfN) {
return swapsForOne + swapsForN - 1;
} else {
return swapsForOne + swapsForN;
}
}
}
``` | 0 | 0 | ['Dart'] | 0 |
semi-ordered-permutation | Python3 Program | python3-program-by-vaarshik_pemmasani-xe2c | Code | VAARSHIK_PEMMASANI | NORMAL | 2025-02-22T18:25:43.987819+00:00 | 2025-02-22T18:25:43.987819+00:00 | 2 | false |
# Code
```python3 []
class Solution:
def semiOrderedPermutation(self, nums: List[int]) -> int:
count = 0
for i in range(len(nums)):
if nums[i] == 1:
while i > 0:
nums[i], nums[i - 1] = nums[i - 1], nums[i]
count += 1
i -= 1
break
for i in range(len(nums)):
if nums[i] == len(nums):
while i < len(nums) - 1:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
count += 1
i += 1
break
return count
``` | 0 | 0 | ['Python3'] | 0 |
semi-ordered-permutation | EASY BY PRINCE GANESHWALA | easy-by-prince-ganeshwala-by-princeganes-5bfq | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | PrinceGaneshwala | NORMAL | 2025-02-19T16:23:41.480151+00:00 | 2025-02-19T16:23:41.480151+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int semiOrderedPermutation(int[] nums) {
int length=nums.length;
int minelementindex=-1;
int maxelementindex=-1;
for(int i=0;i<length;i++)
{
if(nums[i]==1)
{
minelementindex=i;
}
if(nums[i]==length)
{
maxelementindex=i;
}
}
int ans=0;
if(minelementindex<maxelementindex)
{
ans+=minelementindex;
ans+=length-1-maxelementindex;
}
else if(maxelementindex<minelementindex)
{
ans+=length-1-maxelementindex;
ans+=minelementindex-1;
}
return ans;
}
}
``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | [C++] Simple Solution | c-simple-solution-by-samuel3shin-ng0j | Code | Samuel3Shin | NORMAL | 2025-01-27T15:54:12.494146+00:00 | 2025-01-27T15:54:12.494146+00:00 | 2 | false | # Code
```cpp []
class Solution {
public:
int semiOrderedPermutation(vector<int>& A) {
int ans = 0;
int idx = 0;
for(int i=0; i<A.size(); i++) {
if(A[i] == 1) {
idx = i;
break;
}
ans++;
}
while(A[0] != 1) {
int tmp = A[idx];
A[idx] = A[idx-1];
A[idx-1] = tmp;
idx--;
}
idx = 0;
for(int i=0; i<A.size(); i++) {
if(A[i] == A.size()) {
idx = i;
break;
}
}
while(A[A.size()-1] != A.size()) {
int tmp = A[idx];
A[idx] = A[idx+1];
A[idx+1] = tmp;
idx++;
ans++;
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
semi-ordered-permutation | semiOrderedPermutation: easy O(n) solution. BEAT 100%. ✅ | semiorderedpermutation-easy-on-solution-8s4am | IntuitionThe problem involves making the given permutation semi-ordered with a minimum number of adjacent swaps. By finding the positions of 1 and n, we can cal | rTIvQYSHLp | NORMAL | 2025-01-24T08:20:18.780428+00:00 | 2025-01-24T08:20:18.780428+00:00 | 2 | false | # Intuition
The problem involves making the given permutation semi-ordered with a minimum number of adjacent swaps. By finding the positions of 1 and n, we can calculate the necessary swaps.
# Approach
1. Locate the positions of the numbers 1 and n in the permutation.
2. Calculate the number of swaps needed by considering their initial positions and the required final positions.
3. If the position of 1 is after n, decrement the position of 1 to account for their shift.
4. Sum the moves needed to place 1 at the start and n at the end.
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(1)
# Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
int indexOne, indexN;
for(int i=0;i<numsSize;i++){
if(nums[i]==1) indexOne=i;
else if(nums[i]==numsSize) indexN=i;
}
if(indexOne>indexN) indexOne--;
return indexOne + numsSize-1-indexN;
}
``` | 0 | 0 | ['Array', 'C', 'Simulation'] | 0 |
semi-ordered-permutation | Track min/max value ids | track-minmax-value-ids-by-linda2024-enm7 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | linda2024 | NORMAL | 2025-01-21T18:17:08.752880+00:00 | 2025-01-21T18:17:08.752880+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public int SemiOrderedPermutation(int[] nums) {
int len = nums.Length;
int minIdx = -1, maxIdx = -1;
for(int i = 0; i < len; i++)
{
if(minIdx < 0 || minIdx >= 0 && nums[minIdx] > nums[i])
minIdx = i;
if(maxIdx < 0 || maxIdx >= 0 && nums[maxIdx] < nums[i])
maxIdx = i;
}
return minIdx + (len-1-maxIdx) - (minIdx > maxIdx ? 1 : 0);
}
}
``` | 0 | 0 | ['C#'] | 0 |
semi-ordered-permutation | Semi ordered permutation in C | semi-ordered-permutation-in-c-by-praveen-ot4a | Code | praveenkesava | NORMAL | 2025-01-21T09:42:35.657970+00:00 | 2025-01-21T09:42:35.657970+00:00 | 1 | false |
# Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
int index1, index2;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == 1)
index1 = i;
if (nums[i] == numsSize)
index2 = i;
}
if (index1 < index2)
return index1 + ((numsSize - 1) - index2);
return index1 + (((numsSize - 1) - index2)) - 1;
}
``` | 0 | 0 | ['C'] | 0 |
semi-ordered-permutation | Easy (with comments) | easy-with-comments-by-vamsi0874-mkil | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | vamsi0874 | NORMAL | 2025-01-21T06:53:37.772896+00:00 | 2025-01-21T06:53:37.772896+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```typescript []
function semiOrderedPermutation(nums: number[]): number {
const n = nums.length;
// Find the indices of 1 and n
const index1 = nums.indexOf(1);
const indexN = nums.indexOf(n);
// Calculate swaps needed for both
if (index1 < indexN) {
// If `1` is to the left of `n`, no overlap
return index1 + (n - 1 - indexN);
} else {
// If `1` is to the right of `n`, overlap occurs
return index1 + (n - 1 - indexN) - 1;
}
}
``` | 0 | 0 | ['TypeScript'] | 0 |
semi-ordered-permutation | Java beats 100%! very fast solution with explanation | java-beats-100-very-fast-solution-with-e-54cn | IntuitionWe need to move min and max elements to the start and to the end of the array.ApproachWe iterate over the array and search for max element. Then, we mo | had0uken | NORMAL | 2025-01-20T14:26:50.201295+00:00 | 2025-01-20T14:26:50.201295+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need to move min and max elements to the start and to the end of the array.
# Approach
<!-- Describe your approach to solving the problem. -->
We iterate over the array and search for max element. Then, we move element right and increment result var. After that we decrement index i and repeat the operation. We do it until the max element is set to last position in the array. Then, we do the same with the minimal element = 1, and move it to the left. We do it until element = 1 (the minimal element) is set to 0 index of the array. Then, we just return the result var.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int semiOrderedPermutation(int[] nums) {
int result = 0;
for(int i =0;i<nums.length-1;i++)
{
if(nums[nums.length-1]==nums.length)break;
if(nums[i]==nums.length) {
int temp = nums[i + 1];
nums[i+1]=nums[i];
nums[i]=temp;
i=-1;
result++;
}
}
for(int i=1;i<nums.length;i++)
{
if(nums[0]==1)break;
if(nums[i]==1){
int temp = nums[i-1];
nums[i-1]=nums[i];
nums[i]=temp;
i=0;
result++;
}
}
return result;
}
}
``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Easy solution | easy-solution-by-akshayya_ru-ldrt | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Akshayya_RU | NORMAL | 2025-01-16T14:30:20.423886+00:00 | 2025-01-16T14:30:20.423886+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int semiOrderedPermutation(vector<int>& nums) {
int n=nums.size();
int l=find(nums.begin(),nums.end(),1)-nums.begin(),r=find(nums.begin(),nums.end(),n)-nums.begin();
if(l<r)
return l+(n-1-r);
return l+(n-1-r)-1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Solution in C | solution-in-c-by-mariya_ashile-ztwj | Code | Mariya_Ashile | NORMAL | 2025-01-13T10:15:34.222749+00:00 | 2025-01-13T10:15:34.222749+00:00 | 2 | false |
# Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
int n1=-1,n2=-1;
for(int i=0;i<numsSize;i++)
{
if(nums[i]==1) n1=i;
else if(nums[i]==numsSize) n2=i;
if(n1!=-1 && n2!=-1) break;
}
return ((n1<n2) ? (n1 - n2 + numsSize-1) : (n1 - n2 + numsSize-2));
}
``` | 0 | 0 | ['C'] | 0 |
semi-ordered-permutation | Solution in C | solution-in-c-by-vishalkannan_070-ls3l | Approach
Iterate through the array to find the index of 1and index of last element.
Compare the indices "a" and "b" to determine if they are in the correct orde | VishalKannan_070 | NORMAL | 2025-01-09T17:25:54.269569+00:00 | 2025-01-09T17:25:54.269569+00:00 | 3 | false | # Approach
- Iterate through the array to find the index of `1`and index of last element.
- Compare the indices "a" and "b" to determine if they are in the correct order `(a < b)`
- If 1 is before numsSize, the number of swaps is the sum of "a" and the distance from "b" to the end of the array.
- If 1 is after numsSize, subtract one extra swap to avoid double-counting.
- The function returns the calculated number of swaps.
# Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
int a, b;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == 1)
a = i;
if (nums[i] == numsSize)
b = i;
}
if (a < b)
return a + ((numsSize - 1) - b);
return a + (((numsSize - 1) - b)) - 1;
}
``` | 0 | 0 | ['Array', 'C'] | 0 |
semi-ordered-permutation | 2717. Semi-Ordered Permutation | 2717-semi-ordered-permutation-by-g8xd0qp-acaq | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-06T17:39:10.252753+00:00 | 2025-01-06T17:39:10.252753+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums
* @return {number}
*/
var semiOrderedPermutation = function(nums) {
// Find the index of 1 and n
const n = nums.length;
const indexOf1 = nums.indexOf(1);
const indexOfN = nums.indexOf(n);
// Number of swaps to move 1 to the front
let swaps = indexOf1;
// Number of swaps to move n to the end
// If n is before 1 in the list, we need to subtract one swap to avoid double counting
if (indexOfN > indexOf1) {
swaps += (n - indexOfN - 1);
} else {
swaps += (n - indexOfN - 1) - 1;
}
return swaps;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
semi-ordered-permutation | Semi Ordered Permutation Solution in C | semi-ordered-permutation-solution-in-c-b-b6om | IntuitionApproachComplexity
Time complexity:
o(n)
Space complexity:
O(1)
Code | Darsan20 | NORMAL | 2025-01-05T17:34:55.484518+00:00 | 2025-01-05T17:34:55.484518+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
o(n)
- Space complexity:
O(1)
# Code
```c []
int semiOrderedPermutation(int* nums, int numsSize) {
int one_index = 0, n_index = 0;
for (int i=0;i<numsSize;i++)
{
if (nums[i] == 1)
one_index = i;
if (nums[i] == numsSize)
n_index = i;
}
if (one_index < n_index)
return one_index + (numsSize - n_index - 1);
else
return one_index + (numsSize - n_index - 1)-1;
}
``` | 0 | 0 | ['C'] | 0 |
semi-ordered-permutation | Semi-ordered-permutation(In Java with Explaination and Example) | semi-ordered-permutationin-java-with-exp-85t0 | Explaination
Find the positions of 1 and n in the array (x and y).
The position of 1 in nums (let's call it x).
The position of n in nums (let's call it y).
Cal | nishanthinimani525 | NORMAL | 2025-01-03T09:15:40.389678+00:00 | 2025-01-03T09:15:40.389678+00:00 | 11 | false | # Explaination
- Find the positions of 1 and n in the array (x and y).
The **position of 1** in nums (let's call it x).
The **position of n** in nums (let's call it y).
- Calculate the swaps as:
If x < y: Total swaps = x + (n - 1 - y).
If x > y: Total swaps = x + (n - 1 - y) - 1.
# Examples
Input: nums = [2, 1, 4, 3]
pos1 = 1 (position of 1).
posN = 3 (position of 4).
Calculations:
Swaps to move 1 to the start: pos1 = 1.
Swaps to move n to the end: (n - 1 - posN) = 4 - 1 - 3 = 0.
Total swaps: 1 + 0 = 2.
**Output: 2.**
# Code
```java []
class Solution {
public int semiOrderedPermutation(int[] nums) {
int n = nums.length;
int x = nums[0],y=nums[0];
for(int i=0;i<n;i++){
if(nums[i]==1){
x=i;
}
if(nums[i]==n){
y=i;
}
}
if(x<y){
return x+(n-y-1);
}
else{
return x+(n-y-1)-1;
}
}
}
``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Kotlin Straightforward Solution | kotlin-straightforward-solution-by-curen-l4ae | Code | curenosm | NORMAL | 2025-01-01T16:48:03.764755+00:00 | 2025-01-01T16:48:03.764755+00:00 | 4 | false | # Code
```kotlin []
class Solution {
fun semiOrderedPermutation(nums: IntArray): Int {
val (indexOne, indexN) = arrayOf(nums.indexOf(1), nums.indexOf(nums.size))
val res = indexOne + (nums.size - indexN - 1)
return res - if (indexOne >= indexN) 1 else 0
}
}
``` | 0 | 0 | ['Kotlin'] | 0 |
semi-ordered-permutation | Easy soln. | easy-soln-by-mamthanagaraju1-q6kw | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | mamthanagaraju1 | NORMAL | 2025-01-01T12:51:51.431787+00:00 | 2025-01-01T12:51:51.431787+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int semiOrderedPermutation(vector<int>& nums) {
int x=0,y=0;
int n= nums.size();
for(int i=0;i<nums.size();i++){
if(nums[i]==1){
x=i;
}
if(nums[i]==n){
y=i;
}
}
return x<y?x+(n-y-1):x+(n-y-1)-1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
semi-ordered-permutation | Easy Solution in Java | easy-solution-in-java-by-sathurnithy-fap8 | Code | Sathurnithy | NORMAL | 2024-12-31T10:27:23.756980+00:00 | 2024-12-31T10:27:23.756980+00:00 | 7 | false |
# Code
```java []
class Solution {
public int semiOrderedPermutation(int[] nums) {
if(nums[0] == 1 && nums[nums.length - 1] == nums.length) return 0;
int posOne = -1, posN = -1;
for(int i=0; i<nums.length; i++){
if(nums[i] == 1)
posOne = i;
else if(nums[i] == nums.length)
posN = i;
if((posOne != -1) && (posN != -1))
break;
}
int swap = 0;
if(posOne > posN)
swap--;
swap += posOne + (nums.length - 1 - posN);
return swap;
}
}
``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | Submission beat 100% of other submissions' runtime. | submission-beat-100-of-other-submissions-qgyw | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Vishva-mitra | NORMAL | 2024-12-26T15:25:19.664315+00:00 | 2024-12-26T15:25:19.664315+00:00 | 8 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int semiOrderedPermutation(int[] nums) {
int firstIdx = 0;
int lastIdx = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
firstIdx = i;
}
if (nums[i] == nums.length) {
lastIdx = i;
}
}
return lastIdx > firstIdx ? (nums.length - 1 - lastIdx + firstIdx)
: (nums.length - 1 - lastIdx + firstIdx) - 1;
}
}
``` | 0 | 0 | ['Java'] | 0 |
semi-ordered-permutation | One Line | one-line-by-mrn3088-qhww | null | mrn3088 | NORMAL | 2024-12-10T21:26:53.343795+00:00 | 2024-12-10T21:26:53.343795+00:00 | 7 | false | \n# Complexity\n- Time complexity: O(N) \nNotice here we used the := operator. \n- Space complexity: O(1)\n\n# Code\n```python3 []\nclass Solution:\n def semiOrderedPermutation(self, nums: List[int]) -> int:\n return max(-1 + 2 * ((i := min((t for t in enumerate(nums)), key=lambda x:x[1])[0]) - (j := max((t for t in enumerate(nums)), key=lambda x:x[1])[0])), 0) + min(i, j) + len(nums) - max(i, j) - 1\n``` | 0 | 0 | ['Python3'] | 0 |
semi-ordered-permutation | Go golang clean solution | go-golang-clean-solution-by-leaf_peng-tst0 | go\n\nfunc semiOrderedPermutation(nums []int) int {\n var i, j int\n n := len(nums)\n for idx, num := range nums {\n if num == 1 {\n | leaf_peng | NORMAL | 2024-11-24T15:04:02.329495+00:00 | 2024-11-24T15:04:02.329529+00:00 | 5 | false | ```go\n\nfunc semiOrderedPermutation(nums []int) int {\n var i, j int\n n := len(nums)\n for idx, num := range nums {\n if num == 1 {\n i = idx\n } else if num == n {\n j = idx\n }\n }\n if i < j {\n return i + (n - j - 1)\n }\n return i + (n - j - 1) - 1\n}\n``` | 0 | 0 | ['Go'] | 0 |
semi-ordered-permutation | beats 100% .Simple approach | beats-100-simple-approach-by-kumardixit8-3dy2 | 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 | kumardixit88 | NORMAL | 2024-11-19T02:38:35.737631+00:00 | 2024-11-19T02:38:35.737657+00:00 | 3 | 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```java []\nclass Solution {\n public int semiOrderedPermutation(int[] nums) {\n int cost = 0 ;\n int n = nums.length;\n int min = Integer.MAX_VALUE;\n int max = Integer.MIN_VALUE;\n int minPos = -1;\n int maxPos = -1;\n for(int i=0;i<n;i++){\n\n if(nums[i]<min){\n min = nums[i];\n minPos = i;\n }\n\n if(nums[i]>max){\n max = nums[i];\n maxPos = i;\n }\n \n }\n if(minPos>maxPos){\n return (minPos-0) + (n-maxPos-1) -1;\n }\n return (minPos-0) + (n-maxPos-1);\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.