question_id
int64 700k
876k
| question_title
stringlengths 3
81
| question_content
stringlengths 131
2.51k
| dataset
stringclasses 1
value | difficulty
stringclasses 3
values | java
dict | python
dict | test_cases
stringlengths 200
208M
|
|---|---|---|---|---|---|---|---|
703,988
|
Sum of elements in a matrix
|
Given a non null integer matrix Grid of dimensions NxM.Calculate the sum of its elements.
Examples:
Input:
N=2,M=3
Grid=
[[1,0,1],
[-8,9,-2]]
Output:
1
Explanation:
The sum of all elements of the matrix is
(1+0+1-8+9-2)=1.
Input:
N=3,M=5
Grid=
[[1,0,1,0,1],
[0,1,0,1,0],
[-1,-1,-1,-1,-1]]
Output:
0
Explanation:
The sum of all elements of the matrix are
(1+0+1+0+1+0+1+0+1+0-1-1-1-1-1)=0.
Constraints:
1<=N,M<=1000
-1000<=Grid[i][j]<=1000
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1619347516,
"func_sign": [
"int sumOfMatrix(int N, int M, int[][] Grid)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String[] S = read.readLine().split(\" \");\n int N = Integer.parseInt(S[0]);\n int M = Integer.parseInt(S[1]);\n int Grid[][] = new int[N][M];\n for (int i = 0; i < N; i++) {\n String[] s = read.readLine().split(\" \");\n for (int j = 0; j < M; j++) Grid[i][j] = Integer.parseInt(s[j]);\n }\n Solution ob = new Solution();\n System.out.println(ob.sumOfMatrix(N, M, Grid));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // Function to find the sum of all elements in a matrix\n int sumOfMatrix(int N, int M, int[][] Grid) {\n // variable to store the sum\n int sum = 0;\n // loop through each row of the matrix\n for (int i = 0; i < N; i++)\n // loop through each column of the matrix\n for (int j = 0; j < M; j++)\n // add the current element to the sum\n sum += Grid[i][j];\n // return the final sum\n return sum;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n int sumOfMatrix(int N, int M, int[][] Grid) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619347516,
"func_sign": [
"sumOfMatrix(self,N,M,Grid)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, M = map(int, input().strip().split(' '))\n Grid = [[0 for i in range(M)] for j in range(N)]\n for i in range(N):\n s = list(map(int, input().strip().split(' ')))\n for j in range(M):\n Grid[i][j] = s[j]\n ob = Solution()\n print(ob.sumOfMatrix(N, M, Grid))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find the sum of all elements in a matrix.\n def sumOfMatrix(self, N, M, Grid):\n sum = 0\n for i in range(N):\n for j in range(M):\n # Adding each element of the matrix to the sum.\n sum += Grid[i][j]\n return sum\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def sumOfMatrix(self,N,M,Grid):\n #code here"
}
|
eJxrYJm6h4UBDCK2AhnR1UqZeQWlJUpWCkqGMXmGCiDCwMBASUdBKbWiIDW5JDUlPr+0BKYEKBWTVxeTp1Sro4BFqy4evbp4NBspGEHsVYAogjNxmGVCwCiwXQpQG5E4uJyGyzx8mjCUEqcO6ERjBeOYPAMFIESlcBiAy6dgYxB+U0D2LbL/0ZSQGLVEeh8lEnXRnUKiz7AlB/yONyaUMElygi4JsW4AdyHRAWWoYEBeNtM1RAoPYh0ITSRk6ATpIi9DYTMKf+mAGQM4FcZO0QMArx1d3A==
|
701,873
|
Count subsequences of type a^i, b^j, c^k
|
Given a string S, the task is to count number of subsequences of the form a**ib**jc**k, where i >= 1, j >=1 and k >= 1.
Examples:
Input:
S = "abbc"
Output:
3
Explanation:
Subsequences are abc, abc and abbc.
Input:
S = "abcabc"
Output:
7
Explanation:
Subsequences are abc, abc,
abbc, aabc abcc, abc and abc.
Constraints:
1 <= |S| <= 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1618167386,
"func_sign": [
"public int fun(String s)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n\tpublic static void main (String[] args) {\n\t\t\n\t\tScanner sc = new Scanner (System.in);\n\t\tint t = Integer.parseInt(sc.next());\n\t\t\n\t\twhile(t>0)\n\t\t{\n\t\t String s = sc.next();\n\t\t \n\t\t Solution T = new Solution();\n\t\t System.out.println(T.fun(s));\n\t\t \n\t\t t--;\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730267710,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public int fun(String s)\n {\n // Write your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618167386,
"func_sign": [
"fun(self,s)"
],
"initial_code": "# Initial Template for Python 3\n\n# Position this line where user code will be pasted.\n\nt = int(input())\n\nfor _ in range(t):\n s = input()\n print(Solution().fun(s))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def fun(self, s):\n # initialize sub_sequences list with initial values\n sub_sequences = [0, 0, 0]\n i = len(s) - 1\n while i >= 0:\n # if current character is 'c', update sub_sequences[2] based on formula\n if s[i] is 'c':\n sub_sequences[2] = (2 * sub_sequences[2] + 1) % 1000000007\n # if current character is 'b', update sub_sequences[1] based on formula\n elif s[i] is 'b':\n sub_sequences[1] = (2 * sub_sequences[1] +\n sub_sequences[2]) % 1000000007\n # if current character is 'a', update sub_sequences[0] based on formula\n elif s[i] is 'a':\n sub_sequences[0] = (2 * sub_sequences[0] +\n sub_sequences[1]) % 1000000007\n # decrement i\n i = i - 1\n # return the final value of sub_sequences[0]\n return sub_sequences[0]\n",
"updated_at_timestamp": 1730267710,
"user_code": "#User function Template for python3\n\nclass Solution:\n def fun(self,s):\n # code here"
}
|
eJylVc1OhDAQ9mB8DtLzxtAfttQnMRFj6MjBC+6BTUyMxofQV/TmO9jC0izIV0CGScuBmX7zzTfl4/Lr5+qitdtv93L3yp7qw7FhNwnjRV06s87IGdslrHo5VNRUjw/Px+b0lZQ6K+r3omZvu2QYTdaWFLzbLLkVpOLacJTKmQfiAYHoFIT6Coj8wa2D6H2qUbz1sM8KsZEKpJIQRjAbjIKhhEoIpXJlIMVlR2mHknp88WK10CnEaWPPGu5Fy92k98D96tB67H5DcJXo0O4zJLVxf4aOyM0NbtefriMpYDUojdo2Gq1VkpjhmqbJXsZ0zk8TKDhiOmgB8bFZN0MRzot8+3FnpYx6u2L2UXJaUsPgjlwo3wh5s3P8jxZuwxS7/UCuTEpjUjzzk78X3B8t+0T3n9e/0exlcw==
|
703,537
|
Even Decimal Binary String
|
Given a binary string of size N,you have to return the number ofsubstrings that haveeven value in its decimal form.Note: Most significant bit is on the right end side. For example - binary representation of 6 is 011.
Examples:
Input:
N = 3
S = "101"
Output:
2
Explanation:
Substrings in S:
1, 10, 101, 0, 01, 1
Corresponding decimal values:
1, 1, 5, 0, 2, 1
There are only 2 even decimal valued
substrings.
Input:
N = 5
S = "10010"
Output:
8
Explanation:
Substrings in S:
1, 0, 0, 1, 0, 10, 00, 01, 10, 100,
001, 010, 1001, 0010 and 10010
Corresponding decimal Values are:
1, 0, 0, 1, 0, 1, 0, 2, 1, 1, 4, 2,
9, 4 ans 9
There are 8 decimal values which are even.
Constraints:
1 ≤ T ≤1000
1 ≤N ≤10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static long evenDecimalSubStr(int N, String S)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n//Position this line where user code will be pasted.\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0)\n {\n int N = Integer.parseInt(read.readLine());\n String s = read.readLine().trim();\n Solution ob = new Solution();\n System.out.println(ob.evenDecimalSubStr(N, s));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static long evenDecimalSubStr(int N, String S) {\n long result = 0;\n for (int i = 0; i < N; i++) {\n // substring started with '0'\n if (S.charAt(i) == '0') {\n // increment result by (n-i)\n // because all substring which\n // are generate by this character\n // produce even decimal value.\n result += (N - i);\n }\n }\n return result;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution{\n static long evenDecimalSubStr(int N, String S){\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"evenDecimalSubStr(self, N, S)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N = int(input())\n S = input()\n ob = Solution()\n print(ob.evenDecimalSubStr(N, S))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n def evenDecimalSubStr(self, N, S):\n result = 0\n for i in range(0, N):\n # substring started with '0'\n if (S[i] == '0'):\n # increment result by (n-i)\n # because all substring which are generate by\n # this character produce even decimal value.\n result += (N - i)\n return result\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def evenDecimalSubStr (self, N, S):\n # code here"
}
|
eJxrYJn6goUBDCIeAhnR1UqZeQWlJUpWCkqGMXlAZKCko6CUWlGQmlySmhKfX1qCkK2LyVOq1VHA0GKIQ4sBDi1GQFtwWWOMW48hqfYYGoA0wQAZmg3gAIdmU1N8VhvAIA7dRvh0wzXjcrgxVpfjsgvTElNo4JASLgZ4kwi6YuLdguphhNtI9T0kocTEAHXidSlxmpHTADmpB6uHSPcRXncRldBwmQxyFdhcMnIwmntiMBI9FUMuJsYALT8Smzpip+gBAHpnfWs=
|
701,265
|
Transpose of Matrix
|
Write a program to find the transpose of a square matrixof size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.Example 1:
Examples:
Input:
N = 4
mat[][] = {{1, 1, 1, 1},
{2, 2, 2, 2}
{3, 3, 3, 3}
{4, 4, 4, 4}}
Output:
{{1, 2, 3, 4},
{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4}}
Input:
N = 2
mat[][] = {{1, 2},
{-9, -2}}
Output:
{{1, -9},
{2, -2}}
Your Task:
You dont need to read input or print anything.
Complete the function
transpose
() which takes matrix[][] and N as input parameter andfinds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose.
Expected Time Complexity:
O(N * N)
Expected Auxiliary Space:
O(1)
Constraints:
1 <= N <= 10**3
-10**9
<= mat[i][j] <= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1687267797,
"func_sign": [
"public void transpose(int n,int a[][])"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader in=new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out=new PrintWriter(System.out);\n int t=Integer.parseInt(in.readLine().trim());\n while(t-->0)\n {\n int n=Integer.parseInt(in.readLine().trim());\n int a[][]=new int[n][n];\n for(int i=0;i<n;i++){\n String s[]=in.readLine().trim().split(\" \");\n for(int j=0;j<n;j++){\n a[i][j]=Integer.parseInt(s[j]);\n }\n }\n Solution ob=new Solution();\n ob.transpose(n,a);\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n out.print(a[i][j]+\" \");\n }out.println();\n }\n \nout.println(\"~\");\n}\n out.close();\n }\n}",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\nclass Solution {\n public void transpose(int n, int mat[][]) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < i; j++) {\n int temp = mat[i][j];\n mat[i][j] = mat[j][i];\n mat[j][i] = temp;\n }\n }\n }\n}",
"updated_at_timestamp": 1730466012,
"user_code": "//User function Template for Java\nclass Solution\n{\n public void transpose(int n,int a[][])\n {\n \n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1687503081,
"func_sign": [
"transpose(self, matrix, n)"
],
"initial_code": "# Initial Template for Python 3\n\nfor _ in range(int(input())):\n n = int(input())\n matrix = [\n list(map(int, input().split()))\n for _ in range(n)\n ]\n ob = Solution()\n ob.transpose(matrix, n)\n\n for row in matrix:\n print(*row)\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to calculate transposition of a matrix.\n def transpose(self, matrix, n):\n for i in range(n):\n for j in range(i + 1, n):\n # Swapping elements at (i,j) and (j,i).\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n",
"updated_at_timestamp": 1730466012,
"user_code": "#User function Template for python3\n\nclass Solution:\n def transpose(self, matrix, n):\n # Write Your code here"
}
|
eJzdV02O9FQMZMEBOII1669Qv/88ToJEIxYwCzbNt5hPQkIgDgGXY8dNqLK7J8n0ZJgVCxKN1PPi92yX7ark98///PuLz/z6+i/++OaXhx8vHz89PXxlD+l8aedLsmzFqvFnt2GLTUsnLidL2VKxVC3JrFsalhZL0zKfZ+7Llovlark9fLCHx58/Pn7/9PjDdz99erp5MO7iQd0ynWUerzMHd54vha50/MJDzpcqt9UPrwyLIdArHfHs8+W38+Xh1w+2D52bkE63y2j//A+fzNtlyZ5/b9bp9Xl9OYh+e/zmwPWM84VejblsDFe7jdmrCQjlSRAGQWosAKHkaVy8WzJGfrdkiwr2YsmGwHuxZF34vlhSve+WrKpKL5asqEleLCnruyVLB0j+39I8qiiNDxA4vdEEzxNoxwNob8+fZY4Y54ptPa3wcUlWeGqxwpCblW5lWFmsTKt8XJPVbJVeq1Wm1a0Oq4vVaY2PW7KWrRVrjKpZY+rD2mJtWufjzrnO1ov1ap1Rd+uEZ7E+bfDxSDY468VGtdFsMKthgxASR9U92ZJt4fxXW5ot3RZmvdjCkdFIcGA5m8UmOaHZ7DaHcV41yqcjeJNohpAwbabG8Bkiw6Cr6cRDJIkWEWHWzIzRM0JGMZ2ICDKBJFgEhEkzMQbPAKcTE/EnxsSRWBEP5sy8GPsMomqCnxATRkJFOJgy05rOp2K+LvSJMFEkUkSDGc+uVhcTDhWG4BNggkigCMYcmg4x46KasS7EnvgSQ+IkQpneBtPLOb0s0+EV66ipxJzlxFKznCwZy0LoCa8g/Bc+5Q7tPanxu5jPf2tx6L98WIPY7fvDvsceHn09xncfuO/uXnEjAodHTpj4M2KXA9aZfxoAJNqlKp3QIyaZaJrUYWmGK3YE/3Rkpm1W42ca564VGmeem+ctRRRaFwFH48KDC21LfyNdwRphTAmVDtLk5ohYsUUU3c+Vh6hBi8g8hqJprdfkPA0FrMiK4hUKnvK4ZTE9MALmOChhZRb4ln4E7yKa2d0ai92tSdjdav7drX7f3Wrx3a2u3t1q5N19OMA7Drwjxf9q4XWSlsSzODSG7KEt0C5oIzxtiLoh9oaYSgUVKSF4HH5GUbuIUBCkjiB2BLkjCB5JgfEYZ3q1kJgNQfgI0kcQP/SyRPpBKABCBRBKgFADuCKoP1wVEMqAUAeEQiBUAqEUKEyIrISQDIRswKWDaZ9EsQgFQWVaZE2ElCDkBCEpCFlBSAsq0yJZwTXGx5s8jZAahNwgJAdNrSZ0XXsQ+oPQIIQOwbWI2IceITQJoUsIbULoE0Kj0JkWORYhVgjBgosWq3eSYCC0CyMf9ulwTZ7O+snJuzgHN2lOHyIm9QK82NNLA8d9OEpKX3nBgx6awsUl5uRKkZ3wqxCSXjAbosamw+I9A2+I7uVTXQQ4HM3uuUPmRW8QTU0jdSkuEk1gS2MIjN6Di7pU7QfvreGdoBKrdvDCDIcRMq/+Pt79jWNxKTy5omUXpuqqj+otr16GN+ribQXvme4VVulUE8i++ZfB8FeY6QKaXAeLyxllNIn9fH40GPCun96j8AYc3i7qAxUYsu/+yrS4Xp9cdrOrZ1WrSHzZrdC8aSA1IdXVBmp672a1l/pGjdXVBgeM0Hbv/JuPg+V2cfPtoufrpa6+Xird9WKNrpeQu15E53rtv3M23yGrr9UVNr6wOlt9YXW2+sLGmT5prlR3NANrNJt0tnisy/tvsU3O6+K6Jp16zmkDygbUzaqA2SS+ZrMurmss5DMyK7QbuDYY8KzXys45OwDkzvC9drWpI95pPd5pJ0bkVPejj7G7KN4bQJ3vNCzvdX38MvnSUp+GtD42//aPL/8B66a0vw==
|
702,929
|
Check if divisible by 4
|
Given a number N. Check whether it is divisble by 4.
Examples:
Input:
N = 1124
Output:
1
Explanation:
The number is divisible by 4
as 1124 % 4 = 0.
Input:
N = 7
Output:
0
Explanation:
The number is not divisibly by
4 as 7 % 4 = 3.
|
geeksforgeeks
|
Easy
|
{
"class_name": "Sol",
"created_at_timestamp": 1615292571,
"func_sign": [
"int divisibleBy4(String N)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nclass GfG\n{\n public static void main (String[] args)\n {\n \n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n \n while(t-- > 0)\n {\n String s = sc.next ();\n\n \t\tSystem.out.println (new Sol().divisibleBy4 (s));\n \nSystem.out.println(\"~\");\n}\n \n }\n}\n\n// Contributed By: Pranay Bansal\n",
"script_name": "GfG",
"solution": "// Back-end complete function Template for Java\nclass Sol {\n int divisibleBy4(String s) {\n int num = 0;\n int len = s.length();\n // if length is 1, we simply check the digit's divisibility\n if (len == 1) {\n num = (s.charAt(0) - '0');\n if (num % 4 == 0) return 1;\n else return 0;\n }\n // computing the number formed by the last 2 digits\n num += (s.charAt(len - 1) - '0');\n num = (s.charAt(len - 2) - '0') * 10 + num;\n if (num % 4 == 0) return 1;\n else return 0;\n }\n}\n// Contributed By: Pranay Bansal\n",
"updated_at_timestamp": 1730469315,
"user_code": "//User function Template for Java\n\nclass Sol\n{\n int divisibleBy4 (String N)\n {\n // Your Code Here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"divisibleBy4(self, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n for tc in range(t):\n s = input()\n ob = Solution()\n print(ob.divisibleBy4(s))\n\n # Contributed By: Pranay Bansa\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n # Function to check if the number is divisible by 4.\n def divisibleBy4(self, s):\n num = 0\n n = len(s)\n\n # Checking if the string has only one character.\n if n == 1:\n num = int(s[0])\n # Checking if the character is divisible by 4.\n if num % 4 == 0:\n return 1\n else:\n return 0\n\n num = int(s[n - 1])\n # Calculating the number from the last two characters.\n num = int(s[n - 2]) * 10 + num\n\n # Checking if the number is divisible by 4.\n if num % 4 == 0:\n return 1\n else:\n return 0\n\n# Contributed By: Pranay Bansal\n",
"updated_at_timestamp": 1730469315,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef divisibleBy4 (self, N):\n\t\t# Your Code Here"
}
|
eJy9VMtKxDAUdSH4FUIJLgfJ4yZN/RLBiAvtwk2cRQcGRJiPGP/Xm8dMW5smdSieW4Y2k5ycnJzkcP19d3Pl8XiLL0+f5N1udx15qIgwllEOxnJJjW10rSQITjYVaffb9rVr314+dl3szIzFTvhLvjbVgITjyAj8mwuQaoYhOVwaC9TDyVDGaoaMtURtCualhCfJCG5VWEhQ6wa7AMJYwYDJZl4aPTFO6XSEI/bg5zcnO/rGaMm5KbnobTdWRqARAUXCX2zYoqMqPT80sQEBo4XyUOgbhHJ2xrp4W3w6cFP6VbPz7KD7IGUSRE+TJJx08OtgERgnTkOVNE/p3NFQy84GXRbFbNZHOS3kohjj1aVcMGNM4/B+MBAzkIto8ggOtY8/i8r7NpW/AeaSS1fOVvaCWvWYlK38by9d+9/vqGx4y+kVC+P7fLz/AbIVChU=
|
705,582
|
Replace O's with X's
|
Given a matrix mat of size N x M where every element is either 'O' or 'X'. Replace all 'O' or a group of 'O' with 'X' that are surrounded by 'X'.
Examples:
Input:
n = 5, m = 4
mat = {{'X', 'X', 'X', 'X'},
{'X', 'O', 'X', 'X'},
{'X', 'O', 'O', 'X'},
{'X', 'O', 'X', 'X'},
{'X', 'X', 'O', 'O'}}
Output:
ans = {{'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X'},
{'X', 'X', 'O', 'O'}}
Explanation:
Following the rule the above matrix is the resultant matrix.
Input:
n = 5, m = 4
mat = {{'X', 'O', 'X', 'X'},
{'X', 'O', 'X', 'X'},
{'X', 'O', 'O', 'X'},
{'X', 'O', 'X', 'X'},
{'X', 'X', 'O', 'O'}}
Output:
ans = {{'X', 'O', 'X', 'X'},
{'X', 'O', 'X', 'X'},
{'X', 'O', 'O', 'X'},
{'X', 'O', 'X', 'X'},
{'X', 'X', 'O', 'O'}}
Explanation:
Following the rule the above matrix is the resultant matrix.
Constraints:
1 ≤ n, m ≤ 500
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1616153578,
"func_sign": [
"static char[][] fill(int n, int m, char a[][])"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n public static void main(String args[])throws IOException\n {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while(t-- > 0){\n String a[] = in.readLine().trim().split(\" \");\n int n = Integer.parseInt(a[0]);\n int m = Integer.parseInt(a[1]);\n char mat[][] = new char[n][m];\n for(int i=0; i<n; i++)\n {\n String S[] = in.readLine().trim().split(\" \");\n for(int j=0; j<m; j++)\n {\n mat[i][j] = S[j].charAt(0);\n }\n }\n \n Solution ob = new Solution();\n char[][] ans = ob.fill(n, m, mat);\n for(int i = 0;i < n;i++) {\n for(int j = 0;j < m;j++) {\n System.out.print(ans[i][j] + \" \");\n }\n System.out.println();\n }\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730272660,
"user_code": "//User function Template for Java\n\nclass Solution{\n static char[][] fill(int n, int m, char a[][])\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616153578,
"func_sign": [
"fill(self, n, m, mat)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n, m = [int(x) for x in input().split()]\n mat = []\n for i in range(n):\n s = list(map(str, input().split()))\n mat.append(s)\n\n ob = Solution()\n ans = ob.fill(n, m, mat)\n for i in range(n):\n for j in range(m):\n print(ans[i][j], end=\" \")\n print()\n print(\"~\")\n",
"solution": "# Backend complete function Template for python3\n\nclass Solution:\n def floodFillUtil(self, screen, x, y, prevC, newC, N, M):\n # Base cases\n if x < 0 or x >= N or y < 0 or y >= M:\n return\n if screen[x][y] != prevC:\n return\n # Replace the color at (x, y)\n screen[x][y] = newC\n self.floodFillUtil(screen, x+1, y, prevC, newC, N, M)\n self.floodFillUtil(screen, x-1, y, prevC, newC, N, M)\n self.floodFillUtil(screen, x, y+1, prevC, newC, N, M)\n self.floodFillUtil(screen, x, y-1, prevC, newC, N, M)\n\n def fill(self, n, m, mat):\n temp = []\n for i in range(n):\n row = []\n for j in range(m):\n if mat[i][j] == 'X':\n row.append('X')\n else:\n row.append('-')\n temp.append(row)\n\n for i in range(n):\n if temp[i][0] == '-':\n self.floodFillUtil(temp, i, 0, '-', 'O', n, m)\n for i in range(n):\n if temp[i][m-1] == '-':\n self.floodFillUtil(temp, i, m-1, '-', 'O', n, m)\n for i in range(m):\n if temp[0][i] == '-':\n self.floodFillUtil(temp, 0, i, '-', 'O', n, m)\n for i in range(m):\n if temp[n-1][i] == '-':\n self.floodFillUtil(temp, n-1, i, '-', 'O', n, m)\n\n for i in range(n):\n for j in range(m):\n if temp[i][j] == '-':\n temp[i][j] = 'X'\n return temp\n",
"updated_at_timestamp": 1730272660,
"user_code": "#User function Template for python3\n\nclass Solution:\n def fill(self, n, m, mat):\n # code here"
}
|
eJztWM1OwzAM5sBDcLR6nlBbaQLxErlGoogD7MCl7LBJSAjEQ8AzcuMZaJd2qRPbSbeWFalY7Mc/n+3ETrx+nH/9XJzt/vR39eH2NXkq19tNcgNJVpQZVC+qKJMFJKuX9ephs3q8f95uGg0FRfleSd8WQNhp1k6zdilkaeURFGhMhmmoZuzeKx+NPMwkzT03VlND5z3AZOLck7CAfgRuqC0XZyVzaQQiW/CTqL/Fcl1vlrgNXkK2tFGTVIspSGX3l8qkWYVWTFhisWfpih1LX4wsKbGSxaK16FuMXMxbXDVxzcUdYxtdogDqLJ+8nOzxPIU8pU8F8mzkytIhoxhG3CvKeEhRQHMVGSzzjxUZNB+RaWlakcTzXWPUYRAjYhRWsYso7otVDOx0fPWo09VjH0RhTIihaE//RPO0GY3h/bSY42mOU59DY5LX1RVc2+GowbI/QTrjkw4y0HGHb09qiBLGJhQN4HAMp+ue59iIsI4WOPTgnkOWswMBNz4yYyczrjJjLiFQnU/E1O049y4dblbmp2QxQWZJes7E/LQ1S/hZE0xRNi/CkhtoCaa5quVf66YV5WjMjS92tzm1pKcnqijqmA579NIaj9K482lwyGkw8QR3lXN0kn2LFfVdp26HacEhejD8MDMQSvA4UHGhHPIU9g+6dFpV3NLwJczoT+JmnLIktrnqfjmmwXp12N3n5S9rmmac
|
705,223
|
Swapping Triangles
|
Given an integer N and a matrix A of dimensions NxN.Swap the values of the triangle above the primarydiagonal with the values of the triangle below the primary diagonal.
Examples:
Input:
N=3
A=[[1,2,3],[4,5,6],[7,8,9]]
Output:
1 4 7
2 5 8
3 6 9
Explanation:
Swapping the upper triangle with the
lower triangle gives this result.
Input:
N=4
A=[[2,7,3,1],[10,1,5,1],[10,4,7,6],[6,9,1,8]]
Output:
2 10 10 6
7 1 4 9
3 5 7 1
1 1 6 8
Explanation:
Swapping upper triangle with the
lower triangle leads to this result.
Constraints:
1<=N,A[i][j]<=1000, for 0<=i
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int[][] swapTriangle(int N, int A[][])"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int N = Integer.parseInt(read.readLine());\n int A[][] = new int[N][N];\n for (int i = 0; i < N; i++) {\n String S[] = read.readLine().split(\" \");\n for (int j = 0; j < N; j++) {\n A[i][j] = Integer.parseInt(S[j]);\n }\n }\n Solution ob = new Solution();\n A = ob.swapTriangle(N, A);\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n System.out.print(A[i][j] + \" \");\n }\n System.out.println();\n }\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // function to swap elements in the lower triangle with their corresponding elements in the upper\n // triangle\n int[][] swapTriangle(int N, int A[][]) {\n // iterate over the rows\n for (int i = 0; i < N; i++) {\n // iterate over the columns\n for (int j = 0; j < N; j++) {\n // check if the current element is in the lower triangle\n if (j < i) {\n // swap the current element with its corresponding element in the upper triangle\n int temp = A[i][j];\n A[i][j] = A[j][i];\n A[j][i] = temp;\n }\n }\n }\n // return the modified matrix\n return A;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n int[][] swapTriangle(int N, int A[][]) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"swapTriangle(self,N,A)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N = int(input())\n A = [[0]*N for _ in range(N)] # Create a new list for each row\n for i in range(N):\n A[i] = list(map(int, input().strip().split(\" \")))\n ob = Solution()\n ans = ob.swapTriangle(N, A)\n for i in range(N):\n for j in range(N):\n print(ans[i][j], end=\" \")\n print()\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def swapTriangle(self, N, A):\n for i in range(N):\n for j in range(N):\n if j < i:\n temp = A[i][j]\n A[i][j] = A[j][i]\n A[j][i] = temp\n return A\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def swapTriangle(self,N,A):\n #code here"
}
|
eJztWMuOHEUQ5MBHcAzN2UL1fvhLkLyIA+yBy+DDWkJCIH+CD0b+XSKzenamp6t6awYOyNrN0mi7K+uREdlVmfnx27+/fPeN/v3wif+8++Pw6/H9h6fDWxzsw1GaMebheHiDw+Pv7x9/fnr85affPjydVNiJh+NfVPjzDdZjHceCPx5hPB6ewx3CaJKok1ArgP8mZBRUWO7IWlgH62EDrKgl2AxbYCsc+x3HOTgPF+Dizg44jlMlcIBsJeu0WQbL3osuUWSih2OQtYOuIDuO3AjX5nJcYWSBXyxoSOL5Z/s83OFZUTZ4+eRXT9310wWC4MMJQbVaOFoQxAlAvqpq0hlALksrCRFhIRQVntv1JI/zevgAH+HTjgVZUawCk28wF1lVVkkyi1hSFUori/gGtmwy6SaKLKKAW+XG6yYE86R0FSHEG25iBIO6DDbSwLmSE2IrOcN4IZfYPssK8JOsX+Ym1y+LyPZlRe29tLs+s5Guqejaiq6x6FqLrrno2rt5qwZ33tLi7ls7dHM9AmDGIk7n9rqb5cPuEwiD7jMe3e50AU2nO+NSNt0Fa7nqrriWVbd8RuN2qWix386aDi+2k6rHTGu6AZNNlCOm286H0nGx9dVCjzOTWmZSy0xqmUktM6llJrXMpJaZ1DKTWpNKZkrHzKiYCQ3TFPpBTv9a6Uk7gCbkdBS9KOdD6QW5PJ52ZX1Q7cj1kTWU7eE1kN4x1pWXDrTdNnHIjdvcuTdo0ydhr91yNG7abUfl5uSUuPDOxsEZ9zYOLri3aRB7b5PPGve2f3XVrJOYUQj0Ouh10Ougr3HQOHXV04UZbmBMyHCPkRyDNMZfmvzrrcbUmbl1sIgWiSm3RbGoUj1oFxfzaGbawSE6JIfMHNyhSj2h3U1Mqpl3B4/okTyyR2FSLhWGdv1Ihs1YghYFpIAcUAKqZOnthpHcPiIwiqDJETmiRFSpkbRLRDL9hJAQGT8Qk4SSUImAafeE5P0ZISNmJEYOBC2jEh7TrgIpAhSEgliQCjJjBqJK7MxSsqjwFaEiVqSKXFEYLQjsdad+tUdJuwdWdaRVFYSBmsGmDCJWcKNe+skWCSHmhJXIERzaTxNpRZB+Ukm2SAgxJ6xEjuDQfpoYpZ88k0qyRUKIOWElcgSH9ifppxOQZ1JJtkgIMSesRI7gZOmnh9AJyDOpJFskhJgTViJXpJ/uQw+hE5BnUkm2SAgxJ6xVM3AtLokPiZ+ILwjfwqnwJtwI/nXkuVrLoGX8AKoC7TWikHpfkgpQC+TDc6RQFW2vOGcl1DbqjXIQFP2ihR6Jkr0CnpV2qxATXzqLMJHUWYxiHxR1bkacwyrWUVGuiq5vPDhlIKl7GcV8r27pFjdpxMvErR4Xlm+5uUIjV8LvtDhSc45GdyvGNdcSG8ziABIKW7N4W/Of5hOnqmfzwOZTYoSeN+rBWptb/Kx5Tov+0uKnzfeaN/VIkzrIwOatZpjWtPOTWue9u0l7ok79n5dFg/1fFkbbtm4pjXK/NzBeJjVvUJW7Zaj64+fv/wEjbwtq
|
701,271
|
Boundary traversal of matrix
|
You are given a matrixof dimensions nx m. The task is to perform boundary traversal on the matrix in a clockwise manner starting from the first row of the matrix. Example 1:
Examples:
Input:
n = 4, m = 4
matrix[][] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15,16}}
Output:
1 2 3 4 8 12 16 15 14 13 9 5
Explanation:
The matrix is:
1 2 3 4
5
6 7
8
9
10 11
12
13 14 15 16
The boundary traversal is:
1 2 3 4 8 12 16 15 14 13 9 5
Input:
n = 3, m = 4
matrrix[][] = {{12, 11, 10, 9},
{8, 7, 6, 5},
{4, 3, 2, 1}}
Output:
12 11 10 9 5 1 2 3 4 8
Your Task:
Complete the function
boundaryTraversal()
that takes matrix, n and mas input parameters and returns the list of integers that form
the boundary traversal of the matrix in a clockwise manner.
Expected Time Complexity:
O(N+ M)
Expected Auxiliary Space:
O(N+M)
Constraints:
1 <= n, m<= 1000
0 <= matrix
i
<= 1000
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1618656612,
"func_sign": [
"static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader in=new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out=new PrintWriter(System.out);\n int t = Integer.parseInt(in.readLine().trim());\n \n while(t-- > 0)\n {\n String s[] = in.readLine().trim().split(\" \");\n int n = Integer.parseInt(s[0]);\n int m = Integer.parseInt(s[1]);\n int a[][] = new int[n][m];\n s = in.readLine().trim().split(\" \");\n int ind=0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n a[i][j] = Integer.parseInt(s[ind++]);\n }\n }\n Solution ob = new Solution();\n ArrayList<Integer> ans = ob.boundaryTraversal(a, n, m);\n for (int i : ans) {\n out.print(i + \" \");\n }\n out.println();\n \nout.println(\"~\");\n}\n out.close();\n }\n}",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\n\nclass Solution {\n // Function to return list of integers that form the boundary\n // traversal of the mat in a clockwise manner.\n static ArrayList<Integer> boundaryTraversal(int mat[][]) {\n int n = mat.length;\n int m = mat[0].length;\n ArrayList<Integer> output = new ArrayList<Integer>();\n\n // base case if number of row or column is 1 then adding all elements.\n if (n == 1) {\n int i = 0;\n while (i < m) output.add(mat[0][i++]);\n } else if (m == 1) {\n int i = 0;\n while (i < n) output.add(mat[i++][0]);\n } else {\n // we take care of fact that we don't add any number multiple times.\n\n // traversing first row and adding elements in the list.\n for (int j = 0; j < m; j++) output.add(mat[0][j]);\n\n // traversing last column and adding elements in the list.\n for (int j = 1; j < n; j++) output.add(mat[j][m - 1]);\n\n // traversing last row and adding elements in the list.\n for (int j = m - 2; j >= 0; j--) output.add(mat[n - 1][j]);\n\n // traversing first column and adding elements in the list.\n for (int j = n - 2; j >= 1; j--) output.add(mat[j][0]);\n }\n // returning the list.\n return output;\n }\n}",
"updated_at_timestamp": 1730267170,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n //Function to return list of integers that form the boundary \n //traversal of the matrix in a clockwise manner.\n static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m)\n {\n // code here \n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618656612,
"func_sign": [
"BoundaryTraversal(self,matrix, n, m)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n, m = map(int, input().strip().split())\n values = list(map(int, input().strip().split()))\n k = 0\n matrix = []\n for i in range(n):\n row = []\n for j in range(m):\n row.append(values[k])\n k += 1\n matrix.append(row)\n obj = Solution()\n ans = obj.BoundaryTraversal(matrix, n, m)\n for i in ans:\n print(i, end=\" \")\n print()\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n\n # Function to return list of integers that form the boundary\n # traversal of the matrix in a clockwise manner.\n def BoundaryTraversal(self, matrix, n, m):\n output = []\n\n # base case if number of row or column is 1 then adding all elements.\n if n == 1:\n i = 0\n while i < m:\n output.append(matrix[0][i])\n i += 1\n elif m == 1:\n i = 0\n while i < n:\n output.append(matrix[i][0])\n i += 1\n else:\n\n # we take care of fact that we don't add any number multiple times.\n\n # traversing first row and adding elements in the list.\n row_ind = 0\n col_ind = 0\n while col_ind < m:\n output.append(matrix[row_ind][col_ind])\n col_ind += 1\n\n # traversing last column and adding elements in the list.\n col_ind = m-1\n row_ind += 1\n while row_ind < n:\n output.append(matrix[row_ind][col_ind])\n row_ind += 1\n\n # traversing last row and adding elements in the list.\n row_ind = n-1\n col_ind -= 1\n while col_ind > -1:\n output.append(matrix[row_ind][col_ind])\n col_ind -= 1\n\n # traversing first column and adding elements in the list.\n col_ind = 0\n row_ind -= 1\n while row_ind > 0:\n output.append(matrix[row_ind][col_ind])\n row_ind -= 1\n\n # returning the list.\n return output\n",
"updated_at_timestamp": 1730267170,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to return list of integers that form the boundary \n #traversal of the matrix in a clockwise manner.\n def BoundaryTraversal(self,matrix, n, m):\n # code here "
}
|
eJztWstuG0cQzMGn3PwHDV5yEYx5P/wlAcwgh0SHXDY6SECAwIY/wv7fVPXsio/dJamANClhDR4ocrYf1dU1PUN/fff9/S8/6b9ff8abT/+u/uoenh5XH2Xl112QsO6sOPESJEqSLEWqWCPWinVivdggNopN6y5KXHcOq504Ly6Ii+JM/4hLYisMWD7sstgCewF2XRGLP5NagS14hbt1V6tUPJilJqlRaljdyer+n4f7Px7v//z976fHPsohuqLxbMzAZ5R192UcUqJ/ut0EryEURoiA9aGN+6DuU/t49flOtiByDDZOQ7TuPPMYfXUkj0iAKhZm6X22b1L/YZgMRMtURt7WHZJCMjMV83Ox7y0mEZBK+zYNhWu11JVHc2qmG7KTwWyn2oPwXEmutAMaLYggtv8YC71MVweZJ2GaVjzsohyIO4pP4s2Obw8+VLXHrLL4ovywrRQghq/KmaT8CcolMMqSLVYXKIVnUJhwry5o1O2Tj0aVnQjIm7m0iI6ZKd1uTPsozjVDcxcMo2JsWeOMGrPX+K0EvJwEeIQugARJAvhYJKDVjCQjEW/Q11kiSAI5QGSgGDoE1cPLSUKpgiTEi8KA4EVSlWykQCbwBvzOkpFLlBwke8lOMniNl5PipaDNo5QkBdkWKehRAoEi7YuFVAiAk2pPZOZASmCARJENQkZccA4P1aotv9ECeir0SucMz2iCRiEyPTNmaqeqEJVq9Ou10efUra1jpFsdNMEH1NYdbOV51m4YMubDmLosd9bSR6WBV0rYHeY0PgBBlt4rDaJSIis9KoFqlQXEIABpkJUSUenhlSpWCRCUDEmJUUiSYnb4MCo4CwZikB5ZqRJ3q2UN2xp4GbSEQd6GYgMUDMAw3EUIGdYSHwJEhAgRMWIbaR/BhvYgVYP4En+2GNYARcvdjpscVYTKonqDdQDTAjUbKD58j88Cv+Ma7kh4BiBbYG09a+JfyN8mqk1ikpKy9YxmxmgZAerZrMfeW+691xaNRuX6KEOfoenbq3UlSgwmNDWc4mTsx4HTZoeRAm4UihKez2DnOLOfRTm0NnbcPMdb6g9xPSuyh5tqS2S5z6bbDf7wFnYDAR5Gd2ILo5q5kyRrvIUd3mBOGRitjtp704kql4xGKwINYAljIURjAQdorg0ncdhz9usE23AFpAlqIVTbyr09C1AqLAtCYURaY3usdVFzRrcYpxa3hgeUhla8xmbVEKUMgUzGNoxBbaBpo0kbMo6OCyxU1mkl6rzjdWICilMipyPxlcRpksOc0y+mWDzqOO3bAdqT9qZ9ptWJEeIlfPM6pHF52czkW7zS8II5NDzzSDQX/OxT5zxJIOvxWSKd+TCRhtMEvR06T9z2Xl3rsltfO/gb3K1zWvbrt7lfa2UvtGNfTeqQz3IwWaTu7OguSveKle5yOjdxzXjSPePxi8brXjx7M9keP/Tu2b3ay+eL/Uj02n8lWq7PB8q+uftzntwvc4duL36J/n/1NiyCexuCe9s3K8th49rBv7LDxlXPGvH4T6HLaeNlpw3YPd95Y/Z+XDfHE2/IqzdX/f82/nlE/O3bh/8A3S+qew==
|
703,249
|
Front-Back Transformation - copy
|
Given a string S, consisting only of english alphabets, replace all the alphabets with the alphabets occuring at the same position when counted in reverse order of alphabets. For example, 'a' would be replaced by 'z', 'b' by 'y', 'c' by 'x' and so on. Any capital letters would be replaced by capital letters only.
Examples:
Input:
S = "Hello"
Output:
Svool
Explanation:
'H' is the 8th letter from the
beginning of alphabets, which is replaced by
'S' which comes at 8th position in reverse order
of alphabets. Similarly, all other letters are
replaced by their respective upper or lower case
letters accordingly.
Input:
S = "GfG"
Output:
TuT
Explanation:
'G' is replaced with 'T'
and 'f' is replaced with 'u'
1<=Length of string S <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"String convert(String s)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*; \nclass GFG{\n public static void main(String args[]) throws IOException { \n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0){\n String S = read.readLine();\n Solution obj = new Solution();\n System.out.println(obj.convert(S));\n \n \nSystem.out.println(\"~\");\n}\n } \n} ",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // Convert given string by replacing each character with its corresponding opposite letter in the\n // alphabet\n String convert(String a) {\n // Create a StringBuilder to store the converted string\n StringBuilder ans = new StringBuilder();\n // Iterate over each character in the given string\n for (int i = 0; i < (int) a.length(); ++i) {\n char ch = a.charAt(i);\n // If the character is a lowercase letter, replace it with its opposite lowercase letter\n if (ch >= 'a' && ch <= 'z') ch = (char) ('z' - (ch - 'a'));\n // If the character is an uppercase letter, replace it with its opposite uppercase letter\n else ch = (char) ('Z' - (ch - 'A'));\n // Append the converted character to the StringBuilder\n ans.append(ch);\n }\n // Convert the StringBuilder back to a string and return it\n return ans.toString();\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution \n{ \n String convert(String s) \n { \n return s;\n }\n} "
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"convert(self, s)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n s = input()\n\n solObj = Solution()\n ans = solObj.convert(s)\n\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n def convert(self, s):\n ans = '' # Initialize an empty string 'ans'\n for i in s: # Iterate through each character in the given string 's'\n if ord(i) >= ord('a') and ord(i) <= ord('z'): # Check if the character is lowercase\n # Convert the character to its inverted lowercase value and add it to 'ans'\n ans += chr(ord('z') - (ord(i) - ord('a')))\n else: # If the character is not lowercase, it must be uppercase\n # Convert the character to its inverted uppercase value and add it to 'ans'\n ans += chr(ord('Z') - (ord(i) - ord('A')))\n return ans # Return the final converted string 'ans'\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n\n def convert(self, s):\n # code here"
}
|
eJytVEmO01AUZIHENSKvW0i9Zed5TOJ5Igh5jIfE8Ty1QBwC7sCOKxIQrbbVPHeM8OovrKp6r+rVl9fffrx59fszv18f7x+QOMubGnm3Qe4PGeriPhnSEZvwyN0GCfo88OrA/3hp6j8/2YPZ6Y1ayYV4yD4fMuTT3WaOMdqD1Zud0eqNBoA4qIt5uE8EZEgBKNtsn0ulUmut0VsjgLM7CykXM0cqIDzMAZDEXCrkUqnUWmv01ujM3hrsEXUwF/cInwyokD4yERtzCZ8CPHzKJWzMRPSRCsmA8HEPc1HHHq3B7I1Ob7VGrZVKLqVCzAEVU6EAy3RgAEXqyFIdtHifoxVx9YlLBQCM8/WYdqlSSO3IuPol5XsAc+LoZb5QAHoSktPcJoABXhvAAFsFMDiu5wfhMYqT9HTOLnlRVnXTdv04AAzj0HdtU1dlkV+y8ylN4ugYBr7nuAADiuEESdEMy/HCdrcXJVlRNd0wbQs6FMs0dE1VZEnc77YCz7EMTZEEjmKwt/MLfNHgZEnr/TO1L4lNnsldUAttfNGM1XZAE84yuyKtyzl9DPO/j3dTW0FDPRXnX67yhi69YVkr63DFbiHyX421eD631xlE8WTIcvZXVwNEOO3IGb/3P25hWqiPCj58ffsTs82wdQ==
|
700,356
|
Equal Sum and XOR
|
Given a positive integer N, Your task is to complete the function countValues which returns an integer denoting the count of all integers i such that0 <= i <= n and n+i = n^i where ^ denotes a XOR operation.Input:The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N.Output:For each test case in a new line output will be the count of such positive integers.Constraints:1<=T<=1001<=N<=1000Example(To be used only for expected output):Input2712Output14Explanation:For first test case7^i = 7+i holds only for only for i = 07+0 = 7^0 = 7For second test case12^i = 12+i hold only for i = 0, 1, 2, 3for i=0, 12+0 = 12^0 = 12for i=1, 12+1 = 12^1 = 13for i=2, 12+2 = 12^2 = 14for i=3, 12+3 = 12^3 = 15
Example(To be used only for expected output):
Input:
2
7
12
Output:
1
4
Explanation:
For first test case
7^i = 7+i holds only for only for i = 0
7+0 = 7^0 = 7
For second test case
12^i = 12+i hold only for i = 0, 1, 2, 3
for i=0, 12+0 = 12^0 = 12
for i=1, 12+1 = 12^1 = 13
for i=2, 12+2 = 12^2 = 14
for i=3, 12+3 = 12^3 = 15
Note:
The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
|
geeksforgeeks
|
Easy
|
{
"class_name": "GfG",
"created_at_timestamp": 1619348482,
"func_sign": [
"public int countValues(int n)"
],
"initial_code": "//initial code\nimport java.util.*;\n\nclass EqualSumAndXor\n{\n public static void main(String[] args)\n {\n Scanner sc=new Scanner(System.in);\n int t=sc.nextInt();\n while(t>0)\n {\n int a =sc.nextInt();\n GfG g=new GfG();\n \n System.out.println(g.countValues(a));\n t--;\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "EqualSumAndXor",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "class GfG{\n /*you are required to complete this method */\n\tpublic int countValues(int n)\n\t{\n //Your code here\n\t}\n}\n"
}
|
{
"class_name": null,
"created_at_timestamp": 1619348482,
"func_sign": [
"countValues(n)"
],
"initial_code": "# Your code goes here\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n = int(input().strip())\n print(countValues(n))\n print(\"~\")\n\n# Contributed By: Harshit Sidhwa\n",
"solution": "def countValues(n):\n # initializing the count variable\n cnt = -1\n\n # iterating over the range from 0 to n+1\n for i in range(n+1):\n # checking if the sum of n and i is equal to the XOR of n and i\n if (n + i == n ^ i):\n # if it is true, then increment the count variable\n cnt += 1\n\n # returning the count plus 1\n return cnt + 1\n",
"updated_at_timestamp": 1729753320,
"user_code": "# You are required to complete this fucntion\n# Function should return the an integer\ndef countValues(n):\n # Code here\n"
}
|
eJydVMtugzAQ7KHqdyCfUWUbTCE/kFvOkeqqh4RDLy4HkCJFqfoRyf/GXkTrlt3lgZB52LOzO7P29+Nt9/QA137rX17P4sM1XSs2iVDWKZEmoj419aGtj++fXfs79WWduKTJv/VSSgpSYBhtnb+rqiJQGkA5Bs2sk9YZKXlagJYw4in0aS/K2kN4vvF6ukS0OAPFqUGdGSX2Y6wXkftP3AwWeia/7gU0Ah6WRUdcefQn/l9Gs1RxSgd2E5hLz5ppDy1MznZB9udR5PEX5imqIVVeOZEoJ5sLk/PrMEqPHGPahms2jaYdEB43ZTQXueC33GphwITl7qjYctTx1RkFESjaFX4xtbFWonprCDIdkz1CFb0R+wajgHgPKOaMGABv1+c7osYBsA==
|
701,283
|
Binary String
|
Given a binary stringS. The task is to count the number of substrings that start and end with 1. For example, if the input string is “00100101”, then there are three substrings “1001”, “100101” and “101”.
Examples:
Input:
N = 4
S = 1111
Output:
6
Explanation:
There are 6 substrings from
the given string. They are 11, 11, 11,
111, 111, 1111.
Input:
N = 5
S = 01101
Output:
3
Explanation:
There 3 substrings from the
given string. They are 11, 101, 1101.
Constraints:
1 ≤ |S| ≤ 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1619084131,
"func_sign": [
"public static int binarySubstring(int a, String str)"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG{\n public static Scanner sc = new Scanner(System.in);\n\tpublic static void main (String[] args){\n int t;\n \tt=sc.nextInt();\n \tsc.nextLine();\n \twhile((t--)!=0){\n \t int n=sc.nextInt();\n \t sc.nextLine();\n \t String s = new String();\n \t s=sc.nextLine();\n \t Solution obj = new Solution();\n \t System.out.println(obj.binarySubstring(n, s));\n \t\nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "GFG",
"solution": "class Solution\n{\n //Function to count the number of substrings that start and end with 1.\n public static int binarySubstring(int a, String str)\n {\n int c=0;\n for(int i=0;i<str.length();++i)\n {\n //counting number of 1's in the string.\n if(str.charAt(i)=='1')\n ++c;\n }\n //returning count of possible pairs among total number of 1's.\n return (c*(c-1))/2;\n }\n}",
"updated_at_timestamp": 1730267061,
"user_code": "\n\nclass Solution\n{\n //Function to count the number of substrings that start and end with 1.\n public static int binarySubstring(int a, String str)\n {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619084131,
"func_sign": [
"binarySubstring(self,n,s)"
],
"initial_code": "import atexit\nimport io\nimport sys\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\[email protected]\n\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\nif __name__=='__main__':\n t = int(input())\n for i in range(t):\n n=int(input())\n s=str(input())\n obj = Solution()\n print(obj.binarySubstring(n,s))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to count the number of substrings that start and end with 1.\n def binarySubstring(self, n, s):\n # counting number of 1's in the string.\n number_of_ones = s.count('1')\n\n # returning count of possible pairs among total number of 1's.\n return ((number_of_ones * (number_of_ones - 1)) // 2)\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to count the number of substrings that start and end with 1.\n def binarySubstring(self,n,s):\n #code here"
}
|
eJxrYJnqyMIABhFWQEZ0tVJmXkFpiZKVgpKBko6CUmpFQWpySWpKfH5pCVRcqVZHAUmZYUweEOFSbBCTVxeTh1WLIYlajIC2kGoNUI8hLnsM8eghwx4DUv1jCnKbIW7n4dJnBnIfCOLQaIxbH1gbLgux6sMZ4jj9Aw1AnP4yIxAchPTjDBewNpIizoC8tEsNl5KeXGCpmYycA9eKaowBiSYZ4EkMsVP0ABXjVX4=
|
701,256
|
Make Matrix Beautiful
|
A beautiful matrix is a matrix in which the sum of elements in each row and column is equal. Given a square matrixof size NxN. Find theminimum number of operation(s) that are required to make the matrix beautiful.In one operation you canincrement thevalue of any onecell by 1.Example 1:
Examples:
Input:
N = 2
matrix[][] = {{1, 2},
{3, 4}}
Output:
4
Explanation:
Updated matrix:
4 3
3 4
1. Increment value of cell(0, 0) by 3
2. Increment value of cell(0, 1) by 1
Hence total 4 operation are required.
Input:
N = 3
matrix[][] = {{1, 2, 3},
{4, 2, 3},
{3, 2, 1}}
Output:
6
Explanation:
Number of operations applied on each cell are as follows:
1 2 0
0 0 0
0 1 2
Such that all rows and columns have sum of 9.
Your Task:
You don't need to read input or print anything.Complete the function
findMinOpeartion()
that takes
matrix and n
as input
parameters
and returns the
minimum number of operations
.
Expected Time Complexity:
O(N * N)
Expected Auxiliary Space:
O(N)
Constraints:
1 <= N <= 10**3
1 <= matrix[i][j] <= 10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1691817228,
"func_sign": [
"public static int findMinOperation(int N, int[][] matrix)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\nclass IntMatrix\n{\n public static int[][] input(BufferedReader br, int n, int m) throws IOException\n {\n int[][] mat = new int[n][];\n\n for(int i = 0; i < n; i++)\n {\n String[] s = br.readLine().trim().split(\" \");\n mat[i] = new int[s.length];\n for(int j = 0; j < s.length; j++)\n mat[i][j] = Integer.parseInt(s[j]);\n }\n\n return mat;\n }\n\n public static void print(int[][] m)\n {\n for(var a : m)\n {\n for(int e : a)\n System.out.print(e + \" \");\n System.out.println();\n }\n }\n\n public static void print(ArrayList<ArrayList<Integer>> m)\n {\n for(var a : m)\n {\n for(int e : a)\n System.out.print(e + \" \");\n System.out.println();\n }\n }\n}\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while(t-- > 0){\n \n int N;\n N = Integer.parseInt(br.readLine());\n \n \n int[][] matrix = IntMatrix.input(br, N, N);\n \n Solution obj = new Solution();\n int res = obj.findMinOperation(N, matrix);\n \n System.out.println(res);\n \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "\nclass Solution {\n public static int findMinOperation(int N, int[][] matrix) {\n // code here\n }\n}\n \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1692023092,
"func_sign": [
"findMinOpeartion(self, matrix, n)"
],
"initial_code": "# Initial Template for Python 3\n\nfor _ in range(int(input())):\n n = int(input())\n matrix = [list(map(int, input().split())) for _ in range(n)]\n ob = Solution()\n print(ob.findMinOpeartion(matrix, n))\n print(\"~\")\n",
"solution": "class Solution:\n def findMinOpeartion(self, matrix, n):\n sumRow = [0] * n\n sumCol = [0] * n\n\n # calculating sumRow[] and sumCol[] array.\n for i in range(n):\n for j in range(n):\n sumRow[i] += matrix[i][j]\n sumCol[j] += matrix[i][j]\n\n # finding maximum sum value in either row or in column.\n maxSum = 0\n for i in range(n):\n maxSum = max(maxSum, sumRow[i])\n maxSum = max(maxSum, sumCol[i])\n\n count = 0\n i, j = 0, 0\n while i < n and j < n:\n # finding minimum increment required in either row or column.\n diff = min(maxSum - sumRow[i], maxSum - sumCol[j])\n\n # adding difference in corresponding cell, sumRow[] and sumCol[] array.\n matrix[i][j] += diff\n sumRow[i] += diff\n sumCol[j] += diff\n\n # updating the result.\n count += diff\n\n # if ith row is satisfied, incrementing i for next iteration.\n if sumRow[i] == maxSum:\n i += 1\n\n # if jth column is satisfied, incrementing j for next iteration.\n if sumCol[j] == maxSum:\n j += 1\n\n # returning the result.\n return count\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findMinOpeartion(self, matrix, n):\n # Code here"
}
|
eJxrYJlax8YABhHlQEZ0tVJmXkFpiZKVgpJhTB4IGYBBTJ6SjoJSakVBanJJakp8fmkJVBVQpg4oWaujgKmVZE1GQE0KcBuhDAWyzDFQMIASJOo1BmuD6kaiSDfGUMFIAUiZKJgqmMXkmStYKFjiNMbIHJ85hqAwQKVIdI4JVCPcBOwMEk01BUeSAhqmjSCp6c8A7i1kOMQFyclPSBkKysKbpwwNLC1hGihJSkbkZRgKc4wBDtXYCygDeMhQUsCADYshPmQg9sbEkGGzAs5wAjkGd5xaWGINLKAeksIL5HZEMiItORrgtip2ih4A2l7LsA==
|
703,141
|
A guy with a mental problem
|
A person needs to reach home by train but compulsively switches trains at every station. If they start with train arr1 at the first station, they will switch to train arr2 at the next station, and then switch back to train arr1 at the following station, and so on. Similarly, if they start with train arr2, they will switch to train arr1 at the next station, and continue alternating.
Examples:
Input:
arr1 = [2, 1, 2], arr2 = [3, 2, 1]
Output:
5
Explanation:
Starting with train arr2 yields the minimum total time of 5.
Input:
arr1 = [1, 3, 1, 2] arr2 = [2, 2, 3, 1]
Output:
5
Explanation:
Starting with train arr1 yields the minimum total time of 5.
1 ≤ arr1.size(), arr2.size() ≤ 10**6
1 ≤arr1[i],arr2[i]≤
10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1616524107,
"func_sign": [
"public int minTime(int[] arr1, int[] arr2)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\npublic class Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int t = scanner.nextInt();\n scanner.nextLine(); // Consume the newline character\n\n while (t-- > 0) {\n // Read input for arr1\n String input = scanner.nextLine();\n String[] inputArray = input.split(\" \");\n int[] arr1 = new int[inputArray.length];\n for (int i = 0; i < inputArray.length; i++) {\n arr1[i] = Integer.parseInt(inputArray[i]);\n }\n\n // Read input for arr2\n input = scanner.nextLine();\n inputArray = input.split(\" \");\n int[] arr2 = new int[inputArray.length];\n for (int i = 0; i < inputArray.length; i++) {\n arr2[i] = Integer.parseInt(inputArray[i]);\n }\n\n Solution solution = new Solution();\n System.out.println(solution.minTime(arr1, arr2));\n System.out.println(\"~\");\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n public int minTime(int[] arr1, int[] arr2) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616524107,
"func_sign": [
"min_time(self, arr1, arr2)"
],
"initial_code": "if __name__ == \"__main__\":\n import sys\n input = sys.stdin.read\n data = input().splitlines()\n\n t = int(data[0])\n index = 1\n for _ in range(t):\n arr1 = list(map(int, data[index].split()))\n arr2 = list(map(int, data[index + 1].split()))\n index += 2\n\n solution = Solution()\n print(solution.min_time(arr1, arr2))\n print(\"~\")\n",
"solution": "class Solution:\n # Calculate the minimum time to reach home by alternating between two trains\n def min_time(self, arr1, arr2):\n # Initialize sums for even and odd index positions for both train arrays\n sum_arr1_even = sum_arr1_odd = 0\n sum_arr2_even = sum_arr2_odd = 0\n\n n = len(arr1) # Get the number of stations\n\n # Loop through each station\n for i in range(n):\n if i % 2 == 0:\n # Add times from arr1 and arr2 at even indices\n sum_arr1_even += arr1[i]\n sum_arr2_even += arr2[i]\n else:\n # Add times from arr1 and arr2 at odd indices\n sum_arr1_odd += arr1[i]\n sum_arr2_odd += arr2[i]\n\n # Calculate total times for starting on arr1 and switching to arr2 and vice versa\n sum_arr1_even += sum_arr2_odd\n sum_arr1_odd += sum_arr2_even\n\n # Return the minimum of the two calculated times\n return min(sum_arr1_even, sum_arr1_odd)\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def min_time(self, arr1, arr2):\n # code here\n"
}
|
eJy1VUsOgjAQdWHiNSZdEwMtYHThOUzEuFAWbtAFJCZG4yH0vpapLb8WqGDbxUxhXh/TN8Nz+l7PJjg2C25sb+SUXLKUrIB4UZIvF0fVJg6Q+HqJD2l83J+ztIh48Id3B5owgwCoCoUlDrEF1IhEDUgsD5NYwqfKN8OZiPFwQQg8xQyPkLtGRGZA9JEgKJJiRxIuU7ekGmDCgIEPAXoBtxjfsYcK69cBrS4G9HkRuvQRmgTmqqyVp5Kuq01hu2UvUj0J3ZTE6C/E/vcB2iqzLDCp3w7FJaPrG3NpGePbh+SrKIEe2jfVi1evCZ4UlPLXte+SxTGW5dPsYoMaV+Vmx7haaGuKOWBUAo/ckf4u/Wtg95p/AD6y+7c=
|
704,459
|
Number Of Open Doors
|
Consider a long alley with a N number of doors on one side. All the doors are closed initially. You move to and fro in the alley changing the states of the doors as follows: you open a door that is already closed and you close a door that is already opened. You start at one end go on altering the state of the doors till you reach the other end and then you come back and start altering the states of the doors again.In the first go, you alter the states of doors numbered 1, 2, 3, , n.In the second go, you alter the states of doors numbered 2, 4, 6In the third go, you alter the states of doors numbered 3, 6, 9 You continue this till the Nth go in which you alter the state of the door numbered N.You have to find the number of open doors at the end of the procedure.
Examples:
Input:
N =
2
Output:
1
Explanation:
Initially all doors are closed.
After 1st go, all doors will be opened.
After 2nd go second door will be closed.
So, Only 1st door will remain Open.
Input:
N =
4
Output:
2
Explanation:
Following the sequence 4 times, we can
see that only 1st and 4th doors will
remain open.
Constraints:
1 <= N <= 10**12
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1619174244,
"func_sign": [
"static int noOfOpenDoors(Long N)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n Long N = Long.parseLong(read.readLine());\n\n Solution ob = new Solution();\n System.out.println(ob.noOfOpenDoors(N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\n\nclass Solution {\n // Function to calculate the number of open doors\n static int noOfOpenDoors(Long N) {\n int ans = (int)(Math.sqrt(N)); // Calculating the square root of N\n return ans; // Returning the answer\n }\n};",
"updated_at_timestamp": 1730474975,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int noOfOpenDoors(Long N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619174244,
"func_sign": [
"noOfOpenDoors(self, N)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N = int(input())\n\n ob = Solution()\n print(ob.noOfOpenDoors(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def noOfOpenDoors(self, N):\n ans = int(math.sqrt(N)) # Calculating the square root of N\n return ans\n",
"updated_at_timestamp": 1730474975,
"user_code": "#User function Template for python3\n\nclass Solution:\n def noOfOpenDoors(self, N):\n # code here"
}
|
eJydU0sOgjAQdcFBSNfEOJ2hUE9iIsaFsnCDLCAxMRoPoTdx5+Xk6y++JjAppGT6eNM3by7e7eFNmljcq83yqHZZXhZq7itKMlKBr9JDnm6KdLvel8U7dU4ydQr8n/MGAAQAYsRgAcC2wVGV/I9kMlojdKwlJBOyA82CitUkkcRsBJOLYZkhcTRLaKLYQjTVAUuPTCisyVG6aIO4MSe67GAEtShkAUZEmAk1ojcBBNZZrMRwMWzbvo9L9p20lux4C1dfSQKHxuXk3osOHzrpm9lzjdAYJQYKQd3zLchr1cpUb1hk99fVdfoEN353rg==
|
704,433
|
Reach the Nth point
|
There are N points on the road, you can step ahead by 1 or 2 . If you start from a point 0, and can only move from point i to point i+1 after taking a step of length one, find the number of ways you can reach at point N.
Examples:
Input:
N =
4
Output:
5
Explanation:
Number of ways to reach at 4th
point are {1, 1, 1, 1}, {1, 1, 2},
{1, 2, 1} {2, 1, 1}, {2, 2}.
Input:
N = 5
Output:
8
Explanation:
Number of ways to reach at 5th
point are {1, 1, 1, 1, 1},
{1, 1, 1, 2}, {1, 1, 2, 1}, {1, 2, 1, 1},
{2, 1, 1, 1}{1, 2, 2}, {2, 1, 2}, {2, 2, 1}
Constraints:
1 ≤ N ≤ 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int nthPoint(int n)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n int n = Integer.parseInt(br.readLine().trim());\n Solution ob = new Solution();\n int ans = ob.nthPoint(n);\n System.out.println(ans); \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730474921,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public int nthPoint(int n)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"nthPoint(self,n)"
],
"initial_code": "# Initial Template for Python 3\n\nimport sys\nsys.setrecursionlimit(10**6)\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n = int(input())\n ob = Solution()\n ans = ob.nthPoint(n)\n print(ans)\n",
"solution": "class Solution:\n def nthPoint(self, n):\n mod = 1000000007\n dp = [0] * (n + 1)\n dp[0] = 1\n dp[1] = 1 # ways to reach the 1st stair\n for i in range(2, n + 1):\n dp[i] = (dp[i - 1] % mod + dp[i - 2] % mod) % mod\n return dp[n]\n",
"updated_at_timestamp": 1730474921,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef nthPoint(self,n):\n\t\t# Code here"
}
|
eJylk89Kw0AQhz30QcKei8z/nfVJBCMeNAcvsYcUCiL4EO1jePMBTYONCjupaE6B7Dffzswvr6vD++pieq7fxpeb5/TYb7ZDumoStj1CWjep2226+6F7uHvaDp/fvLR9elk3P49TdByhiNUIjQg2hZFiqVEIEZadCGS01WURpsRgjpQDW9xX1lwKV6ehMSdYDAo5Rr4IJCFiIY98oVBQiLNWwUkYkcWyoRNTVXnShrSOQy2etU7D0f69zEIiiNmzCEQtzDWiAkZKGTUI4tdd/naDxTGwOqOB1/MVxxn5OH2LYnLSnln+YuN4LgAo0T84k/8e+bz+dqr5uw3c7i8/AKtYXuY=
|
705,705
|
Help a Thief!!!
|
You have to help a thief to steal as many as GoldCoins as possible from a GoldMine. There he saw N Gold Boxes an each Gold Boxes consists of Ai Plates each plates consists of Bi Gold Coins. Your task is to print the maximum gold coins theif can steal if he can take a maximum of T plates.
Examples:
Input:
T =
3,
N =
3
A[] =
{1, 2, 3}
B[] =
{3, 2, 1}
Output:
7
Explanation:
The thief will take 1 plate of coins
from the first box and 2 plate of coins
from the second plate. 3 + 2*2 = 7.
Input:
T =
0,
N =
3
A[] =
{1, 3, 2}
B[] =
{2, 3, 1}
Output:
0
Explanation:
The thief can't take any plates.
So he can't steal any coins.
Constraints:
0 <= T,N <= 10**4
1 <= A[i] <= 10**4
1 <= B[i] <= 10**4
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int maxCoins(int[] A, int[] B, int T, int N)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n int T = Integer.parseInt(S[0]);\n int N = Integer.parseInt(S[1]);\n \n String S1[] = read.readLine().split(\" \");\n String S2[] = read.readLine().split(\" \");\n \n int[] A = new int[N];\n int[] B = new int[N];\n \n for(int i=0; i<N; i++)\n {\n A[i] = Integer.parseInt(S1[i]);\n B[i] = Integer.parseInt(S2[i]);\n }\n\n Solution ob = new Solution();\n System.out.println(ob.maxCoins(A,B,T,N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730479216,
"user_code": "class Solution {\n static int maxCoins(int[] A, int[] B, int T, int N) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxCoins(self, A, B, T, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n T, N = map(int, input().split())\n A = list(map(int, input().split()))\n B = list(map(int, input().split()))\n\n ob = Solution()\n print(ob.maxCoins(A, B, T, N))\n print(\"~\")\n",
"solution": "class Solution:\n # Function to find the maximum and maximum number of\n # coins that can be obtained given the budget and\n # the number of coins available\n def maxCoins(self, A, B, T, N):\n # If the budget is 0 or less than the minimum coin value,\n # then no coins can be obtained, so return 0\n if T == 0 or T < min(A):\n return 0\n\n # Creating a list of tuples to store the profit and value\n # of each coin, so that we can sort them in descending order\n profit = []\n for i in range(N):\n profit.append((B[i], A[i]))\n profit.sort(reverse=True)\n\n # Initializing variables for the remaining budget and maximum coins\n t = T\n maxc = 0\n\n # Iterating over the sorted coins\n for j in range(N):\n # If the budget is exhausted, break the loop\n if t == 0:\n break\n # If the budget is greater than or equal to the value\n # of the current coin, use the entire value of the coin\n if t >= profit[j][1]:\n maxc += profit[j][0]*profit[j][1]\n t -= profit[j][1]\n # If the budget is less than the value of the current coin,\n # use the remaining budget to get maximum number of coins\n else:\n maxc = maxc + t*profit[j][0]\n t = 0\n\n # Return the maximum number of coins that can be obtained\n return maxc\n",
"updated_at_timestamp": 1730479216,
"user_code": "#User function Template for python3\n\nclass Solution:\n def maxCoins(self, A, B, T, N):\n # code here "
}
|
eJy9VcFOwzAM5cCBz7ByRBNq0jotfAkSRRxgBy5lh05CQiA+Av4Xv7TpNLVO6Sro1Jc08vxs5zn5PP+2F2fhub2Uyd2beW52+9bckLF1YzN5qOgm5AB5WBGoG8a0M7EcDTKzIbN93W0f2+3Tw8u+jd5gkYX/fdSNed/QMVVwwHEcQwzmWh5ABSgBXmGcIbRd9IfckBoyAx15eUt5K1D2aYopjX5aujqxOIcnRzkVxPjwMhTy6VR3mi+HWMs+B8RqXb8bZKu4ZTAKJlqWWg4lz9Qv7Ji6L3UzsQhghRDmCcbgzU5vQyKMwAgoADnAAbRaw5xTKq3CSDYK/1DlrjtyHlqkyroKh1L3ai6GNnKxgZRI8l8oGFqCJ/EonoVBmERRYVaEVQcOrUd8QqaxqP2wUJpJmfNyf0q/lv/asOubtRfRX/XsJLdmfOIpbN3yk9hnaS3TSG6n6OPorkJUa+4rnr+vhpMAMpw/DXjdceAzTkW0SF7lSn3df139AHwoExU=
|
702,894
|
Smallest subarray with sum greater than x
|
Givena numberx andan array of integers arr, find the smallest subarray with sum greater than the given value. If such a subarray do not exist return 0 in that case.
Examples:
Input:
x = 51, arr[] = [1, 4, 45, 6, 0, 19]
Output:
3
Explanation:
Minimum length subarray is [4, 45, 6]
Input:
x = 100, arr[] = [1, 10, 5, 2, 7]
Output:
0
Explanation:
No subarray exist
Constraints:
1 ≤ arr.size, x ≤ 10**5
0 ≤ arr[] ≤ 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1618657724,
"func_sign": [
"public static int smallestSubWithSum(int x, int[] arr)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n\n while (T > 0) {\n int x = Integer.parseInt(br.readLine().trim());\n String[] input = br.readLine().trim().split(\" \");\n int[] arr = Arrays.stream(input).mapToInt(Integer::parseInt).toArray();\n\n Solution solution = new Solution();\n System.out.println(solution.smallestSubWithSum(x, arr));\n\n T--;\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n public static int smallestSubWithSum(int x, int[] arr) {\n int n = arr.length; // Get the size of the array\n int curr_sum = 0, min_len = n + 1; // Initialize current sum and minimum length\n int start = 0, end = 0; // Initialize start and end pointers\n\n // Traverse the array\n while (end < n) {\n // Expand the window by adding elements to curr_sum until it exceeds x\n while (curr_sum <= x && end < n) curr_sum += arr[end++];\n\n // Shrink the window from the left while curr_sum is greater than x\n while (curr_sum > x && start < n) {\n // Update the minimum length if the current window is smaller\n if (end - start < min_len) min_len = end - start;\n\n // Remove elements from the start of the window\n curr_sum -= arr[start++];\n }\n }\n\n // If no valid subarray is found, return 0\n if (min_len > n) return 0;\n return min_len; // Return the minimum length\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n public static int smallestSubWithSum(int x, int[] arr) {\n // Your code goes here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618657724,
"func_sign": [
"smallestSubWithSum(self, x, arr)"
],
"initial_code": "def main():\n T = int(input())\n\n while T > 0:\n x = int(input())\n a = [int(x) for x in input().strip().split()]\n print(Solution().smallestSubWithSum(x, a))\n\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n\n def smallestSubWithSum(self, x, arr):\n n = len(arr)\n curr_sum = 0\n min_len = n + 1\n start = 0\n end = 0\n\n while end < n:\n while curr_sum <= x and end < n:\n curr_sum += arr[end]\n end += 1\n\n while curr_sum > x and start < n:\n if end - start < min_len:\n min_len = end - start\n curr_sum -= arr[start]\n start += 1\n\n if min_len > n:\n return 0\n return min_len\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def smallestSubWithSum(self, x, arr):\n # Your code goes here \n \n"
}
|
eJytk8FKxEAMhj3oe4Q5L5JkJq27TyJY2YNW8FL30AVBXHwIfV+TmbKwSNZOtafSId/8/5+/H5dfT1cX+bnd6svdW3gedvsxbCBQNwh2AwEhCDC0cAPEwPotrCD0r7v+Yewfty/7cZpouuGgh+8rOMW0ohhFMMTCSEZsXI44HEK9mwWUFRGiZGUuJTkUzq5QRxFaVWWwainRpChA1IdiEBpfCDqMtblBM6FuLBJfRvQSsZkkk4xkoVQz1jpSYhAjpHoCUXGSozQ/uiA5sxkvEMa8Ga3YMZGSbvWOS+NEzveMPB3zI5mx2yi/bdfTcVoQWsTIbYcfdWesLPykRbKYYokWe2KTE/8FleNZ/gMdi/KXu+fu9/7z+hsBO5Fj
|
712,306
|
Postfix to Infix Conversion
|
You are given a string that represents the postfix form of a valid mathematical expression. Convert it to its infix form.
Examples:
Input:
ab*c+
Output:
((a*b)+c)
Explanation:
The above output is its valid infix form.
3<=post_exp.length()<=10**4
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1666247053,
"func_sign": [
"static String postToInfix(String exp)"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.math.*;\nimport java.io.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n Scanner sc = new Scanner(System.in);\n int T = sc.nextInt();\n while (T-- > 0) {\n sc.nextLine();\n String s = sc.next();\n Solution obj = new Solution();\n String ans = obj.postToInfix(s);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\n\nclass Solution {\n static boolean isOperand(char x) {\n return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');\n }\n static String postToInfix(String exp) {\n // code here\n Stack<String> s = new Stack<String>();\n\n for (int i = 0; i < exp.length(); i++) {\n // Push operands\n if (isOperand(exp.charAt(i))) {\n s.push(exp.charAt(i) + \"\");\n }\n\n // We assume that input is\n // a valid postfix and expect\n // an operator.\n else {\n String op1 = s.peek();\n s.pop();\n String op2 = s.peek();\n s.pop();\n s.push(\"(\" + op2 + exp.charAt(i) + op1 + \")\");\n }\n }\n\n // There must be a single element\n // in stack now which is the required\n // infix.\n return s.peek();\n }\n}",
"updated_at_timestamp": 1730785685,
"user_code": "// User function Template for Java\n\nclass Solution {\n static String postToInfix(String exp) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1666332578,
"func_sign": [
"postToInfix(self, postfix)"
],
"initial_code": "# Initial Template for Python 3\n\n# Position this line where user code will be pasted.\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n postfix = input()\n ob = Solution()\n res = ob.postToInfix(postfix)\n print(res)\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nfrom collections import deque\n\n\nclass Solution:\n # Function to convert postfix expression to infix expression.\n def postToInfix(self, postfix):\n # Function to check if a character is an operand.\n def isOperand(x):\n return ('a' <= x <= 'z') or ('A' <= x <= 'Z')\n\n stack = deque()\n n = len(postfix)\n for i in range(n):\n if isOperand(postfix[i]):\n stack.append(postfix[i])\n else:\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append(\"(\" + op2 + postfix[i] + op1 + \")\")\n\n return stack[-1]\n",
"updated_at_timestamp": 1730785685,
"user_code": "#User function Template for python3\n\nclass Solution:\n def postToInfix(self, postfix):\n # Code here"
}
|
eJy9lM9u1EAMxjkgnmOVk8fuYOXKkyCRGiUzk39t022bbLJBIB4CXpUbEhPUqN12Z3YvMNrDHqLP/n7+7O9vf/5+9+bv+/jL//n0JWm67dAnHzZJmnV5YZCsY51cbBI3bZ3pnf18O/SPnwDkBAUapTRYdkpl3besS75ebF7qkLFOkCI6hSIwCFa8TEhn2tOMowy8C3fk30R7hbOSUfGg9C6sNosMuxEj/iaBvcyLv4Fhh2O4N8/KutJ71FzVGCHGUGgwBBbBSamWp6HCOqycF4UxiMzWEjmnI+YXdf9Dj9Isyr4M2aWA0+Hx3G7v7h96T8ITIUIUYQ6VuGd4YOgFBvE8YERPG/xY1OOL0qnqpiUUzYQh/SUCBI6h9FAEaoSG2rh2015d33QkqINdNwythiuEa4Eb6mJqnsESV/R51hLSm2XJ2RJaj5mtisBdneer9SroHRxByVBpqAXyZ86xiqgjucMwPy3uIRzWZyxy6sJgjrs5A9eU7s8MxvOjEw6JTY8nJFyj+x9F4qfSUzp5Jl8PM8v+0TjXe3V8qEFlkz4druA+rk2+PouagjvapocLGu37VHJO3mGXlmuFyx/v/wBpZSSJ
|
701,448
|
Strongly connected component (Tarjans's Algo)
|
Given a Directed Graph with V vertices and E edges, Find the members of strongly connected components in the graph.
Examples:
Input:
Output:
0 1 2,3,4,
Explanation:
We can clearly see that there are 3 Strongly
Connected Components in the Graph
as mentioned
in the Output.
Input:
Output:
0 1 2,
Explanation:
All of the nodes are connected to each other.
So, there's only one SCC as shown.
Constraints:
1
≤
V
≤
10**5
1
≤
E
≤
10**5
0
≤
u, v
≤
N-1
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public ArrayList<ArrayList<Integer>> tarjans(int V, ArrayList<ArrayList<Integer>> adj)"
],
"initial_code": "// Initial Template for Java\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass Gfg\n{\n public static void main (String[] args)\n {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n \n while(t-- > 0)\n {\n // arraylist of arraylist to represent graph\n ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n \n int V = Integer.parseInt(sc.next());\n int E = Integer.parseInt(sc.next());\n \n for(int i =0; i < V; i++)\n adj.add(i, new ArrayList<Integer>());\n \n for(int i = 1; i <= E; i++)\n { int u = Integer.parseInt(sc.next());\nint v = Integer.parseInt(sc.next());\n\n// adding directed edgese between \n// vertex 'u' and 'v'\nadj.get(u).add(v);\n }\n \n Solution ob = new Solution();\n ArrayList<ArrayList<Integer>> ptr = ob.tarjans(V, adj);\n\n for(int i=0; i<ptr.size(); i++)\n {\n for(int j=0; j<ptr.get(i).size(); j++)\n {\n if(j==ptr.get(i).size()-1)\n System.out.print(ptr.get(i).get(j));\n else\n System.out.print(ptr.get(i).get(j) + \" \");\n }\n System.out.print(\",\");\n }\n System.out.println();\n\t\t\nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "Gfg",
"solution": "// User function Template for Java\nclass Solution {\n // Function to return a list of lists of integers denoting the members\n // of strongly connected components in the given graph.\n static int time = 0;\n int[] disc;\n int[] low;\n boolean[] stkMember;\n Stack<Integer> stk = new Stack<Integer>();\n // (discovery,low)\n ArrayList<ArrayList<Integer>> result;\n\n public ArrayList<ArrayList<Integer>> tarjans(int V, ArrayList<ArrayList<Integer>> adj) {\n // code here\n low = new int[V];\n Arrays.fill(low, -1);\n disc = new int[V];\n Arrays.fill(disc, -1);\n stkMember = new boolean[V];\n result = new ArrayList<>();\n Stack<Integer> stk = new Stack<Integer>();\n for (int i = 0; i < V; i++) {\n if (disc[i] == -1) dfs(adj, stk, i);\n }\n Collections.sort(\n result,\n new Comparator<ArrayList<Integer>>() {\n @Override\n public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {\n return o1.get(0).compareTo(o2.get(0));\n }\n });\n return result;\n }\n\n public void dfs(ArrayList<ArrayList<Integer>> adj, Stack<Integer> stack, int u) {\n disc[u] = time;\n low[u] = time;\n stkMember[u] = true;\n stk.push(stack.push(u));\n time++;\n ArrayList<Integer> nbr = adj.get(u);\n for (Integer n : nbr) {\n if (disc[n] == -1) {\n dfs(adj, stack, n);\n low[u] = Math.min(low[u], low[n]);\n } else if (stkMember[n]) {\n low[u] = Math.min(low[u], disc[n]);\n }\n }\n int w = -1;\n if (low[u] == disc[u]) {\n ArrayList<Integer> res = new ArrayList<>();\n while (w != u) {\n w = stack.pop();\n stkMember[w] = false;\n res.add(w);\n }\n Collections.sort(res);\n result.add(res);\n }\n }\n}\n",
"updated_at_timestamp": 1730273609,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n //Function to return a list of lists of integers denoting the members \n //of strongly connected components in the given graph. \n public ArrayList<ArrayList<Integer>> tarjans(int V, ArrayList<ArrayList<Integer>> adj) \n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"tarjans(self, V, adj)"
],
"initial_code": "# Initial Template for Python 3\nfrom collections import OrderedDict\nimport sys\n\nsys.setrecursionlimit(10**6)\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n V, E = list(map(int, input().strip().split()))\n adj = [[] for i in range(V)]\n for i in range(E):\n a, b = map(int, input().strip().split())\n adj[a].append(b)\n\n for i in range(V):\n adj[i] = list(OrderedDict.fromkeys(adj[i]))\n\n ob = Solution()\n ptr = ob.tarjans(V, adj)\n\n for i in range(len(ptr)):\n for j in range(len(ptr[i])):\n if j == len(ptr[i]) - 1:\n print(ptr[i][j], end=\"\")\n else:\n print(ptr[i][j], end=\" \")\n print(\",\", end=\"\")\n print()\n print(\"~\")\n",
"solution": "# Backend Complete Function solution for python3\n\nclass Solution:\n\n # vector to store the members of the strongly connected components.\n ans = []\n temp = []\n Time = 0\n\n def SCCUtil(self, adj, u, low, disc, stackMember, st):\n # initializing discovery time and low value.\n disc[u] = self.Time\n low[u] = self.Time\n self.Time += 1\n stackMember[u] = True\n st.append(u)\n\n # traversing over the adjacent vertices.\n for v in adj[u]:\n # If v is not visited yet, then we call the function\n # recursively for adjacent node for it.\n if disc[v] == -1:\n self.SCCUtil(adj, v, low, disc, stackMember, st)\n\n # checking if the subtree rooted with v has a connection to\n # one of the ancestors of u\n # Case 1: (per above discussion on Disc and Low value)\n low[u] = min(low[u], low[v])\n elif stackMember[v] == True:\n # updating low value of 'u' only if 'v' is still in stack\n # (i.e. it's a back edge, not cross edge).\n # Case 2 (per above discussion on Disc and Low value)\n low[u] = min(low[u], disc[v])\n\n # if head node is found, pop the stack and store\n # strongly connected components.\n if low[u] == disc[u]:\n while len(st) > 0 and u != st[-1]:\n w = st.pop()\n self.temp.append(w)\n stackMember[w] = False\n self.ans.append(self.temp)\n self.temp = []\n\n # Function to return a list of lists of integers denoting the members\n # of strongly connected components in the given graph.\n def tarjans(self, V, adj):\n self.ans = []\n self.temp = []\n\n # marking all the vertices as not visited and initializing parent\n # and visited and ap(articulation point) arrays.\n disc = [-1] * (V)\n low = [-1] * (V)\n stackMember = [False] * (V)\n st = []\n\n # calling the recursive helper function to find articulation points\n # in DFS tree rooted with vertex 'i'.\n for i in range(V):\n if disc[i] == -1:\n # we call the SCCUtil function.\n self.SCCUtil(adj, i, low, disc, stackMember, st)\n\n # sorting all the lists in final answer list.\n for j in range(len(self.ans)):\n self.ans[j].sort()\n self.ans.sort()\n\n return self.ans\n",
"updated_at_timestamp": 1730273609,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to return a list of lists of integers denoting the members \n #of strongly connected components in the given graph.\n def tarjans(self, V, adj):\n # code here"
}
|
eJydVMtOwzAQ5ID4jpHPFrIdJ3H4EiSMOEAkuLg9pBISKuIj4H/xOk1bSNZJk8PKj3hmd2btr+ufzc1V+u5f4+DhQ7yF7a4TdxDaB62gSx9ijGMYHwwUhcKHAtYHi7hb0rRC7UMN54NDRdPGh4ZGup8qQolrQkK079v2uWtfnja7buBCBEUEgUMjI6z04TP+vZf4m5GD1qOERrmUx4QqCpY26hw5URI9R5vQzln/KaBoo5gpL1OWNtB2vq6hJNfL6yho1ftEJzWtqz65JHvyQ+XzSnLXkpAiCpthBoY7YzB4xR1k6QxWclrYCafmJGBtH3f/yRS2KOonyXodhTYLrR6u07mlM6Xg0Mlw865Q56xxBuusWdPkYLu8uajND00+lVlGhekaFqh3+qZ1pOdwMedRcepIVvTLLkR63HnBJHcp6PlfljiPLvaP37e//bHbqg==
|
703,869
|
Shortest un-ordered subarray
|
Given an array arr of distinct numbers. Find the length of the shortest unordered (neither increasing nor decreasing) subarray in the given array. If there is no subarray then return 0.
Examples:
Input:
arr[] = [7, 9, 10, 8, 11]
Output:
3
Explanation:
Shortest unsorted subarray is 9, 10, 8 which is of 3 elements.
Input:
arr[] = [1, 2, 3, 5]
Output:
0
Explanation:
There is no subarray.
Constraints:
1 <= arr.size() <= 10**6
1 <= arr[i] <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617815784,
"func_sign": [
"public int shortestUnorderedSubarray(int arr[])"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n long res = obj.shortestUnorderedSubarray(arr);\n\n System.out.println(res);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function to find the length of the shortest unordered subarray\n // in a given array.\n public int shortestUnorderedSubarray(int[] arr) {\n int n = arr.length;\n // Initializing minimum length, flag, and answer variables\n long min = Integer.MAX_VALUE;\n int flag = -1, ans = 1;\n // Iterating through the array\n for (int i = 1; i < n; i++) {\n // Checking if the array is increasing or decreasing\n if (flag == -1) {\n // If increasing, set flag to 1 and increment the answer\n if (arr[i] > arr[i - 1]) {\n flag = 1;\n ans++;\n }\n // If decreasing, set flag to 0 and increment the answer\n else {\n flag = 0;\n ans++;\n }\n }\n // If the array is already in increasing or decreasing order\n else {\n // If still increasing, continue to next element\n if (arr[i] > arr[i - 1] && flag == 1) continue;\n // If increasing after decreasing, update flag to 1, increment answer\n // and check if it is the shortest unordered subarray\n else if (arr[i] > arr[i - 1] && flag == 0) {\n flag = 1;\n ans++;\n if (ans >= 3 && min > ans) min = ans;\n }\n // If still decreasing, continue to next element\n else if (arr[i] < arr[i - 1] && flag == 0) continue;\n // If decreasing after increasing, increment answer, update flag to 0,\n // and check if it is the shortest unordered subarray\n else if (arr[i] < arr[i - 1] && flag == 1) {\n ans++;\n flag = 0;\n if (ans >= 3 && min > ans) min = ans;\n }\n }\n }\n // If no unordered subarray is found, return 0\n if (min == Integer.MAX_VALUE) return 0;\n // Otherwise, return the length of the shortest unordered subarray\n else return (int) min;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n public int shortestUnorderedSubarray(int arr[]) {}\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617815784,
"func_sign": [
"shortestUnorderedSubarray(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n # n = int(input())\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n ans = ob.shortestUnorderedSubarray(arr)\n print(ans)\n tc -= 1\n print(\"~\")\n",
"solution": "class Solution:\n\n def shortestUnorderedSubarray(self, arr):\n n = len(arr)\n # Initializing minimum length, flag, and answer variables\n Min = float('inf')\n flag = -1\n ans = 1\n\n # Iterating through the array\n for i in range(1, n):\n # Checking if the array is increasing or decreasing\n if flag == -1:\n # If increasing, set flag to 1 and increment the answer\n if arr[i] > arr[i - 1]:\n flag = 1\n ans += 1\n # If decreasing, set flag to 0 and increment the answer\n else:\n flag = 0\n ans += 1\n # If the array is already in increasing or decreasing order\n else:\n # If still increasing, continue to next element\n if arr[i] > arr[i - 1] and flag == 1:\n continue\n # If increasing after decreasing, update flag to 1, increment answer\n # and check if it is the shortest unordered subarray\n elif arr[i] > arr[i - 1] and flag == 0:\n flag = 1\n ans += 1\n if ans >= 3 and Min > ans:\n Min = ans\n # If still decreasing, continue to next element\n elif arr[i] < arr[i - 1] and flag == 0:\n continue\n # If decreasing after increasing, increment answer, update flag to 0,\n # and check if it is the shortest unordered subarray\n elif arr[i] < arr[i - 1] and flag == 1:\n ans += 1\n flag = 0\n if ans >= 3 and Min > ans:\n Min = ans\n\n # If no unordered subarray is found, return 0\n if Min == float('inf'):\n return 0\n # Otherwise, return the length of the shortest unordered subarray\n else:\n return Min\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def shortestUnorderedSubarray(self, arr):\n #Code here\n \n \n "
}
|
eJztVsuOHEUQ5OAjEgf/QGjObquy3uUvQWIQB9gDl8GHtYSEQHwE/C8RWdWeMd6ZZbGNhOQd7Wi6OisfkRFZ9fuzP59/9YX/ff0lf3zzy+HH0+s394dXOKTjqR5PBR0DCRWZD8eTBcSAFJADStAz//k+oiCj0W5wh4XDCxzufn599/393Q/f/fTmfjmlNf3y+7fj6fDrC1zEi8dTo6/CzfRVYQZLMC53hYgMIvdFAW56f9/1TH3AmGJF9MLkLXqq4DtaKF7Uo2V3oxzyY2U8GM4Y63giTLMYeWWcBmNRmUVdd/q+L4d8YVwcgL77NPdWPUpXV2wgRsSMyH6wTi42tSoRO+7PSBWpIHU1Lw3kiJyREzIr5WJjR1HYSUPJKMS6oHRULg7UiEr0yISKysWGFtAimqGx8RWN6XV0LrJBRDajJ3Tmy8WGETAihmFkDJKEbVQhXHWovEr+1upouwVN074toI/lS07LHoCRbEVl+Nb2VJhT2vMLqGMlrezLXglLYq9SULMFsKguVoglAnkyIjnOxaFu3sohtKM52skBLw54c8wpF3rMYWdtdjo39/6ufAQtk2P2LM8B8IfmL4obJd/AbZLV5H92uTFx6S8G9Z2OBSeRM0JnxM4InhE9I3xG/EwRiKARQusqg3ZdzKEdcbQultKO8Y1YWhNladdUNe0IqBFRI6RGTI1JGlE1wmpV3KZdFUjiJO0IrlXaVcmAdiSSFdoVEZZ2RZjSjnyzYo/pLFwZGtLtlIjYQ/qIPyKQGCQKiUMikVgkGomHXTSjnWjZ6yIA0R5LBZJD2aVBNtjSC4WT2i4idiHtygpq+pSbaFB2DUYniQvzPAHKHAJTwmxguRyg1bs8nHpht5o75u6xtP4u+1jDRAHiQwqijhgkIolPopXY5SwTsfXl1JGtydhkbTI32Vt3Yk2PTjHnmJPMWeY0c5450ZxpTjWb26aD9tZpWYGud/pGm9N+0Jz1tHTAxXi98rKe03pvYZ1a+TxRJSw2XJJCwGbYIrYbM/ra+ZXXQTW9Lp9cIMGiT5fsWZ+72725kwsSzpqD2D97rftn6X5+FnEemAsXRWDL2Aq2iq1h69gGX+k13zP2xsib/bszTpX1y46sVP42Jy+ojrr3ao1A6oRCmoOQeiOZOCs4Qtrty8OD561oHXROPuVsPZ/TMc+TOnzIUX2+wDzxzvKfU77Hj0X67epN78MueKTnE0nwP74o6Yz+fFf6fFf6xHelxyaKjoWPMxXenk7Xx8OtCfqpRoSnleyfJfbtHy//Ap57ZY4=
|
702,903
|
Partition Point in the Array
|
Given an array arr[] of integers. Find an element such that all the elements to its left are smaller and to its right are greater. Print -1 if no such element exists.
Examples:
Input:
arr[] = [4, 3, 2, 5, 8, 6, 7]
Output:
5
Explanation:
To the left of element 5 every element is smaller to it and to the right of element 5 every element is greater to it.
Input:
arr[] = [5, 6, 2, 8, 10, 9, 8]
Output:
-1
Explanation:
No such desired element is present in the array.
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int FindElement(int[] arr)"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n // int k = Integer.parseInt(br.readLine());\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n int ans = obj.FindElement(arr);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function to find the element from the array.\n int FindElement(int[] arr) {\n int n = arr.length;\n // Create an array 'SE[]' that will\n // store smaller element on right side.\n if (n == 1) return arr[0];\n int[] SE = new int[n + 1];\n // Create an another array 'GE[]' that\n // will store greatest element on left side.\n int[] GE = new int[n + 1];\n // initialize first and last index of SE[], GE[]\n GE[0] = arr[0];\n SE[n - 1] = arr[n - 1];\n // store greatest element from left to right\n for (int i = 1; i < n; i++) {\n if (GE[i - 1] < arr[i]) GE[i] = arr[i];\n else GE[i] = GE[i - 1];\n }\n // store smallest element from right to left\n for (int i = n - 2; i >= 0; i--) {\n if (arr[i] < SE[i + 1]) SE[i] = arr[i];\n else SE[i] = SE[i + 1];\n }\n // Now find a number which is greater than all\n // elements at it's left and smaller than all\n // then elements to it's right\n for (int j = 0; j < n; j++) {\n if ((j == 0 && j + 1 < n && arr[j] < SE[j + 1])\n || (j == n - 1 && j - 1 >= 0 && arr[j] > GE[j - 1])\n || (j + 1 < n && j - 1 >= 0 && arr[j] < SE[j + 1] && arr[j] > GE[j - 1])) return arr[j];\n }\n return -1;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n int FindElement(int[] arr) {\n // Your code goes here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"FindElement(self,arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n while t > 0:\n arr = list(map(int, input().split()))\n ob = Solution()\n res = ob.FindElement(arr)\n print(res)\n t -= 1\n print(\"~\")\n",
"solution": "class Solution:\n\n def FindElement(self, arr):\n n = len(arr) # Get the size of the array\n\n if n == 1:\n return arr[0] # Special case where there's only one element\n\n # Arrays to store the greater element on the left and smaller element on the right.\n SE = [float('inf')] * (n + 1)\n GE = [-float('inf')] * (n + 1)\n\n # Initializing the arrays with the first and last elements of the given array.\n GE[0] = arr[0]\n SE[n - 1] = arr[n - 1]\n\n # Calculating the greater element on the left for each index.\n for i in range(1, n):\n GE[i] = max(GE[i - 1], arr[i])\n\n # Calculating the smaller element on the right for each index.\n for i in range(n - 2, -1, -1):\n SE[i] = min(SE[i + 1], arr[i])\n\n # Iterating through the array to find the element.\n for j in range(n):\n # Checking if the current element satisfies the condition.\n if (j == 0 and arr[j] < SE[j + 1]) or \\\n (j == n - 1 and arr[j] > GE[j - 1]) or \\\n (j > 0 and j < n - 1 and arr[j] < SE[j + 1] and arr[j] > GE[j - 1]):\n return arr[j]\n\n # Returning -1 if no such element is found.\n return -1\n",
"updated_at_timestamp": 1729753320,
"user_code": "# function for adding one to number \nclass Solution:\n def FindElement(self,arr):\n # Your code goes here "
}
|
eJytlM1qwkAUhbsofY7DrKXMTyY/Pkmhli5qFqWQuogglEofon3fnhmNmpobHFPDYUaZHO755l6/bn/e7m7i52HJzeOHem1W61bNocyiMZqChUMGTznuDbSaQdWbVf3S1svn93XbvcDT20WjPmf4Y+ODFSqUKJCfOHXOueToBUcbCtMaljKeKqmKKoI8TH78LZxxVEb5sPK8p3Luc64F18JLoexoKPQfe/otNVOEPUApmbbdFWYj3h1gIuZTSFZ2BLOD29tkeyt/MIymrLeCSeZXBmtDS0OzirVKTVCO8DoW05UBkw6MN6Kh0Yd2ATbpJkO01DDy/cecYigxUwglFi724MCkcr44RsHuikEdmZIrx6R0E3DFly9JDn+YpMl/Vv3++o8GG6QqsTmHM4H+GabkDnn6vv8FWbu5mg==
|
700,276
|
Max sum in the configuration
|
Given an integer array(0-based indexing) a of size n. Your task is to return the maximum value of the sum of i*a[i] for all 0<= i <=n-1,where a[i] is the element at index i in the array. The only operation allowed is to rotate(clockwise or counterclockwise) the array any number of times.
Examples:
Input:
n = 4, a[] = {8, 3, 1, 2}
Output:
29
Explanation:
All the configurations possible by rotating the elements are:
3 1 2 8 here sum is 3*0+1*1+2*2+8*3 = 29
1 2 8 3 here sum is 1*0+2*1+8*2+3*3 = 27
2 8 3 1 here sum is 2*0+8*1+3*2+1*3 = 17
8 3 1 2 here sum is 8*0+3*1+1*2+2*3 = 11, so the maximum sum will be 29.
Input:
n = 3, a[] = {1, 2, 3}
Output:
8
Explanation:
All the configurations possible by rotating the elements are:
1 2 3 here sum is 1*0+2*1+3*2 = 8
3 1 2 here sum is 3*0+1*1+2*2 = 5
2 3 1 here sum is 2*0+3*1+1*2 = 5, so the maximum sum will be 8.
Constraints:
1<=n<=10**5
1<=a[]<=10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1616777501,
"func_sign": [
"long max_sum(int a[], int n)"
],
"initial_code": "import java.util.*;\n\nclass Maxsum_Among_All_Rotations_Array {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while (t > 0) {\n int n = sc.nextInt();\n int arr[] = new int[n];\n for (int i = 0; i < n; i++) arr[i] = sc.nextInt();\n\n System.out.println(new Solution().max_sum(arr, n));\n\n t--;\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "Maxsum_Among_All_Rotations_Array",
"solution": "class Solution {\n int maxSum(int[] arr) {\n int n = arr.length;\n int cum_sum = 0;\n for (int i = 0; i < n; i++) cum_sum += arr[i];\n\n int initial_val = 0;\n int max = 0;\n\n for (int i = 0; i < n; i++) {\n initial_val += i * arr[i];\n max = initial_val;\n }\n\n for (int i = 1; i < n; i++) {\n int temp = initial_val - (cum_sum - arr[i - 1]) + arr[i - 1] * (n - 1);\n initial_val = temp;\n if (temp > max) max = temp;\n }\n\n return max;\n }\n}",
"updated_at_timestamp": 1730270660,
"user_code": "class Solution {\n long max_sum(int a[], int n) {\n // Your code here\n }\n}\n"
}
|
{
"class_name": null,
"created_at_timestamp": 1616777501,
"func_sign": [
"max_sum(a,n)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n = int(input())\n arr = list(map(int, input().strip().split()))\n print(max_sum(arr, n))\n print(\"~\")\n",
"solution": "def max_sum(a, n):\n cum_sum = sum(a)\n\n # calculating initial value and setting max as initial value\n initial_val = 0\n max_val = 0\n for i in range(n):\n initial_val += i * a[i]\n max_val = initial_val\n\n for i in range(1, n):\n temp = initial_val - (cum_sum - a[i - 1]) + a[i - 1] * (n - 1)\n initial_val = temp\n if temp > max_val:\n max_val = temp\n\n return max_val\n",
"updated_at_timestamp": 1730270660,
"user_code": "#User function Template for python3\n\ndef max_sum(a,n):\n #code here"
}
|
eJydVEFOwzAQ7IH+Y+VzVXnXjp3wEiSCOJQcuLg9pFKlCsQj4Bfc+CB2iFBLNI7D2lEiOTPanfHu283H13o1xN1n/Lg/q+dwOPbqlhS3IW09hNqQ6k6Hbtd3T4/7Yz/+o9vw2gb1sqE/QJ0eaqgmT44qsmRIiAGNNIio+s2AZt6AejzN8dO4IAPAuoSVWJiNBTqA9jmJLpSJOtVRL0Z1GFiCjTurLtcAaS7EnZHRZFWMKWga1sJ7Im1ohihzcd6IfzvBCVnoBYuuilJhlEtkmCHgkeHHX0zkzaIW9PCWWINqmjJVeSovUiYP9MrCXCZu4wlROiKQFdP2YOcQiaRzY4QXD7LSNK27aoKH9+03wLmYvQ==
|
703,818
|
Find the fine
|
Given an array of car numbers car[],an array of penalties fine[], and an integer value date. The task is to find the total fine which will be collected on the given date. The fine is collected from odd-numbered cars on even dates and vice versa.
Examples:
Input:
date = 12, car[] = [2375, 7682, 2325, 2352], fine[] = [250, 500, 350, 200]
Output:
600
Explanation:
The date is 12 (even), so we collect the fine from odd-numbered cars. The odd-numbered cars and the fines associated with them are as follows:
2375 -> 250
2325 -> 350
The sum of the fines is 250+350 = 600
Input:
date = 8, car[] = [2222, 2223, 2224], fine[] = [200, 300, 400]
Output:
300
Constraints:
1 <= car.size <= 10**5
1 <= car[i], fine[i], date <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617813715,
"func_sign": [
"public long totalFine(int date, int car[], int fine[])"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n while (t-- > 0) {\n int date = Integer.parseInt(br.readLine().trim());\n String inputLine[] = br.readLine().trim().split(\" \");\n int n = inputLine.length;\n int car[] = new int[(int)(n)];\n for (int i = 0; i < n; i++) {\n car[i] = Integer.parseInt(inputLine[i]);\n }\n\n String inputLine2[] = br.readLine().trim().split(\" \");\n int n2 = inputLine.length;\n int fine[] = new int[(int)(n2)];\n for (int i = 0; i < n2; i++) {\n fine[i] = Integer.parseInt(inputLine2[i]);\n }\n\n Solution obj = new Solution();\n System.out.println(obj.totalFine(date, car, fine));\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n public long totalFine(int date, int car[], int fine[]) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617813715,
"func_sign": [
"totalFine(self, date, car, fine)"
],
"initial_code": "# Initial Template for Python 3\ndef main():\n T = int(input())\n\n while T > 0:\n date = int(input())\n car = [int(x) for x in input().strip().split()]\n fine = [int(x) for x in input().strip().split()]\n\n print(Solution().totalFine(date, car, fine))\n print(\"~\")\n\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "# User function Template for python3\nclass Solution:\n\n def totalFine(self, date, car, fine):\n # Number of cars\n n = len(car)\n even = 0\n odd = 0\n\n # Iterating over all the cars\n for i in range(n):\n # If car number is even, adding fine to even variable\n if car[i] % 2 == 0:\n even += fine[i]\n else:\n # If car number is odd, adding fine to odd variable\n odd += fine[i]\n\n # If date is even, returning odd fines\n if date % 2 == 0:\n return odd\n else:\n # If date is odd, returning even fines\n return even\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def totalFine(self, date, car, fine):\n #Code here\n \n \n "
}
|
eJzNVstuE0EQ5MCJryjtOULzfvAlSBhxAB+4LDk4EhIC8RHwcdz4FLprJoRA2lbsWKQPtevdntma6uoZf336/eezJ4yXP+Tm1afl/Xp5tVteYPGbtWtsVq+BoIGogaSBrCGvnXMIClEhKWSB5QLL9uPl9u1u++7Nh6vdnLfIq836ZbMuny9w+3s6kxsXD8VAjMREzMRCrMRG7Iqeg4WLMBEewgLFoTo0h+40w+AUskUppxiuL1AMxEhMxEwsxEpsxK4YZeLeKkpO0CnkuT7m71oyWi3Q9/Lc4BZdapZeIaY8yoQmgSqBIsHasEysGIsHltFT4jkCMx8zGzMXM9OSK4a9JdQyxFw7Qioi/V7/kG4h88pFNNzYDnMIZjpmKmaacJQcZ0kXeq37pfNOrsilNp0rxKz3tEqIZbNG9XOmncVJaiVLEl9MV1OE+UUoFChIzfW78+MKMr+Ah0KglNpWiKOp/iQhhj6CiMraHld70SYHdhjLIbj2Wp4CxSmYp1iQxqyyHrn4mg1m3RSrlRRG744uHf06Onf0sO4LfdSCNSmjRpYG3t72Tmnjdp4+/u2Vbppl2OGervmr9W6ZaLjIpisjHDvDZGxZyZ3jtDpNovy/NHr4qh7H5WZbvP8WeOi/wr9suZRD29f+nbUeamD7MKkPd5pw3e2uI/YMZ+soiX3ASkp1Md5ZYmttx3WuO6l1X397/gvenZ3n
|
703,338
|
Jay's Apples
|
Given a queue of persons represented by an array of integers, where each person is identified by a specific integer, find the minimum kilograms of apples that need to be distributed, ensuring that each person receives 1 kilogram of apples only once.
Examples:
Input:
arr[] = [1, 1, 1, 1, 1]
Output:
1
Explanation:
The person identified by '1' appears multiple times but will only receive 1 kilogram of apples once. Therefore, the minimum apples required is 1 kg.
Input:
arr[] = [1, 2, 3, 1, 2]
Output:
3
Explanation:
There are three distinct persons in the queue, so 3 kilograms of apples need to be distributed.
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int minimumApple(int[] arr)"
],
"initial_code": "import java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int t = Integer.parseInt(scanner.nextLine());\n\n Solution ob = new Solution(); // Instantiate the Solution object once\n\n while (t-- > 0) {\n String line = scanner.nextLine();\n String[] elements = line.split(\" \");\n int[] arr = new int[elements.length]; // Changed to int[]\n\n for (int i = 0; i < elements.length; i++) {\n arr[i] = Integer.parseInt(elements[i]);\n }\n\n System.out.println(ob.minimumApple(arr));\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1727776457,
"user_code": "// User function Template for Java\n\n// User function Template for Java\n\nclass Solution {\n public int minimumApple(int[] arr) {\n // Complete the function\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"minimumApple(self, arr)"
],
"initial_code": "def main():\n T = int(input())\n\n while T > 0:\n # Convert input to list of integers\n a = list(map(int, input().strip().split()))\n print(Solution().minimumApple(a))\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n def minimumApple(self, arr):\n # Use a set to store unique values\n unique_apples = set(arr)\n # Return the size of the set, which represents the minimum number of apples required\n return len(unique_apples)\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\n\nclass Solution:\n def minimumApple(self, arr):\n # Complete the function\n"
}
|
eJy1k8EKwjAQRD2Iv+GQgyeRbNO01S8RrHjQHryohwqCCH6E/q+boFU0ihuxEOihs/NmOzm2z71Oyz/jLr9M9mq52mxrNYKickWaDxIYpLDIkKPAEKRVH6rabap5XS1m6219V6hDH4EZmmUFyzMek/K4BCSaYR2HI3EsjsbxOKIrk2RY4kOZQCwQmzCaAaUgC8pAOagAyQyYton5ZBBYBLRPZiQWljPIfoIWKqxY4TxiJGJNuJNRKT0ApZryWIRbOx9QqGm9iOVDL3VTzLhG3oHfEcN/VMoxxCnd5ZAIzAtQEiS6oUesx+qY5gRWWpYfllr8cas/0lD2lev0NLgAARal0g==
|
701,365
|
Fractional Knapsack
|
Given weights and values of n items, we need to put these items in a knapsack of capacity w to get the maximum total value in the knapsack. Return a double value representing the maximum value in knapsack.Note: Unlike 0/1 knapsack, you are allowed to break the item here.The details of structure/class is defined in the comments above the given function.
Examples:
Input:
n = 3, w = 50, value[] = [60,100,120], weight[] = [10,20,30]
Output:
240.000000
Explanation:
Take the item with value 60 and weight 10, value 100 and weight 20 and split the third item with value 120 and weight 30, to fit it into weight 20. so it becomes (120/30)*20=80, so the total value becomes 60+100+80.0=240.0 Thus, total maximum value of item we can have is 240.00 from the given capacity of sack.
Input:
n = 2, w = 50, value[] = [60,100], weight[] = [10,20]
Output:
160.000000
Explanation:
Take both the items completely, without breaking. Total maximum value of item we can have is 160.00 from the given capacity of sack.
Constraints:
1 <= n <= 10**5
1 <= w <= 10**9
1 <= value
i
, weight
i
<= 10**4
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1729142017,
"func_sign": [
"double fractionalKnapsack(List<Integer> val, List<Integer> wt, int capacity)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GfG {\n\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim());\n\n while (t-- > 0) {\n // Read values array\n String[] valueInput = br.readLine().trim().split(\" \");\n List<Integer> values = new ArrayList<>();\n for (String s : valueInput) {\n values.add(Integer.parseInt(s));\n }\n\n // Read weights array\n String[] weightInput = br.readLine().trim().split(\" \");\n List<Integer> weights = new ArrayList<>();\n for (String s : weightInput) {\n weights.add(Integer.parseInt(s));\n }\n\n // Read the knapsack capacity\n int w = Integer.parseInt(br.readLine().trim());\n\n // Call fractionalKnapsack function and print result\n System.out.println(String.format(\n \"%.6f\", new Solution().fractionalKnapsack(values, weights, w)));\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "GfG",
"solution": "None",
"updated_at_timestamp": 1730827413,
"user_code": "// User function Template for Java\nclass Solution {\n // Function to get the maximum total value in the knapsack.\n double fractionalKnapsack(List<Integer> val, List<Integer> wt, int capacity) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1729142017,
"func_sign": [
"fractionalknapsack(self, val, wt, capacity)"
],
"initial_code": "# Position this line where user code will be pasted.\n\nif __name__ == '__main__':\n test_cases = int(input())\n for _ in range(test_cases):\n # Read values array\n values = list(map(int, input().strip().split()))\n\n # Read weights array\n weights = list(map(int, input().strip().split()))\n\n # Read the knapsack capacity\n W = int(input().strip())\n\n ob = Solution()\n print(\"%.6f\" % ob.fractionalknapsack(values, weights, W))\n print(\"~\")\n",
"solution": "class Item:\n\n def __init__(self, val, w):\n self.value = val\n self.weight = w\n\n\nclass Solution:\n # Function to get the maximum total value in the knapsack.\n def fractionalknapsack(self, values, weights, W):\n # Create a list of Item objects\n n = len(values)\n items = [Item(values[i], weights[i]) for i in range(n)]\n\n # Variable for current weight in the knapsack\n curr_weight = 0\n curr_value = 0\n\n # Sorting items based on value/weight ratio in descending order\n items = sorted(items, key=lambda x: (x.value / x.weight), reverse=True)\n\n # Iterating over all the items\n for i in range(n):\n # If current weight + item's weight is less than or equal to W,\n # add the item's value to the final value\n if curr_weight + items[i].weight <= W:\n curr_weight += items[i].weight\n curr_value += items[i].value\n # Otherwise, take the fraction of the item's value based on remaining weight\n else:\n accommodate = W - curr_weight\n value_added = items[i].value * (accommodate / items[i].weight)\n curr_value += value_added\n break\n # Returning final value\n return curr_value\n",
"updated_at_timestamp": 1730805296,
"user_code": "#User function Template for python3\nclass Solution:\n # Function to get the maximum total value in the knapsack.\n def fractionalknapsack(self, val, wt, capacity):\n #code here"
}
|
eJzNVUtOw0AMZcGOS1jZIVWRPf9wEiSKWEAXbEIXrYSEQBwC7ss4k04ErfOpStR0ZFlRx362n18+L7+vry6a57aIzt1b8Vyvt5viBgpa1oSIoNhoNoaNZePYeDaBTcWG/4zxDuz9lrUtFlCsXterx83q6eFlu2lzcEQsEdPVj2VdvC9gH0ObIeSsLiMxGZ3ageA7UEEADw4sGNCgGIRCAYUahYITcCZOybkZBKNhWIxvl5tAEWgCQ2AJHIEnCARVbARyJCvBIBNM6cjqYCUUsRAdC7KxMB8LrGJIqVqSez6i4Zi7nryQPZ89lz2bPZM9nT2VvRz6uLE2aYSqMoSh6tKRRjBw+RC3D78Uh/wvdJ++plZupTJa61I3Ty9K1Q06DT4RIREjESURJxGpHf+kZZKXxQ6Puks61TZLJZ8mtjjgESScpX0n6B8o1QLqSXZI836JXse4Xv2LYZ0dBBX3a54dnGc8QVY0ewZEMjgSrXGkPZW6QlOJqpHOseI7Z62hfzSGtLZlsOgHJLL9giZ1bpUaTyfVFRKdTqzTqwndE0itqK93EXI4A2Z3X5heifwD8/6r/AGuQ5wR
|
703,202
|
Smallest distinct window
|
Given a string s, your task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Examples:
Input:
"AABBBCBBAC"
Output:
3
Explanation: Sub-string -> "BAC"
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Constraints:
1 ≤ |Str| ≤ 10**5
String may contain both type of English Alphabets.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1616696799,
"func_sign": [
"public int findSubString( String str)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n\tpublic static void main(String[] args) throws IOException\n\t{\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim());\n while(t-->0)\n {\n String str = br.readLine();\n \n Solution obj = new Solution();\n System.out.println(obj.findSubString(str));\n \n \nSystem.out.println(\"~\");\n}\n\t}\n}\n\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n public int findSubString( String str) {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616696799,
"func_sign": [
"findSubString(self, str)"
],
"initial_code": "# Initial Template for Python 3\ndef main():\n T = int(input())\n while T > 0:\n string = input()\n ob = Solution()\n print(ob.findSubString(string))\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "from collections import defaultdict\n\n\nclass Solution:\n def findSubString(self, str):\n n = len(str)\n\n # if string is empty or having one char\n if n <= 1:\n return 1\n\n # Count all distinct characters.\n dist_count = len(set([x for x in str]))\n\n curr_count = defaultdict(lambda: 0)\n count = 0\n start = 0\n min_len = n\n\n # Now follow the algorithm discussed in below\n # post. We basically maintain a window of characters\n # that contains all characters of given string.\n for j in range(n):\n curr_count[str[j]] += 1\n\n # If any distinct character matched,\n # then increment count\n if curr_count[str[j]] == 1:\n count += 1\n\n # Try to minimize the window i.e., check if\n # any character is occurring more no. of times\n # than its occurrence in pattern, if yes\n # then remove it from starting and also remove\n # the useless characters.\n if count == dist_count:\n while curr_count[str[start]] > 1:\n curr_count[str[start]] -= 1\n start += 1\n\n # Update window size\n len_window = j - start + 1\n\n if min_len > len_window:\n min_len = len_window\n start_index = start\n\n # Return substring starting from start_index\n # and length min_len\n return min_len # str(str[start_index: start_index + min_len])\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findSubString(self, str):\n # Your code goes here\n \n \n "
}
|
eJxrYJlazMoABhE5QEZ0tVJmXkFpiZKVgpJhTF6iko6CUmpFQWpySWpKfH5pCUJKqVZHAU0xaaqTknEoN8ZueFJSMi4dJjgsSMFtCU4tqWnpOLSYY9NSUVFZBUGk+KaqsgKOSNHn6OTs4urm7uHp5e3j6+cfEBgUHBIaFh6BwwwjrL50dHR0cnJ2dnFxdXVzc3f38PD09PLy9vbx8fX18/P3DwgIDAwKCg4OCQkNDQsLD4+IiIyMisJhg6kBIe8ZxsQYgoIWHLo4E5Qp9jgHaYZqxKUTe2rBdATIGcgOwWWeETbz0IwjLaUj6USkMWyGEhFOWCMUf+YwI5AGEAZAEgNKoiY/ZRhiTRmEIgZPGic1zij2YgWZfgQaTUyZEDtFDwBuhNBm
|
702,809
|
Happiest Triplet
|
You are given the three arrays arr1[], arr2[], arr3[] of the same size . Find a triplet such that (maximum-minimum) in that triplet is the minimum of all the triplets. A triplet should be selected so that it should have one number from each of the three given arrays. This triplet is the happiest among all the possible triplets. Print the triplet in decreasing order.
Examples:
Input:
arr1[] = [5, 2, 8] , arr2[] = [10, 7, 12] , arr3[] = [9, 14, 6]
Output:
[7, 6, 5]
Explanation:
The triplet { 5,7,6 } has difference (maximum - minimum)= (7-5) =2 which is minimum of all triplets.
Input:
arr1[] = [15, 12, 18, 9] , arr2[] = [10, 17, 13, 8] , arr3[] = [14, 16, 11, 5]
Output:
[11, 10, 9]
Constraints:
1 ≤ arr1.size(),arr2.size(),arr3.size() ≤ 10**5
1 ≤ arr1[i],arr2[i],arr3[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1617121167,
"func_sign": [
"int[] smallestDifferenceTriplet(int arr1[], int arr2[], int arr3[])"
],
"initial_code": "import java.util.*;\n\n//Position this line where user code will be pasted.\npublic class Main {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n int t = Integer.parseInt(sc.nextLine());\n while (t-- > 0) {\n String line = sc.nextLine();\n String[] arr1Str = line.split(\" \");\n int[] arr1 = new int[arr1Str.length];\n for (int i = 0; i < arr1Str.length; i++) {\n arr1[i] = Integer.parseInt(arr1Str[i]);\n }\n\n line = sc.nextLine();\n String[] arr2Str = line.split(\" \");\n int[] arr2 = new int[arr2Str.length];\n for (int i = 0; i < arr2Str.length; i++) {\n arr2[i] = Integer.parseInt(arr2Str[i]);\n }\n line = sc.nextLine();\n String[] arr3Str = line.split(\" \");\n int[] arr3 = new int[arr3Str.length];\n for (int i = 0; i < arr3Str.length; i++) {\n arr3[i] = Integer.parseInt(arr3Str[i]);\n }\n\n Solution ob = new Solution();\n int[] ans = ob.smallestDifferenceTriplet(arr1, arr2, arr3);\n System.out.println(ans[0] + \" \" + ans[1] + \" \" + ans[2]);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "Main",
"solution": "class Solution {\n int[] smallestDifferenceTriplet(int arr1[], int arr2[], int arr3[]) {\n\n // sort the arrays\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n Arrays.sort(arr3);\n int n = arr1.length;\n // Variables to store the resulting triplet\n int res_min = 0, res_max = 0, res_mid = 0;\n int i = 0, j = 0, k = 0;\n // Initialize the difference to a very large value\n int diff = Integer.MAX_VALUE;\n // three pointers approach\n\n while (i < n && j < n && k < n) {\n int sum = arr1[i] + arr2[j] + arr3[k];\n int max = Math.max(arr1[i], Math.max(arr2[j], arr3[k]));\n int min = Math.min(arr1[i], Math.min(arr2[j], arr3[k]));\n // Check if the current difference is smaller than the previously found\n // difference\n if (diff > (max - min)) {\n diff = max - min;\n res_max = max;\n res_mid = sum - (max + min);\n res_min = min;\n }\n\n // Move the pointer of the array that contains the minimum element\n if (min == arr1[i])\n i++;\n else if (min == arr2[j])\n j++;\n else\n k++;\n }\n\n // Prepare the result array with the smallest difference triplet\n return new int[] {res_max, res_mid, res_min};\n }\n}",
"updated_at_timestamp": 1730269207,
"user_code": "// User function Template for Java\n\nclass Solution {\n int[] smallestDifferenceTriplet(int arr1[], int arr2[], int arr3[]) {\n // write code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617121167,
"func_sign": [
"smallestDifferenceTriplet(self,arr1,arr2,arr3)"
],
"initial_code": "# Initial Template for Python 3\n\nt = int(input())\n\nfor _ in range(0, t):\n arr1 = list(map(int, input().split()))\n arr2 = list(map(int, input().split()))\n arr3 = list(map(int, input().split()))\n ob = Solution()\n ans = ob.smallestDifferenceTriplet(arr1, arr2, arr3)\n print(ans[0], ans[1], ans[2])\n print(\"~\")\n",
"solution": "class Solution:\n def smallestDifferenceTriplet(self, arr1, arr2, arr3):\n # Sort the arrays\n arr1.sort()\n arr2.sort()\n arr3.sort()\n\n n = len(arr1)\n res_min, res_max, res_mid = 0, 0, 0\n i, j, k = 0, 0, 0\n diff = float('inf')\n\n # Iterate through the arrays\n while i < n and j < n and k < n:\n total_sum = arr1[i] + arr2[j] + arr3[k]\n max_value = max(arr1[i], arr2[j], arr3[k])\n min_value = min(arr1[i], arr2[j], arr3[k])\n\n # Move the pointer of the array containing the minimum element\n if min_value == arr1[i]:\n i += 1\n elif min_value == arr2[j]:\n j += 1\n else:\n k += 1\n\n # Update the result if the current difference is smaller\n if diff > (max_value - min_value):\n diff = max_value - min_value\n res_max = max_value\n res_mid = total_sum - (max_value + min_value)\n res_min = min_value\n\n # Return the result list\n return [res_max, res_mid, res_min]\n",
"updated_at_timestamp": 1730269207,
"user_code": "#User function Template for python3\n\nclass Solution:\n def smallestDifferenceTriplet(self,arr1,arr2,arr3):\n #code here.\n \n"
}
|
eJzFVUtOxDAMZcGGW1hZj1Cb1J2WkyARxAK6YBNm0ZGQEIhDwNHYcRgSu6Hp0LTTTCVSKR/HyXPsZ/f9/PP74oza9Zed3LyIR7Pbt+IKRK5NDvYbDmIDonneNfdt83D3tG+9Mqu8aSNeN3BwS+YaDIYl0hjk6AXjFljrpBskKG0UqMR3gMxAWRBFs9zOEHIEiVETrRJg3Cq2Hdl05Icc+qITJxhcu+ZB3Lxi2ZYWJfXIooIWinoZgaIb+BD1RQSWDS4I3M1z5zAncr2NgdvQZkuikrTcPPZA1uDbFN8WZ5kNiwfKPGqwoU2wzxtT5IKgj6BukS7HIIwlHao4dsiRrWghaUPFURF7PZxArX9922F7Q9hgxaICe49UE2+Vgd7UWx2bk6P7J3NmUocBZMfgJD8sdoQKgimjjoCuEg4KY1plTEvQjux1dnKm9hVtUNAWZdP4b2KQY6kF8p+9M8OuOL1O49dxiZZeBWZSVKfX0qXZ7Y/OsHMFJhz/y+5pwcjrEnONnF9K69uPyx90P3si
|
702,812
|
Min sum formed by digits
|
Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of the given array must be used to form the two numbers.
Examples:
Input:
N = 6
arr[] = {6, 8, 4, 5, 2, 3}
Output:
604
Explanation:
The minimum sum is formed by numbers
358 and 246
Input:
N = 5
arr[] = {5, 3, 0, 7, 4}
Output:
82
Explanation:
The minimum sum is formed by numbers
35 and 047
Constraints:
1 ≤ N ≤ 35
0 ≤ A[] ≤ 9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617816232,
"func_sign": [
"public static long minSum(int arr[], int n)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n\tpublic static void main(String[] args) throws IOException\n\t{\n\t BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int t =\n Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n while(t-->0)\n {\n int n = Integer.parseInt(br.readLine().trim());\n int a[] = new int[(int)(n)];\n String inputLine[] = br.readLine().trim().split(\" \");\n for (int i = 0; i < n; i++) {\n a[i] = Integer.parseInt(inputLine[i]);\n }\n \n Solution obj = new Solution();\n System.out.println(obj.minSum(a, n));\n \n \nSystem.out.println(\"~\");\n}\n\t}\n}\n\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730468739,
"user_code": "//User function Template for Java\nclass Solution {\n \n public static long minSum(int arr[], int n)\n {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617816232,
"func_sign": [
"minSum(self, arr, n)"
],
"initial_code": "import heapq as hq\n\nif __name__ == '__main__':\n T = int(input())\n\n for tcs in range(T):\n n = int(input())\n arr = [int(x) for x in input().split()]\n ob = Solution()\n print(ob.minSum(arr, n))\n print(\"~\")\n",
"solution": "class Solution:\n def minSum(self, arr, n):\n import heapq as hq\n hq.heapify(arr) # converting the array into a min heap\n\n n1 = 0\n n2 = 0\n\n i = 1\n while arr: # while there are still elements in the array\n if i % 2 == 0: # if the current index is even\n # pop the smallest element from the heap and add it to n1\n n1 = n1 * 10 + hq.heappop(arr)\n else: # if the current index is odd\n # pop the smallest element from the heap and add it to n2\n n2 = n2 * 10 + hq.heappop(arr)\n i += 1 # increment the index\n\n return n1 + n2 # return the sum of n1 and n2\n",
"updated_at_timestamp": 1730468739,
"user_code": "class Solution:\n def minSum(self, arr, n):\n # Your code goes here\n "
}
|
eJytlMFKxEAMhj2IzxF6XmQmmUxmfBLBigftwUvdwy4IovgQ+o7efAUzs9siQrrbuk0PpbTfn/xJ5v388/virF7XX/pw89I89uvtprmCxre9d22fwUMCBAGCCAEYXLOCpnted/eb7uHuabsZfoguSNu/tX3zuoI/JGx7B05ZXlmoLFJWobFBwxCzs2hc8sqaV9K8RPOKhVSJhYwWM2ZPLMnAoup5xaJiSbFhjy1ll/KLDcUOZ1pQkp5U4J0Nu/Bj4Bg0RhjC0kIKIUZJlhjV7qXqD1dnsCZ/5DuryxhYO+Mp8IQ0FyexVlH8E8VnQ3ryO6t2ClGy90TMItlKQ2+rDHO01DPjl2w1tfZ0ro5bILRketL0+CRCK8NTzyv/t6zfKofWInvrKJra8iwwY89F4kENoqpioxJO7+/sBT7NBu+PfqlmHHH4Y0LTjXr4z9yPJUNhjYRHDFpy4mEkbj8ufwD9VsuC
|
705,356
|
Villain Con
|
The minions are very elitist in nature. If minion x admires minion y, then y thinks too highly of himself and does not admire x back. Also, if x admires y, x also admires everyone that y admires.
All theminions are going to be present at the Villain Con. They wantto make sure that they do not dress in thesame color as someone who admires them.
There are N minions and M relations between them. The relations are given in a 2D array mat. Each relation is given in xi, yiformat where yiadmires xi. Find the minimum number of different colours that the minions will be dressing in.
Examples:
Input:
N = 5, M = 6
mat = {{1, 3},
{2, 3},
{3, 4},
{1, 4},
{2, 5},
{3, 5}}
Output:
3
Explanation:
If we assign red colour to 1 and 2,
green colour to 3, and blue colour to 4 and 5, then
every minion will have different coloured dresses
from the one who admires them.
Input:
N = 3, M = 2
mat = {{1,3},{2,3}}
Output:
2
Explanation:
If we assign red colour to 1 and 2, and green colour to 3, then the condition is satisfied.
Constraints:
1 ≤ N ≤ 10**5
1 ≤ M ≤ 2*10**5
1 ≤ x
i
, y
i≤ N
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int minColour(int N, int M, int mat[][])"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n public static void main(String args[])throws IOException\n {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while(t-- > 0) {\n String a[] = in.readLine().trim().split(\"\\\\s+\");\n int N = Integer.parseInt(a[0]);\n int M = Integer.parseInt(a[1]);\n int mat[][] = new int[M][2];\n for(int i = 0;i < M;i++){\n String a1[] = in.readLine().trim().split(\"\\\\s+\");\n mat[i][0] = Integer.parseInt(a1[0]);\n mat[i][1] = Integer.parseInt(a1[1]);\n }\n \n Solution ob = new Solution();\n System.out.println(ob.minColour(N, M, mat));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": null,
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n static int minColour(int N, int M, int mat[][]) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"minColour(self, N, M, mat)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, M = [int(x) for x in input().split()]\n mat = [[0]*2 for y in range(M)]\n for i in range(M):\n arr = input().split()\n mat[i][0] = int(arr[0])\n mat[i][1] = int(arr[1])\n\n ob = Solution()\n print(ob.minColour(N, M, mat))\n print(\"~\")\n",
"solution": "class Solution:\n # Recursive function to calculate the length of the longest path from node n\n def rec(self, n, adj, lenn):\n # If the length of the path from node n has already been calculated, return it\n if lenn[n]:\n return lenn[n]\n\n # Initialize the length of the path from node n as 0\n lenn[n] = 0\n\n # For each outgoing edge from node n\n for u in adj[n]:\n # Update the length of the path from node n as the maximum of the current length and the length of the path from node u\n lenn[n] = max(lenn[n], self.rec(u, adj, lenn))\n\n # Increment the length of the path from node n by 1\n lenn[n] = lenn[n] + 1\n\n # Return the length of the path from node n\n return lenn[n]\n\n # Function to find the minimum number of colors required to color the nodes\n def minColour(self, N, M, mat):\n # Initialize an adjacency list to represent the graph\n adj = [[] for i in range(N+1)]\n\n # Initialize an array to store the length of the longest path from each node\n lenn = [0 for i in range(N+1)]\n\n # Initialize the maximum value as -1\n maxVal = -1\n\n # Construct the adjacency list from the input matrix\n for i in mat:\n adj[i[0]].append(i[1])\n\n # For each node in the graph\n for i in range(1, N+1):\n # Update the maximum value with the length of the longest path starting from node i\n maxVal = max(maxVal, self.rec(i, adj, lenn))\n\n # Return the maximum value, which represents the minimum number of colors required\n return maxVal\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def minColour(self, N, M, mat):\n # code here"
}
|
eJztlkuOHEUURRmwAXZwVWMLZfwjWAkShRhAD5gUHtgSEgKxAGbAfjk3XtvChhR02wjZUIPu6q6KGy9PnPcyf/zw158/+mC/Pv2JN599d/n69vT5s8snuqTrLR1KjV/K11tWud6K6vVWxf+a+vXWNa63oXm9Ta3rbSkd/rZ/Zv+3+PPqbzZ/nvnk8kSXu2+f3n357O6rL755/uzFZiz54Xq7fP9Er5bQKOE4HlwDq1w/tbAssTELU1FiaapxUU2J5akrEZCGEhFpKhGSlrKv4VAmJbO3N8/KpOSiTEquyqTkpkxK7sqk5KFMSp7KvtylQko5VEgpSYWUwjX4IooKKaWqkFKaCimlq5BShorhTRVSylIlpR6qpNSkSkrNqqRUWBhGVSWlNlVSalc19qFKSp2qpNSltin6CgywGOD90QxTnKa4TNEAV/A7gl8Kfjn4leBXg18Lfj34jeA3Nz9jTIExB8YSGGtgbIGxB8YRGGdgXBuj+RljCow5MJbAWANjC4w9MI7AOAPj2hjNzxhTYMyBsQTGGhhbYOyBcQTGGRjXxhj8dtG75rJLrrvitgvuu96xy5272rWLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBaOLBWM7a7R21mh0Gef6f6e9pU5jbjWPr6RGSstqpDS6jpQGU0Ntau4/TouUNtRsEqKR0pY6Kf1QJ6UndVJ6VielF3VSOt1LSudsfDhd3X081EnpU91CLg0beWiQMpIGKSNrkDIYzqSMqkHKYAqQMjhjH/LQ8DyYGqSMpUnKPDQtdtIkZTLgSZlFk5RZNUmZTZOUyTQhZeKKZZmanitLy4Pl0CJlJS33R9YiZRUtUlbVImVxsyBldS1SFlOJlIVzlm69vB3sm4ytKVuaup1pW5m+jRlbmLl9WVsXZLUubsQjGjFFI+ZoxBKNWLesu1dH9OqMXl1bF2S1Lm7EIxoxRSPmaMQSjVi3rLtXR/TqjF5dWxdktS7Ial2Q1bogq3VBVuuCrNYFWa0LsloXZLUuyGpdkNW6IKt1QVbrgqzWBVmtC7JaF2S1LshqXZDVuiCrdUFW64Ks1gVZrQuyWhdktS7Ial2Q1bogq3VBVuuCrNYFWa0LsloXZLUuyGpdkNW6IKt1QVbrgqzWBVmtC7JaF2S1LshqXZDVuiCrdUFW64Ks1gVZrQuyWhdktS7Ial2Q1bpMP4ycP3OczkKdrjlZwdzbUp4sy6dDN9adPhedL/TrxWK/Hh3Q4s3j1j+Y07Fb89+4xyTtW3d/+Vg67x9L+95k7D3m3mLFDkfskGKHHDuU2KHGDi126Pc7xJOv3/NBO0N6pt37DWfX86aIXtH2YdIef9I2D5Q+/xdO6P5B8q2c0/ns/Ztz7fFjkc3568GD9R044S3/Gxzzfkz5XTP6WeH9nFZ/HBivY7teXwd3/xj8jw35KOiv75yf//Lxb7kAoR8=
|
703,309
|
Why is Melody so chocolaty?
|
Chunky gets happy by eating Melody. Given an array arr[], each element represents the happiness Chunky gets by eating the melody.Chunky knows why Melody is so chocolaty but will only tell you once you tell him the maximum happiness he can get by eating two adjacent melodies.
Examples:
Input:
arr[] = [1, 2, 3, 4, 5]
Output:
9
Explanation:
maximum happiness he can get is 9, selecting arr[3] = 4 and arr[4] = 5 which adds up to 9.
Input:
arr[] = [2, 1, 3, 4]
Output:
7
Explanation:
maximum happiness he can get is 7, selecting arr[2] = 3 and arr[3] = 4 which adds up to 7.
Constraints:
2 ≤ arr.size() ≤ 10**6
0 ≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int maxHappiness(List<Integer> arr)"
],
"initial_code": "// Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n\n int t = scanner.nextInt();\n scanner.nextLine(); // Consume the newline character\n\n Solution solution = new Solution();\n for (int i = 0; i < t; i++) {\n String input = scanner.nextLine();\n String[] parts = input.split(\" \");\n List<Integer> arr = new ArrayList<>();\n\n for (String part : parts) {\n arr.add(Integer.parseInt(part));\n }\n\n int result = solution.maxHappiness(arr);\n System.out.println(result);\n System.out.println(\"~\");\n }\n\n scanner.close();\n }\n}",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n public int maxHappiness(List<Integer> arr) {\n // code here.\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"max_happiness(self, arr)"
],
"initial_code": "def main():\n import sys\n input = sys.stdin.read\n data = input().strip().split('\\n')\n\n t = int(data[0])\n index = 1\n solution = Solution()\n\n results = []\n for _ in range(t):\n arr = list(map(int, data[index].split()))\n index += 1\n results.append(solution.max_happiness(arr))\n\n for result in results:\n print(result)\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n\n def max_happiness(self, arr):\n # Initializing ans as minimum value\n ans = float('-inf')\n for i in range(len(arr) - 1):\n # Finding the largest adjacent sum\n ans = max(ans, arr[i] + arr[i + 1])\n # Returning ans\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def max_happiness(self, arr):\n # code here"
}
|
eJxrYJm6kI8BDCJmARnR1UqZeQWlJUpWCkrGMXmGBiCgAKGAXAVLEFCACcfkQflQESUdBaXUioLU5JLUlPj80hKoQUZQ7XVAE8AaIEyQoCGYqVSro4BksRHIpmEBY/JggadABANX8CGCywBbcMGjASVyiBLCYSNSLKHZZYKWJhTQUwjMRwghLP5FdrAFmDQHk2Zg0hRMmhCRmLAzwebhSldGxiamCmbmFpZA1yDYCF8hIL4AsjAwMjYlnIrBXoWEBhLEYSbE9bhiGE+oE0ERDktMGwnoxZseYRFNsl4jhL2kmILXQFLjnMhIx1124bePPMuMaJIuqJcjDA1xuhJhCV1CBEfBR5tKZQjUKvCwsEQEBlgMZwFFfvVAYfCT3uIYjTDKIozIXGGMkVUHL6RKm8uEUEFDTMBhrcxGYmgaGlNcS8MdZGBGbCUBVoi1kkYrpkbLKfTIRg36wVBqxU7RAwCZMDsW
|
703,804
|
Count the subarrays having product less than k
|
Given an array of positive numbers, the task is to find the number of possible contiguous subarrays having product less than a given number k.
Examples:
Input:
n = 4, k = 10
a[] = {1, 2, 3, 4}
Output:
7
Explanation:
The contiguous subarrays are {1}, {2}, {3}, {4}
{1, 2}, {1, 2, 3} and {2, 3}, in all these subarrays
product of elements is less than 10, count of
such subarray is 7.
{2,3,4} will not be a valid subarray, because
2*3*4=24 which is greater than 10.
Input:
n = 7 , k = 100
a[] = {1, 9, 2, 8, 6, 4, 3}
Output:
16
Constraints:
1<=n<=10**6
1<=k<=10**15
1<=a[i]<=10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1617641104,
"func_sign": [
"public long countSubArrayProductLessThanK(long a[], int n, long k)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG {\n\tpublic static void main(String[] args) throws IOException\n\t{\n\t BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t PrintWriter out=new PrintWriter(System.out);\n int t = Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n while(t-->0)\n {\n StringTokenizer stt = new StringTokenizer(br.readLine());\n \n int n = Integer.parseInt(stt.nextToken());\n long k = Long.parseLong(stt.nextToken());\n \n long a[] = new long[n];\n String inputLine[] = br.readLine().trim().split(\" \");\n for (int i = 0; i < n; i++) {\n a[i] = Long.parseLong(inputLine[i]);\n }\n \n Solution obj = new Solution();\n out.println(obj.countSubArrayProductLessThanK(a, n, k));\n \nout.println(\"~\");\n}\n out.close();\n\t}\n}\n\n",
"script_name": "GFG",
"solution": "class Solution {\n\n public long countSubArrayProductLessThanK(long arr[], int n, long k) {\n long p = 1;\n long res = 0;\n for (int start = 0, end = 0; end < n; end++) {\n\n // Move right bound by 1 step. Update the product.\n p *= arr[end];\n\n // Move left bound so guarantee that p is again\n // less than k.\n while (start < end && p >= k) p /= arr[start++];\n\n // If p is less than k, update the counter.\n // Note that this is working even for (start == end):\n // it means that the previous window cannot grow\n // anymore and a single array element is the only\n // addendum.\n if (p < k) {\n int len = end - start + 1;\n res += len;\n }\n }\n\n return res;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution {\n \n public long countSubArrayProductLessThanK(long a[], int n, long k)\n {\n \n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617641104,
"func_sign": [
"countSubArrayProductLessThanK(self, a, n, k)"
],
"initial_code": "# Initial Template for Python 3\n\ndef main():\n T = int(input())\n while T > 0:\n n, k = [int(x) for x in input().strip().split()]\n arr = [int(x) for x in input().strip().split()]\n print(Solution().countSubArrayProductLessThanK(arr, n, k))\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n def countSubArrayProductLessThanK(self, a, n, k):\n p = 1\n res = 0\n start = 0\n\n for end in range(n):\n # Move right bound by 1 step. Update the product.\n p *= a[end]\n\n # Move left bound so guarantee that p is again less than k.\n while start < end and p >= k:\n p //= a[start]\n start += 1\n\n # If p is less than k, update the counter.\n # Note that this is working even for (start == end):\n # it means that the previous window cannot grow\n # anymore and a single array element is the only\n # addendum.\n if p < k:\n length = end - start + 1\n res += length\n\n return res\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def countSubArrayProductLessThanK(self, a, n, k):\n #Code here\n \n \n \n "
}
|
eJy9VEtOhEAQdWE8x0uvJ6ar+kd7EhMxLpSFG5wFk5gYjYfQE7rzFFYDJupMMcDCBhqS5r36varX0/fPs5N+XX7Ix9WTuW+3u85cwFDdkkWwdnwjgMEWHEByw8GbDUzzuG1uu+bu5mHXjUjmun2pW/O8wR8+wdlCyIKOqJBQqJFBDPIju7NwAd4q7C4o7AXdsxffQuEmkAPJRwY7cIaTowRP8OJ9QpD/MiIhJiRS7HmrRVO8lcM4+i/BVWACSyCpj8IplOQ0SkYsEYQhL4c3LS8qqWBk13zRUTpIS4lIpEcOl2ZRK+CIllSWRwtTr0bR1iBXWVi1ay5PaGCl1Tlms16b37btvpFjPvx0pZAt1Qcmmhnzu9n7g/xYKcAjDTTZP1GXZdXrclqYNNFJe9X611LNG4x58WR01aIqhHllmDMblw/H79xcv51/ActOzps=
|
702,382
|
Sort 0s, 1s and 2s
|
Given an array arr containing only 0s, 1s, and 2s. Sort the array in ascending order.
Examples:
Input:
arr[] = [0, 2, 1, 2, 0]
Output:
0 0 1 2 2
Explanation:
0s 1s and 2s are segregated into ascending order.
Input:
arr[] = [0, 1, 0]
Output:
0 0 1
Explanation:
0s 1s and 2s are segregated into ascending order.
Constraints:
1 <= arr.size() <= 10**6
0 <= arr[i] <= 2
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1724754594,
"func_sign": [
"public void sort012(int[] arr)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n int t = Integer.parseInt(br.readLine());\n\n while (t-- > 0) {\n String input = br.readLine();\n String[] inputArray = input.split(\"\\\\s+\");\n int a[] = new int[inputArray.length];\n\n for (int i = 0; i < a.length; i++) a[i] = Integer.parseInt(inputArray[i]);\n\n Solution ob = new Solution();\n ob.sort012(a);\n\n for (int num : a) {\n System.out.print(num + \" \");\n }\n System.out.println();\n System.out.println(\"~\");\n }\n }\n}\n\n//Position this line where user code will be pasted.",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1731130210,
"user_code": "class Solution {\n // Function to sort an array of 0s, 1s, and 2s\n public void sort012(int[] arr) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1724745105,
"func_sign": [
"sort012(self, arr)"
],
"initial_code": "def main():\n t = int(input().strip()) # Read the number of test cases\n ob = Solution()\n while t > 0:\n t -= 1\n # Read the array as space-separated integers\n arr = list(map(int, input().strip().split()))\n ob.sort012(arr) # Sort the array\n\n print(' '.join(map(str, arr))) # Print the sorted array\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n # Function to sort an array of 0s, 1s, and 2s\n def sort012(self, arr):\n low, mid, high = 0, 0, len(arr) - 1\n\n # Using the Dutch National Flag algorithm\n while mid <= high:\n if arr[mid] == 0:\n arr[low], arr[mid] = arr[mid], arr[low] # Swap the elements\n low += 1\n mid += 1\n elif arr[mid] == 1:\n mid += 1\n else:\n arr[mid], arr[high] = arr[high], arr[mid] # Swap the elements\n high -= 1\n",
"updated_at_timestamp": 1731130210,
"user_code": "class Solution:\n # Function to sort an array of 0s, 1s, and 2s\n def sort012(self, arr):\n # code here\n "
}
|
eJzVVcFOwzAM5cBhn2HlPCHbUi98B4dJK9oBeuBSdugkJDS0j4D/JUuc1mtwq0YgjaZq0zZ+fn55SU+3X9vVTTg2D76zfXcv7f7QuXtwVLeEdcuAwED+SnJntwbXvO2bp6553r0euhTgR3/UrTuuIYchyFoJDELWSmAYsrYUhgMbCsEUmIxUGvoGNFvQlTCMcAmMVQ+ln1KnxNyP4F5nBE2Twnec0L+yhZMJSJoN6NS/QZUvZURhlmoZOGhzjUdqYVnekIpF9aS1IS39SKukkW0as3hfuhVkh5get0NMI05k8dwKklU4Xg1ys0mEkN82x2URU1b5L175eaM6T26B5tP74fKgK13Ekdufzsv8li0+LN65jT9drG35VM0s0mX/MXvl9m4VopemrTPTxhMji7mqHj/vvgElmQi2
|
701,714
|
Number of Unique Paths
|
Given a AX B matrix with your initial position at the top-left cell, find the number of possible unique paths to reach the bottom-right cell of the matrix from the initial position.
Examples:
Input:
A = 2, B = 2
Output:
2
Explanation:
There are only two unique
paths to reach the end of the matrix of
size two from the starting cell of the
matrix.
Input:
A = 3, B = 4
Output:
10
Explanation:
There are only 10 unique
paths to reach the end of the matrix of
size two from the starting cell of the
matrix.
Constraints:
1 ≤ A ≤ 16
1 ≤ B ≤ 16
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1618303175,
"func_sign": [
"public static int NumberOfPath(int a, int b)"
],
"initial_code": "//Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n\tpublic static void main (String[] args) {\n\t \n\t //taking input using Scanner class\n\t\tScanner sc=new Scanner(System.in);\n\t\t\n\t\t//taking total testcases\n\t\tint t=sc.nextInt();\n\t\twhile(t-->0)\n\t\t{\n\t\t //taking dimensions of the matrix\n\t\t int a=sc.nextInt();\n\t\t int b=sc.nextInt();\n\t\t Solution ob = new Solution();\n\t\t //calling method NumberOfPath()\n\t\t System.out.println(ob.NumberOfPath(a,b));\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "GFG",
"solution": "class Solution\n{\n //Function to find total number of unique paths.\n public static int NumberOfPath(int a, int b) \n {\n return comb(a+b-2, b-1);\n }\n \n private static int comb(int n, int r){\n long ans = 1; // n!/(r!*(n-r)!)\n for (int i=r+1; i <= n; i++){\n ans = (ans * i) / (i-r);\n }\n return (int)ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n //Function to find total number of unique paths.\n public static int NumberOfPath(int a, int b) \n {\n //Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618303175,
"func_sign": [
"NumberOfPaths(self,a, b)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n a_b = [int(x) for x in input().strip().split()]\n a = a_b[0]\n b = a_b[1]\n ob = Solution()\n print(ob.NumberOfPaths(a, b))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find total number of unique paths.\n def NumberOfPaths(self, a, b):\n\n # creating a 2D table to store results of subproblems.\n ans = [[0 for i in range(b)] for j in range(a)]\n\n # count of paths to reach any cell in first row is 1.\n for i in range(b):\n ans[0][i] = 1\n\n # count of paths to reach any cell in first column is 1.\n for i in range(a):\n ans[i][0] = 1\n\n # calculating count of paths for other cells in bottom-up manner.\n for i in range(1, a):\n for j in range(1, b):\n # calculating number of paths from previous column+previous row.\n ans[i][j] = ans[i-1][j] + ans[i][j-1]\n\n # returning total paths.\n return ans[a-1][b-1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\n \nclass Solution:\n #Function to find total number of unique paths.\n def NumberOfPaths(self,a, b):\n #code here"
}
|
eJydVDuOU0EQJEDcgWz04hXq/4eTIGFEABuQmA28EhICcQi4L/UWOyBow64Da+R2VddUV8+P57/Wi2cPnzcvcXj7dft0vLs/ba/XxoejL99u1nb75e72w+n24/vP96dzMelw/H44bt9u1t8QpsU0gKxCRpwvnpoZMUfQCI3FA5InyOJ4JKQWywBRLrGpk6x6CiyuKHRnTh+tzMU2QCVZZWppK58Cg1Kb/JcUso5wswgl15wTANl75AamIqoBCDcQujF16k3EVB1dyFGyW3dlZzOJ0P7F3OpU1OZJ7WqlWVLcGZrAEIvG/nNUhDhrkzCFhXASG4GFfScCraNZmeDPoq6a5mVgb8vWVtM29hYXU5MytmRJR02doxtQikZ3NAnldpyU9jJDS4AtI3Y9Hl5tqKeazauRj1+Nh3lejxGjZalUpeMGZLs02NFVhjXNrp73/A/9P/jVWpAaaW/fgwNL4aJJwFeFF4JpwVRFFSbIFQNi5bmfn/2Ymlp1gRJzxV2QKYysMqsUE9hFIA+4MAKM5JARRJAEuKsQKC0cMVC8cNfVALAut5/X7X+3ZoHzylumEpUxqcGLe8FPW3cJybufr34DQgSwsw==
|
705,826
|
Modified Numbers and Queries
|
Find the sum of all the numbers between the range land r.Here each number is represented by the sum of its distinct prime factors.Note: For example, 6 is represented by 5 because 6 has two prime factors 2 and 3 and 2 + 3 = 5.Example 1:
Examples:
Input:
l = 1, r = 2
Output:
2
Explanation:
1->0, 2->2 and 0+2=2.
1 has no prime factors.
Input:
l = 1, r = 6
Output:
17
Explanation:
1->0, 2->2, 3->3, 4->2
5->5, 6->2+3=5, 0+2+3+2+5+5 = 17.
Your Task:
You dont need to read input or print anything. Complete the function
sumOfAll()
which takes land ras input parameter and returns sum all the numbers ( as represented) in the given range both L and R included.
Expected Time Complexity:
O(nloglogn)
Expected Auxiliary Space:
O(n)
Constraints:
1 <= l<= r<=10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int sumOfAll(int l, int r)"
],
"initial_code": "//Initial Template for Java\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String[] input = new String[2]; \n input = br.readLine().split(\" \"); \n int l = Integer.parseInt(input[0]); \n int r = Integer.parseInt(input[1]); \n Solution ob = new Solution();\n System.out.println(ob.sumOfAll(l,r));\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution\n{\n int quary[]; // declaring an array to store the pre-calculated values\n \n void pre()\n {\n quary=new int[10001]; // initializing the array with size 10001\n \n // initializing the values in the array for sieve of Eratosthenes\n // calculating the sum of divisors for each number up to 10000\n for(int i=0 ; i<10001 ; i++)\n quary[i] = 0 ;\n \n quary[1] = 0 ; // the sum of divisors for 1 is 0\n \n // filling the array with the sum of divisors for each number\n // using the sieve of Eratosthenes algorithm\n for(int i=2 ; 2*i<10001 ; i++)\n {\n if( quary[i] == 0 )\n {\n for(int j=2*i ; j<10001 ; j+=i)\n quary[j] += i ; // adding i to the sum for each multiple of i\n }\n }\n \n quary[2] = 2 ; // sum of divisors for 2 is 2\n \n // setting the sum of divisors for all odd numbers starting from 3 to their values\n for(int i=3 ; i<10001 ; i+=2 )\n {\n if( quary[i] == 0 )\n quary[i] = i ; // if no divisor is added, set the sum to the number itself\n }\n \n // calculating the prefix sum of the array for efficient querying\n for(int i=2 ; i<10001 ; i++)\n quary[i] += quary[i-1] ; // prefix sum calculation\n \n }\n \n public int sumOfAll(int l, int r)\n {\n // code here\n pre(); // call the pre() function to pre-calculate the array\n \n // calculating the sum of divisors in the range using the prefix sum\n return quary[r]-quary[l-1];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution\n{\n public int sumOfAll(int l, int r)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"sumOfAll(self, l, r)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n l, r = input().split()\n l = int(l)\n r = int(r)\n ob = Solution()\n print(ob.sumOfAll(l, r))\n print(\"~\")\n",
"solution": "# User function Template for python3\nquery = [0] * (10001)\nflag = False\n\n\ndef pre():\n query[1] = 0\n for i in range(2, 10001):\n if query[i] == 0:\n for j in range(2 * i, 10001, i):\n # as i is the prime factor of j so it is added in it\n query[j] += i\n query[2] = 2\n for i in range(3, 10001, 2):\n if query[i] == 0:\n # those numbers who are itself prime are marked by themselves\n query[i] = i\n for i in range(2, 10001):\n query[i] += query[i - 1]\n\n\nclass Solution:\n def sumOfAll(self, l, r):\n global flag\n if not flag: # if pre is not yet being called we will call it once\n pre()\n flag = True # marked flag true as pre is now called\n # query[i] represent sum of all factors of all numbers from 1 to ith number\n return query[r] - query[l - 1]\n",
"updated_at_timestamp": 1731586329,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef sumOfAll(self, l, r):\n\t\t# code here\n"
}
|
eJytVMsOgjAQ5IB+R9MzmN2WttQvMRHjQTl4qRwgMTEaP0K/V4H4islWBPfQS3dmZ6abnsLLeBS0NbuGQTDf840rqpJPGcfMIUMeMZ7vinxV5uvltirvl5C5Y+b4IWIfCKiLtSeBNATS1uUFohDUUD8OBKYgNQFWjWD1u96k0VvjqIS0NtRIwSQBUnSsTJASlRLoc6c94aCQNpHUm3x7TEw1gv66DC8HJFNcNxiT2LQb11/JGq53iY1zN4D+EToFF0YCWNtJnIahZls18OuGewb2y7Pt6W0Chq4i/ZXFz69hcZ7cAHFxdU8=
|
701,172
|
Swap all odd and even bits
|
Given an unsigned integer N. The task is to swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43(00101011). Here, every even position bit is swapped with an adjacent bit on the right side(even position bits are highlighted in the binary representation of 23), and every odd position bit is swapped with an adjacent on the left side.Example 1:
Examples:
Input:
N = 23
Output:
43
Explanation:
Binary representation of the given number
is
0
0
0
1
0
1
1
1 after swapping
0
0
1
0
1
0
11 = 43 in decimal.
Input:
N = 2
Output:
1
Explanation:
Binary representation of the given number
is
1
0 after swapping 0
1
= 1 in decimal
.
Expected Time Complexity:
O(1).
Expected Auxiliary Space:
O(1).
Constraints:
1 ≤ N ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1618484728,
"func_sign": [
"public static int swapBits(int n)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass BitWise{\n\n\tpublic static void main (String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();//testcases\n\t\twhile(t-->0){\n\t\t int n = sc.nextInt();//taking n\n\t\t \n\t\t Solution obj = new Solution();\n\t\t \n\t\t //calling swapBits() method of class\n\t\t //Swap\n\t\t System.out.println(obj.swapBits(n));\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "BitWise",
"solution": "//Back-end complete function Template for Java\n\nclass Solution\n{\n //Function to swap odd and even bits.\n public int swapBits(int n) \n {\n\t //0xAAAAAAAA means 10101010101010101010101010101010 in binary\n\t //we get all even bits of n.\n\t int ev=n & 0xAAAAAAAA;\n\t //0x55555555 means 01010101010101010101010101010101 in binary.\n\t //we get all odd bits of n.\n\t int od=n & 0x55555555; \n\t \n\t //right Shifting the even bits obtained previously.\n\t ev>>=1;\n\t //left Shifting the even bits obtained previously.\n\t od<<=1;\n\t \n\t //doing bitwise OR of even and odd bits obtained and\n\t //returning the final result.\n\t return (ev | od); \n\t \n\t}\n \n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n //Function to swap odd and even bits.\n public static int swapBits(int n) \n {\n\t // Your code\n\t}\n \n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618484728,
"func_sign": [
"swapBits(self,n)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\n\ndef main():\n T = int(input())\n\n while T > 0:\n n = int(input())\n ob = Solution()\n print(ob.swapBits(n))\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to swap odd and even bits.\n def swapBits(self, n):\n # 0xAAAAAAAA means 10101010101010101010101010101010 in binary.\n # we get all even bits of n.\n ev = n & 0xAAAAAAAA\n # 0x55555555 means 01010101010101010101010101010101 in binary.\n # we get all odd bits of n.\n od = n & 0x55555555\n\n # right Shifting the even bits obtained previously.\n ev >>= 1\n # left Shifting the even bits obtained previously.\n od <<= 1\n\n # doing bitwise OR of even and odd bits obtained and\n # returning the final result.\n return ev | od\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n ##Complete this function\n #Function to swap odd and even bits.\n def swapBits(self,n):\n #Your code here"
}
|
eJyFkj1Ow0AQhSlykMh1hOZ/ZzkJEkYU4ILGpHCkSAjEIeAadNwP24lAFG/ZaqV9b3bezPe2+fjaXKzn+nO+3Dx3j+P+MHVX2477kbvdthuO++F+Gh7ung7T+Un68bUfu5fd9q+egJ6Ank053Es4+ihDldkVVRC2YqlhBVRQERZxKwwqKDICvQF9oowkyCJk2FW0GKeg9n4FoIJrZKHKgj6PNHXzAP7CnlIykV+9VNZqaK6yjryRnkNKw9twmlsGUYOJpasFDGuQYVwFgbyCibFkJ3dKNLq1/dbeZZ5dTTh6+gnR278xYIQTIAvhiiByqzUcbXAmqAXQ/ExheAsovaLYp44byAfTvHavZ//t++U3RsxpZw==
|
705,890
|
Find maximum volume of a cuboid
|
You are given a perimeter & the area. Your task is to return themaximum volume that can be made in the form of a cuboid from the given perimeter and surface area.Note: Round off to 2 decimal places and for the given parameters, it is guaranteed that an answer always exists.
Examples:
Input:
perimeter = 22, area = 15
Output:
3.02
Explanation:
The maximum attainable volume of the cuboid is 3.02
Input:
perimeter = 20, area = 5
Output:
0.33
Explanation:
The maximum attainable volume of the cuboid is 0.33
Constraints :
1 ≤ perimeter ≤ 10**9
1 ≤ area ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"double maxVolume(double perimeter, double area)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n\n while (t-- > 0) {\n String arr[] = read.readLine().trim().split(\"\\\\s+\");\n double perimeter = Double.parseDouble(arr[0]);\n double area = Double.parseDouble(arr[1]);\n\n Solution ob = new Solution();\n double ans = ob.maxVolume(perimeter, area);\n System.out.println(String.format(\"%.2f\", ans));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n double maxVolume(double perimeter, double area) {\n // Calculation of formula to find the maximum volume\n double part1 = perimeter - Math.sqrt(Math.pow(perimeter, 2) - (24 * area));\n double term = Math.pow(part1 / 12, 2);\n double height = (perimeter / 4) - (2 * (part1 / 12));\n double ans = term * height;\n\n // Returning the maximum volume\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n double maxVolume(double perimeter, double area) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxVolume(self, perimeter, area)"
],
"initial_code": "# Initial Template for Python 3\nimport math\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n perimeter, area = [int(x) for x in input().split()]\n\n ob = Solution()\n print('%.2f' % ob.maxVolume(perimeter, area))\n print(\"~\")\n",
"solution": "class Solution:\n def maxVolume(self, perimeter, area):\n # Calculation of formula to find the maximum volume\n part1 = perimeter - math.sqrt(perimeter**2 - (24 * area))\n term = (part1 / 12)**2\n height = (perimeter / 4) - (2 * (part1 / 12))\n ans = term * height\n\n # Returning the maximum volume\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def maxVolume(self, perimeter, area):\n #code here"
}
|
eJylVMtOxDAM5ID4jqjnlWXn0cR8CRJBHKAHLmUPrYTEQ3wE/C9h28BuF6cR61MUJeOZ8eP9/PPl4mwXV2M6XD83D/12HJpL1VDsCXOo32Psm41quqdtdzd097eP4zB/0G56oIF97N/Su9eNOgTkHOrnVAHntQDnjumJcHZKByEIYBlCVTJjdoAkgWljXetDEhp866zRIhqxdwaDB+Sia4pECIRv4QVVypXNabUjneS0K97gv0koXUhPyMBmLXdWURYy1Rm8qzFkMne6nS2WkZNJjlFu7gOiNZnWxNSWdR87xtN10HIOcoq5EUul1Nob65mQwK5WtHbUEMGKY7tgu6Ar8wyouQ2OPYORFsy+zaXhQaA6sfmi2uZd5lgySG6SP7ft6j6q2LtH3YcntN/NB3wB6h3Q0A==
|
702,882
|
Minimum Difference among K
|
Given an array arr[] ofintegers and a positive numberk. We are allowed to take any k integers from the given array. The task is to find the minimum possible value of the difference between the maximum and minimum of k numbers.
Examples:
Input:
arr[] = [10, 100, 300, 200, 1000, 20, 30], k=3
Output:
20
Explanation:
20 is the minimum possible difference between any maximum and minimum of any k numbers.Given k = 3, we get the result 20 by selecting integers {10, 20, 30}.max(10, 20, 30) - min(10, 20, 30) = 30 - 10 = 20.
Input:
arr[] = [1, 1], k=2
Output:
0
Explanation:
max({1,1}) - min({1,1}) = 1 - 1 = 0
Constraints:
1≤ arr.size() ≤ 10**5
1≤ arr[i] ≤ 10**5
0 < k ≤ n
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1730200213,
"func_sign": [
"int minDiff(int[] arr, int k, int m, int th)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n\n int k = Integer.parseInt(br.readLine());\n int m = Integer.parseInt(br.readLine());\n int th = Integer.parseInt(br.readLine());\n // Create Solution object and find closest sum\n Solution ob = new Solution();\n // ArrayList<Long> ans=ob.smallestDifferenceTriplet(a,b,c,n);\n int ans = ob.minDiff(arr, k, m, th);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n /**\n * Function to find the minimum difference between the highest and lowest priority levels among\n * the assigned tasks while ensuring that at least 'm' tasks have a priority level greater than or\n * equal to the threshold 'T'.\n *\n * @param arr An array of integers representing the priority levels of tasks.\n * @param k The number of workers (each worker must be assigned exactly one task).\n * @param m The minimum number of tasks that must have a priority level >= T.\n * @param th The priority threshold.\n * @return The minimum difference if a valid assignment exists, otherwise -1.\n */\n int minDiff(int[] arr, int k, int m, int th) {\n // Edge Case 1: If the number of required high-priority tasks exceeds k, it's\n // impossible to satisfy the constraint\n if (m > k) return -1;\n // Edge Case 2: If the number of tasks is less than k, it's impossible to assign\n // k tasks\n if (arr.length < k) return -1;\n // Step 1: Sort the array to facilitate the sliding window approach\n Arrays.sort(arr);\n int n = arr.length;\n int min_diff = Integer.MAX_VALUE; // Initialize minimum difference to a large value\n boolean found = false; // Flag to indicate if a valid window is found\n // Step 2: Initialize the count of tasks >= T in the first window of size k\n int count = 0;\n for (int i = 0; i < k; i++) {\n if (arr[i] >= th) count++;\n }\n // If the first window satisfies the constraint, update min_diff\n if (count >= m) {\n min_diff = arr[k - 1] - arr[0];\n found = true;\n }\n // Step 3: Slide the window from left to right, updating the count and min_diff\n for (int i = k; i < n; i++) {\n // Remove the element going out of the window\n if (arr[i - k] >= th) count--;\n // Add the new element entering the window\n if (arr[i] >= th) count++;\n // Check if the current window satisfies the constraint\n if (count >= m) {\n int current_diff = arr[i] - arr[i - k + 1];\n if (current_diff < min_diff) {\n min_diff = current_diff;\n found = true;\n }\n }\n }\n // Step 4: Return the result\n // If a valid window was found, return the minimum difference\n // Otherwise, return -1 to indicate that no valid assignment exists\n return found ? min_diff : -1;\n }\n}\n",
"updated_at_timestamp": 1730272658,
"user_code": "// User function Template for Java\n\nclass Solution {\n int minDiff(int[] arr, int k, int m, int th) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1730200213,
"func_sign": [
"minDiff(self,arr,k,m,t)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n k = int(input().strip())\n m = int(input().strip())\n th = int(input().strip())\n ob = Solution()\n ans = ob.minDiff(arr, k, m, th)\n print(ans)\n tc -= 1\n print(\"~\")\n",
"solution": "# User function Template for Python3\n\n\nclass Solution:\n\n def minDiff(self, arr, k, m, t):\n # Edge cases\n if m > k or len(arr) < k:\n return -1\n\n # Sort the array to use a sliding window\n arr.sort()\n\n min_diff = float('inf')\n found = False\n\n # Initialize count for tasks >= threshold in the first window\n count = sum(1 for i in range(k) if arr[i] >= t)\n\n # Check if the first window satisfies the condition\n if count >= m:\n min_diff = arr[k - 1] - arr[0]\n found = True\n\n # Slide the window through the array\n for i in range(k, len(arr)):\n # Update count for the window by adding arr[i] and removing arr[i - k]\n if arr[i - k] >= t:\n count -= 1\n if arr[i] >= t:\n count += 1\n\n # Update min_diff if the current window is valid\n if count >= m:\n min_diff = min(min_diff, arr[i] - arr[i - k + 1])\n found = True\n\n return min_diff if found else -1\n",
"updated_at_timestamp": 1730272658,
"user_code": "#User function Template for python3\nclass Solution:\n def minDiff(self,arr,k,m,t):\n"
}
|
eJzFVEtOwzAQZYHENUZeF9TxJ7E5CRJGLCALNqaLVKqEQBwC7saOq+AZtwmqOiGJIuFaL5HqzJv3Zjzv55/fF2e8br7yy+2LekqbbauuQWFMCLimBYEWOH4nREYN+YyLSeeT9JdagWp2m+ahbR7vn7ftPhB/FtNbTOp1BccMGgxYcFBBDR5CZgTMvDm2AbSADrACrAE9YAC9Ji5mdQJdkKiKlKFHkUngGWvGitExWkbDqBmRsU+LT0lOCKk5zkH+FQPz1yRDiC06TLE1gSGwhxJCRVATeNbe+cBMJqZaLqkdqGi3ZyQqFIbTOXSZlNOsuJb3AnH71gmcqi6dEKYGPXEfcqSYvGyonyXc/638Esf2K1+QJZs2+4BsxGkn+IpOzXrKNOvsmzXUBOP3zo1tvEEhuldSpOCRlvGjWRyYZZvyGFMRqcxDShauicj0uxj/NP6rOSN69ox2fYPefVz9AHwMFW4=
|
700,911
|
Frequency Game
|
Given an array A of size N. The elements of the array consist of positive integers. You have to find the largest element with minimum frequency.
Examples:
Input:
5
2 2 5 50 1
Output:
50
Explanation :
All elements are having frequency 1 except 2.
50 is the maximum element with minimum frequency.
Input:
4
3 3 5 5
Output:
5
Explanation:
Both 3 and 5 have the same frequency, so 5 should be returned.
Constraints:
1 <= N <= 10**5
1 <= A[i] <= 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int LargButMinFreq(int arr[], int n)"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\nimport java.io.*;\n\n// Position this line where user code will be pasted.\n\n// Driver class with main function\nclass GFG {\n // Main function\n public static void main(String[] args)throws IOException {\n BufferedReader in=new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n\n // Iterating over testcases\n while (t-- > 0) {\n int n = Integer.parseInt(in.readLine());\n int arr[] = new int[n];\n\n String s[]=in.readLine().trim().split(\" \");\n for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(s[i]);\n\n Solution obj = new Solution();\n System.out.println(obj.LargButMinFreq(arr, n));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function to find largest number with minimum frequency\n public static int LargButMinFreq(int arr[], int n) {\n // Creating a HashMap to store the frequency of each element in the array\n HashMap<Integer,Integer> hm=new HashMap<>();\n // Iterating over the array and updating the frequency in the HashMap\n for(int i:arr){\n hm.put(i,hm.getOrDefault(i,0)+1);\n }\n // Initializing the minimum frequency as maximum value to find the minimum frequency\n int freq=Integer.MAX_VALUE;\n // Finding the minimum frequency from the HashMap\n for(int i:hm.values()){\n freq=Math.min(freq,i);\n }\n // Initializing the answer as 0 to store the largest number with minimum frequency\n int ans=0;\n // Iterating over the HashMap to find the largest number with minimum frequency\n for(Map.Entry<Integer,Integer> e:hm.entrySet()){\n // If the frequency of the element is equal to the minimum frequency\n if(e.getValue()==freq){\n // Updating the answer with the larger number\n ans=Math.max(ans,e.getKey());\n }\n }\n // Returning the largest number with minimum frequency\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\n// Helper class to find largest number with minimum frequency\nclass Solution {\n // Function to find largest number with minimum frequency\n public static int LargButMinFreq(int arr[], int n) {\n // Your code here\n }\n}"
}
|
{
"class_name": null,
"created_at_timestamp": 1634368837,
"func_sign": [
"LargButMinFreq(arr,n)"
],
"initial_code": "# Initial Template for Python 3\n\nt = int(input())\n\n# Iterating over test cases\nfor _ in range(t):\n n = int(input())\n arr = [int(x) for x in input().split()]\n print(LargButMinFreq(arr, n))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\ndef LargButMinFreq(arr, n):\n # dictionary to store the frequency of list elements\n freq = {}\n # calculating the frequency of each element in the list\n for item in arr:\n if item in freq:\n freq[item] += 1\n else:\n freq[item] = 1\n minfreq = n + 1\n res = -1\n # finding the element with the minimum frequency but largest value\n for key, value in freq.items():\n if minfreq > value:\n res = key\n minfreq = value\n elif minfreq == value:\n # if there are multiple elements with the same minimum frequency,\n # select the one with the largest value\n if res < key:\n res = key\n return res\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\ndef LargButMinFreq(arr,n):\n #code here"
}
|
eJztlbtqW0EQhlO4yGMMpzZh7xc/SSAKLmIVaWQXEhiMjR/Cftd0yTfnApHRKIqCu2gZEOx3/rnszO7zxevPjx/G3+cf/PnyMHzf3O22w5UMfrXxTs1JwCKWsIwVrGIN6xiMGy5lWN/frb9t1zfXt7vtosLWavO02gyPl3JQfZJos2SZXaTZZZjkz1aXJf4lhyWPJZdsimdTO7CRZVlpXnFeYV5elxX4EWXPtxG9LEWqNOnkIB4tJKP4JD6LL+Kr+Ca+k5nhJNi1GYuDpEPTIepQdcg6dB3CDmWH49EznPpW5+pd3at/DUAjIAQf4IKGCBfgAlyAC3ABLsAFuAgX4aLmAhfhIlyEi3ARLsIluASX4JImDZfgElyCS3AJLsNluAyX4bJWBy7DZbgMl+EKXIErcAWuwBUtI1yBK3AFrsJVuApX4Spchatab7gKV+EaXINrcA2uwTW4Btf0YOAaXIfrcB2uw3W4DtfhOlzXE9QjtM/QbELtlL/ur7G9LF/HRknerrNUGHY6utLZeZyYYGdwdLCXKOwwvFWCKY5wwr1m32rT5in32nKlMSkn32oT/IfZNctm53320Mv/qd+b+nea6FOeW/9bg1kejjbP2d2z95zqEVovqrOf1OnLQy7MT/7lZecKth933Zwj+fry6RcuVy7N
|
703,229
|
Numbers with prime frequencies greater than or equal to k
|
You are given an array arr. You need to find elements that appear a prime number of times in the array with minimum k frequency (frequency >= k).
Examples:
Input:
arr[] = [11, 11, 11, 23, 11, 37, 51, 37, 37, 51, 51, 51, 51], k = 2
Output:
[37, 51]
Explanation:
11's count is 4, 23 count 1, 37 count 3, 51 count 5. 37 and 51 are two number that appear prime number of time and frequencies greater than or equal to k = 2.
Input:
arr[] = [11, 22, 33]
Output:
[]
Explanation:
In the array, the counts of elements are: 11 (1 time), 22 (1 time), 33 (1 time). None of these counts are prime numbers, so the output is an empty list.
Constraints:
1 ≤ arr.size() ≤ 10**4
1 ≤ arr[i] ≤ 10**6
1 ≤ k ≤ 100
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public List<Integer> primeOccurences(int[] nums, int k)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass Main {\n public static void main(String args[]) throws IOException {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine().trim());\n\n while (t-- > 0) {\n // Read the array elements from input\n String line = read.readLine().trim();\n String[] numsStr = line.split(\" \");\n int[] nums = new int[numsStr.length];\n for (int i = 0; i < numsStr.length; i++) {\n nums[i] = Integer.parseInt(numsStr[i]);\n }\n\n // Read the value of k\n int k = Integer.parseInt(read.readLine().trim());\n\n // Create an instance of the Solution class\n Solution ob = new Solution();\n\n // Call the primeOccurences function and get the result\n List<Integer> ans = ob.primeOccurences(nums, k);\n\n // Print the result\n for (int num : ans) {\n System.out.print(num + \" \");\n }\n System.out.println();\n }\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n // Check if the number of occurrences is prime\n public boolean isPrime(int n) {\n if (n <= 1) return false;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) return false;\n }\n return true;\n }\n\n // Function to find numbers with prime occurrences\n public List<Integer> primeOccurences(int[] nums, int k) {\n Map<Integer, Integer> freqMap = new HashMap<>();\n // Count frequencies of elements in the array\n for (int num : nums) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n // Find elements with prime frequencies and frequency at least k\n List<Integer> result = new ArrayList<>();\n for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {\n if (isPrime(entry.getValue()) && entry.getValue() >= k) {\n result.add(entry.getKey());\n }\n }\n Collections.sort(result); // Sort the result before returning\n return result;\n }\n}\n",
"updated_at_timestamp": 1727947200,
"user_code": "// User function Template for Java\n\nclass Solution {\n public List<Integer> primeOccurences(int[] nums, int k) {\n // Complete the function\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"primeOccurences(self, arr, k)"
],
"initial_code": "if __name__ == '__main__':\n tc = int(input().strip())\n\n while tc > 0:\n arr = list(map(int, input().strip().split())) # Input array\n k = int(input().strip()) # Input k\n\n ob = Solution()\n print(*ob.primeOccurences(arr, k))\n\n tc -= 1\n",
"solution": "import heapq\nfrom collections import Counter\n\n\nclass Solution:\n # Check if a number is prime\n def isPrime(self, n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n # Function to find numbers with prime occurrences\n def primeOccurences(self, arr, k):\n freq_map = Counter(arr) # Count frequencies of elements in the array\n\n result = []\n for num, freq in freq_map.items():\n if self.isPrime(freq) and freq >= k: # Check if frequency is prime and >= k\n result.append(num)\n\n return sorted(result)\n",
"updated_at_timestamp": 1727947200,
"user_code": "#User function Template for python3\n\nclass Solution:\n # Function to find numbers with prime occurrences\n def primeOccurences(self, arr, k):\n #Complete the function\n"
}
|
eJy1VEtuwyAQ7SLqOUasoyqAE9s9SaUQZdF60Q3NwpEiVZVyiOYm2fVyGYNx/JmxjNUwHoEMMzDvPTgvLn/PT669XXGw/Raf9nAsxSsIaawEBbpxbawWSxDF6VC8l8XH/utY1muVseJnCb3olQTvuuVp3/msdQCVew1tS3smZfszVjEbrN3sMHuOLdMwucNamR3CPIWOa/DgHqFi0a0XDM+mQHnGnSXB+FwJWSEPC7kcRpgiafLyTFAAGyQ9gxyLdpQrkCOc0IynMMEr2qKyDrXiexzUCDGCymYoqoHD6z4ehc6NVRE3lS5+08Eu/ydQCda7tHMi5RgKsD/sptO8RAM6eI09Y3FvMsZicN6CL+hQyvuTMRvP0fzVAxL2MFRB/i+WFHGC3e/LDc3kwoQ=
|
700,334
|
Dijkstra Algorithm
|
Given a weighted, undirected and connected graph of V vertices and an adjacency list adj where adj[i] is a list of lists containing two integers where the first integer of each list jdenotes there is edge between i and j,second integers corresponds to the weight of thatedge .You are given the source vertex S and You toFind the shortest distance of all the vertex's from the source vertex S.You have to return a list of integers denoting shortest distance between each node and Source vertex S.
Examples:
Input:
V
= 2
adj []
{{{1, 9}}, {{0, 9}}}
S
= 0
Output:
0 9
Explanation:
The source vertex is 0. Hence, the shortest
distance of node 0 is 0 and the shortest
distance from node 1 is 9.
Input:
V
= 3,
E = 3
adj = {{{1, 1}, {2, 6}}, {{2, 3}, {0, 1}}, {{1, 3}, {0, 6}}}
S
= 2
Output:
4 3 0
Explanation:
For nodes 2 to 0, we can follow the path-
2-1-0. This has a distance of 1+3 = 4,
whereas the path 2-0 has a distance of 6. So,
the Shortest path from 2 to 0 is 4.
The shortest distance from 0 to 1 is 1 .
Expected Time Complexity:
O(V**2
).
Expected Auxiliary Space:
O(V**2
).
|
geeksforgeeks
|
Medium
|
{
"class_name": null,
"created_at_timestamp": 1729144616,
"func_sign": [
"ArrayList<Integer> dijkstra(ArrayList<ArrayList<iPair>> adj, int src)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass iPair {\n int first, second;\n\n iPair(int first, int second) {\n this.first = first;\n this.second = second;\n }\n}\n\nclass DriverClass {\n public static void main(String args[]) throws IOException {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String str[] = read.readLine().trim().split(\" \");\n int V = Integer.parseInt(str[0]);\n int E = Integer.parseInt(str[1]);\n\n ArrayList<ArrayList<iPair>> adj = new ArrayList<ArrayList<iPair>>();\n for (int i = 0; i < V; i++) {\n adj.add(new ArrayList<iPair>());\n }\n\n int i = 0;\n while (i++ < E) {\n String S[] = read.readLine().trim().split(\" \");\n int u = Integer.parseInt(S[0]);\n int v = Integer.parseInt(S[1]);\n int w = Integer.parseInt(S[2]);\n iPair t1 = new iPair(v, w);\n iPair t2 = new iPair(u, w);\n adj.get(u).add(t1);\n adj.get(v).add(t2);\n }\n\n int src = Integer.parseInt(read.readLine());\n\n Solution ob = new Solution();\n\n ArrayList<Integer> res = ob.dijkstra(adj, src);\n\n for (i = 0; i < V; i++) System.out.print(res.get(i) + \" \");\n System.out.println();\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "DriverClass",
"solution": "None",
"updated_at_timestamp": 1730268093,
"user_code": "/*\nclass iPair {\n int first, second;\n\n iPair(int first, int second) {\n this.first = first;\n this.second = second;\n }\n}\n*/\n\n// User function Template for Java\nclass Solution {\n // Function to find the shortest distance of all the vertices\n // from the source vertex src.\n ArrayList<Integer> dijkstra(ArrayList<ArrayList<iPair>> adj, int src) {\n // Write your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1729144616,
"func_sign": [
"dijkstra(self, adj: List[List[Tuple[int, int]]], src: int) -> List[int]"
],
"initial_code": "if __name__ == '__main__':\n test_cases = int(input())\n for cases in range(test_cases):\n V, E = map(int, input().strip().split())\n adj = [[] for _ in range(V)]\n for _ in range(E):\n u, v, w = map(int, input().strip().split())\n adj[u].append((v, w))\n adj[v].append((u, w))\n src = int(input())\n ob = Solution()\n\n res = ob.dijkstra(adj, src)\n for i in res:\n print(i, end=\" \")\n print()\n print(\"~\")",
"solution": "import atexit\nimport io\nimport sys\nimport heapq\nfrom typing import List, Tuple\n\nMAX_VALUE = (1 << 32)\n\n\nclass Solution:\n # Function to find the shortest distance of all the vertices\n # from the source vertex src.\n def dijkstra(self, adj: List[List[Tuple[int, int]]],\n src: int) -> List[int]:\n V = len(adj)\n dist = [MAX_VALUE] * V\n dist[src] = 0\n pq = []\n heapq.heappush(pq, (0, src))\n\n while pq:\n d, u = heapq.heappop(pq)\n if d > dist[u]:\n continue\n for v, w in adj[u]:\n if dist[v] > dist[u] + w:\n dist[v] = dist[u] + w\n heapq.heappush(pq, (dist[v], v))\n\n return dist\n",
"updated_at_timestamp": 1731646343,
"user_code": "class Solution:\n # Function to find the shortest distance of all the vertices\n # from the source vertex src.\n def dijkstra(self, adj: List[List[Tuple[int, int]]], src: int) -> List[int]:\n # Your code here"
}
|
eJzNVs1u00AQ5sCNlxj5XCHP7o53lydBwogD5MDF9JBKSAjEQ8DrcOO9mG9mYrVCtiqlTZtYcRSv5/uZbzb++fL331cv7PX2j3559234vFzfHIc3NPC8CE3zMhITjzhnknlhSqSXEhUq85L1YsKpUNclwxUNh6/Xh4/Hw6cPX26OUWqkSo2EONG8/JiX4fsV3UWaqDlSxSmhGCseC5Cy4bNiMDuW0ipar+OqgMAecifWo+nNW+gm5aQTAk+woXrcA2A9VNq0VbyFe+wgCUrNRHaNzc2srszMFCxVlRCoPbACokqmPR5FLVaDuYBLypQ2zTbGTikaml1vdDK7u8nBM7pTsRJNLBDUPRedkrhD7pu4lqo0UGiCJmPFe7wFK5RLtkOpq0fqg2yyT7ok2iXuaI20pGhbibRk19PWtIiTmtxLC6Xr0Ts6WGR3x0INamyltQNTKBOUbAZRkKyMorgloazeuC+W0cak5XVtNZ2qplLWXzo+NzSLz0XQSlTWOYTu6rKzB0lc9C4NLIcJG3B1jWzgyRpV9qiiQPHpy95r9sRGaGJA2z4J7Ym+rf2b+0K/vQMla8Cp1+xqTYxzaat2oFefpd2NaZ1e/dyemGZ44NGDxqkDo9MJ76fAZ0eudzwpPsTi+TOOdZ9ct2lG3rGFISr5WU/Fpcfi7H+N8/b+SmMkBwLbk7FE6h+E6X/bjDzuPnNruukpx/sxOjTPIH92dDa3v3xZg57HPnzpJ5f0kI8udO8H6vs8UfuGLPiHCLT3v17/AxLMAMQ=
|
700,463
|
Bridge edge in a graph
|
Given aGraph of V vertices and E edges and another edge(c -d), the task is to find if the given edge is a Bridge.i.e., removing the edge disconnects the graph.
Examples:
Input:
c = 1,
d = 2
Output:
1
Explanation:
From the graph, we can clearly see that
blocking the edge 1-2 will result in
disconnection of the graph. So, it is
a Bridge
and thus the Output 1.
Input:
c = 0,
d = 2
Output:
0
Explanation:
blocking the edge between nodes 0 and 2
won't affect the connectivity of the graph.
So, it's not a Bridge Edge. All the Bridge
Edges in the graph are marked with a blue
line in the above image.
Constraints:
1
≤
V,E
≤
10**5
0
≤
c, d
≤
V-1
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1616496394,
"func_sign": [
"static int isBridge(int V, ArrayList<ArrayList<Integer>> adj,int c,int d)"
],
"initial_code": "import java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass DriverClass\n{\n public static void main (String[] args) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n \n while(t-- > 0)\n {\n ArrayList<ArrayList<Integer>> list = new ArrayList<>();\n int V = sc.nextInt();\n int E = sc.nextInt();\n for(int i = 0; i < V+1; i++)\n list.add(i, new ArrayList<Integer>());\n for(int i = 0; i < E; i++)\n {\n int u = sc.nextInt();\n int v = sc.nextInt();\n list.get(u).add(v);\n list.get(v).add(u);\n }\n int c = sc.nextInt();\n int d = sc.nextInt();\n \n Solution ob = new Solution();\n \n System.out.println(ob.isBridge(V,list,c,d));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "DriverClass",
"solution": "None",
"updated_at_timestamp": 1730267203,
"user_code": "// User function Template for Java\n\nclass Solution\n{\n //Function to find if the given edge is a bridge in graph.\n static int isBridge(int V, ArrayList<ArrayList<Integer>> adj,int c,int d)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616496394,
"func_sign": [
"isBridge(self, V, adj, c, d)"
],
"initial_code": "# Initial Template for Python 3\n\nfrom collections import OrderedDict\nimport sys\n\nsys.setrecursionlimit(10**6)\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n V, E = list(map(int, input().strip().split()))\n adj = [[] for i in range(V)]\n for i in range(E):\n a, b = map(int, input().strip().split())\n adj[a].append(b)\n adj[b].append(a)\n\n for i in range(V):\n adj[i] = list(OrderedDict.fromkeys(adj[i]))\n\n c, d = map(int, input().split())\n ob = Solution()\n\n print(ob.isBridge(V, adj, c, d))\n print(\"~\")\n",
"solution": "# Backend Complete Function solution for python3\nclass Solution:\n\n # Function to perform DFS on graph.\n def DFS(self, adj, v, visited):\n # marking the current vertex as visited.\n visited[v] = True\n\n i = 0\n # traversing over the adjacent vertices.\n while i != len(adj[v]):\n # if any vertex is not visited, we call the function\n # recursively for adjacent node.\n if (not visited[adj[v][i]]):\n self.DFS(adj, adj[v][i], visited)\n i += 1\n\n # Function to find whether graph is connected.\n def isConnected(self, V, adj, one, two):\n\n # using boolean array to mark visited nodes and currently\n # marking all the nodes as false.\n visited = [False] * V\n\n # finding all reachable vertices from first vertex\n # and marking them visited.\n self.DFS(adj, one, visited)\n\n # if second vertex is not visited, we return false else true.\n if (visited[two] == False):\n return False\n return True\n\n # Function to find if the given edge is a bridge in graph.\n\n def isBridge(self, V, adj, u, v):\n\n # if graph is not connected, we return false.\n if self.isConnected(V, adj, u, v) == False:\n return 0\n\n # we remove edge from undirected graph.\n indU = adj[v].index(u)\n indV = adj[u].index(v)\n del adj[u][indV]\n del adj[v][indU]\n\n # checking if graph is connected.\n res = self.isConnected(V, adj, u, v)\n\n # adding the edges back\n adj[u].append(v)\n adj[v].append(u)\n\n # if graph isn't connected after removing edges, return true else false.\n if (res == False):\n return 1\n else:\n return 0\n",
"updated_at_timestamp": 1730267203,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to find if the given edge is a bridge in graph.\n def isBridge(self, V, adj, c, d):\n # code here"
}
|
eJzNVE1LxDAQ9eDBX+BNePS8SF/S9MNfIhjxoD14iXvogiCKP0L/r5kkLlu2ZZtF0R5KmMy8mXkzee+nnxdnJ+G7PveHm5fi0a03Q3GFgtYZGOtK+BOhrFPQ1mlUYquSrVih6J/X/f3QP9w9bYYUXFr35i9fVxgj1mimEStJxZhPJ5dM7CpWNsIOYOGUCUYPpBJcKXBT9RrUqaUGrXUtOnHuxFmnU2baBDHDz26+Ui5Mus1tzoD1wjzffXVgGWmRIAZ2qEAfSA1G6sNWBL/wzyxLeaL542WxAs22Z9agB2ADegi2YCS8EzxxiP9cQlXIcXzlWswmPQ6hQjyCMZdDcLu180+IB6OJ+fnNRS+QC1nYzI4OoR4JOx7Zn84siqLabRETsrg/XdGAI8VyIav7O5HFs5A1/5omne0y51+eoIhCZqMZnS7XuvIfiN3tx+UXfAxUIg==
|
705,618
|
Check Mirror in N-ary tree
|
Given two n-ary trees.Check if they are mirror images of each other or not. You are also given e denoting the number of edges in both trees, and two arrays, A[] and B[]. Each array has2*e space separated values u,v denoting an edge from u to v for the both trees.
Examples:
Input:
n =
3,
e =
2
A[] =
{1, 2, 1, 3}
B[] =
{1, 3, 1, 2}
Output:
1
Explanation:
1 1
/ \ / \
2 3 3 2
As we can clearly see, the second tree
is mirror image of the first.
Input:
n =
3,
e =
2
A[] =
{1, 2, 1, 3}
B[] =
{1, 2, 1, 3}
Output:
0
Explanation:
1 1
/ \ / \
2 3 2 3
As we can clearly see, the second tree
isn't mirror image of the first.
Constraints:
1 <= n,e <= 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1619077929,
"func_sign": [
"static int checkMirrorTree(int n, int e, int[] A, int[] B)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n \n int n = Integer.parseInt(S[0]);\n int e = Integer.parseInt(S[1]);\n \n String S1[] = read.readLine().split(\" \");\n String S2[] = read.readLine().split(\" \");\n \n int[] A = new int[2*e];\n int[] B = new int[2*e];\n \n for(int i=0; i<2*e; i++)\n {\n A[i] = Integer.parseInt(S1[i]);\n B[i] = Integer.parseInt(S2[i]);\n }\n\n Solution ob = new Solution();\n System.out.println(ob.checkMirrorTree(n,e,A,B));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static int checkMirrorTree(int n, int e, int[] A,\n int[] B)\n {\n // code here\n HashMap<Integer, Stack<Integer> > m\n = new HashMap<>();\n for (int i = 0; i < 2 * e; i += 2) {\n if (!m.containsKey(A[i])) {\n m.put(A[i], new Stack<Integer>());\n }\n m.get(A[i]).push(A[i + 1]);\n }\n for (int i = 0; i < 2 * e; i += 2) {\n if (m.get(B[i]).peek() != B[i + 1]) {\n return 0;\n }\n else {\n m.get(B[i]).pop();\n }\n }\n return 1;\n }\n};",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int checkMirrorTree(int n, int e, int[] A, int[] B) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619077929,
"func_sign": [
"checkMirrorTree(self, n, e, A, B)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n, e = map(int, input().split())\n\n A = list(map(int, input().split()))\n B = list(map(int, input().split()))\n\n ob = Solution()\n print(ob.checkMirrorTree(n, e, A, B))\n print(\"~\")\n",
"solution": "class Solution:\n def checkMirrorTree(self, n, e, A, B):\n # Lists to store nodes of the tree\n s = []\n q = []\n\n # initializing both list with empty stack and queue\n for i in range(n + 1):\n s.append([])\n queue = []\n q.append(queue)\n\n # add all nodes of tree 1 to\n # list of stack and tree 2 to list of queue\n for i in range(0, 2 * e, 2):\n s[A[i]].append(A[i + 1])\n q[B[i]].append(B[i + 1])\n\n # now take out the stack and queues\n # for each of the nodes and compare them\n # one by one\n for i in range(1, n + 1):\n while (len(s[i]) > 0 and len(q[i]) > 0):\n a = s[i][len(s[i]) - 1]\n s[i].pop()\n b = q[i][0]\n q[i].pop(0)\n\n if (a != b):\n return 0\n return 1\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def checkMirrorTree(self, n, e, A, B):\n # code here"
}
|
eJzNVcFOwzAM5cCFv7BynlCdpu3KlyAxxAF64FJ26CQkBOIj4Fe48W/YLyurVIIS2k60ipUmfu/ZzuK9nr5/np3gufyQydWTuW+3u85ckOFNa0kMk4UxKzLN47a57Zq7m4ddd3B72bTmeUVhbB7AZgGsoxxYEqi8DhykC/KRGEfh4Z7LkpNRHPjkQxcTOUtP8R2fDJGhchhngQ1ZTOTmjOpRwDIrZVQyW8uoZcbZUK2Cxz4b7MJN3GeVdyLvwPubvHo4BMpZqrxgxuf1o74alnW2anSXkXkRFRh7DiDBoUhwpP7OM+LIigUjFh8u1VTiyWs1tfrbuCKHc/GcYAcn2EGcmqWITj2XcJawrDBrYXNFWwc79TyDNeBe3At6cRX04pMuzvFvzrhn0t+bpoS0YIsbhDpDrH3hq4VbVvyf1TCZGehQpYVrsy8Oz16d/984qmN1jogTx5HHXoie7/rt/AsRO0js
|
704,612
|
Minimum Notes Required
|
An employee's wallet can contain no more than M notes or coins. A boss pays his salary by the minimum notes possible. However the employee may have to leave out some money. Find how much money he has to lose if his original salary is N.Note: The values of notes or coins available are 1000, 500, 100, 50, 20, 10, 5, 2 and 1.
Examples:
Input:
N =
1712,
M
= 4
Output:
12
Explanation:
The boss will give him one 1000, one 500
and two 100 notes, one note of 10 and
one of 2. But because the employee can't
have more notes than 4, he can have a
maximum amount of 1700.
So, he will lose 12.
Input:
N =
1023,
M
= 2
Output:
3
Explanation:
The boss will give him one 1000, one 20
one 2 and one note of 1. But because the
employee can't have more notes than 2,
he can have a maximum amount of 1020.
So, he will lose 3.
Constraints:
1 <= N,M <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int getLoss(int N, int M)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n \n int N = Integer.parseInt(S[0]);\n int M = Integer.parseInt(S[1]);\n\n Solution ob = new Solution();\n System.out.println(ob.getLoss(N,M));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static int getLoss(int N, int M) {\n int c = 0, n, d;\n // taking all 1000 notes possible\n n = N / 1000;\n d = Math.min(n, M);\n c += d;\n N -= d * 1000;\n M -= d;\n // taking all 500 notes possible\n n = N / 500;\n d = Math.min(n, M);\n c += d;\n N -= d * 500;\n M -= d;\n // taking all 100 notes possible\n n = N / 100;\n d = Math.min(n, M);\n c += d;\n N -= d * 100;\n M -= d;\n // taking all 50 notes possible\n n = N / 50;\n d = Math.min(n, M);\n c += d;\n N -= d * 50;\n M -= d;\n // taking all 20 notes possible\n n = N / 20;\n d = Math.min(n, M);\n c += d;\n N -= d * 20;\n M -= d;\n // taking all 10 notes possible\n n = N / 10;\n d = Math.min(n, M);\n c += d;\n N -= d * 10;\n M -= d;\n // taking all 5 notes possible\n n = N / 5;\n d = Math.min(n, M);\n c += d;\n N -= d * 5;\n M -= d;\n // taking all 2 notes possible\n n = N / 2;\n d = Math.min(n, M);\n c += d;\n N -= d * 2;\n M -= d;\n // taking all 1 notes possible\n n = N;\n d = Math.min(n, M);\n c += d;\n N -= d;\n M -= d;\n return N;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int getLoss(int N, int M) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"getLoss(self, N, M)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, M = map(int, input().split())\n ob = Solution()\n print(ob.getLoss(N, M))\n print(\"~\")\n",
"solution": "class Solution:\n def getLoss(self, N, M):\n c = 0\n\n # taking all 1000 notes possible\n n = N // 1000\n d = min(n, M)\n c += d\n N -= d * 1000\n M -= d\n\n # taking all 500 notes possible\n n = N // 500\n d = min(n, M)\n c += d\n N -= d * 500\n M -= d\n\n # taking all 100 notes possible\n n = N // 100\n d = min(n, M)\n c += d\n N -= d * 100\n M -= d\n\n # taking all 50 notes possible\n n = N // 50\n d = min(n, M)\n c += d\n N -= d * 50\n M -= d\n\n # taking all 20 notes possible\n n = N // 20\n d = min(n, M)\n c += d\n N -= d * 20\n M -= d\n\n # taking all 10 notes possible\n n = N // 10\n d = min(n, M)\n c += d\n N -= d * 10\n M -= d\n\n # taking all 5 notes possible\n n = N // 5\n d = min(n, M)\n c += d\n N -= d * 5\n M -= d\n\n # taking all 2 notes possible\n n = N // 2\n d = min(n, M)\n c += d\n N -= d * 2\n M -= d\n\n # taking all 1 notes possible\n n = N\n d = min(n, M)\n c += d\n N -= d\n M -= d\n\n return N\n",
"updated_at_timestamp": 1731580434,
"user_code": "#User function Template for python3\n\nclass Solution:\n def getLoss(self, N, M):\n # code here"
}
|
eJytk70KwkAQhC30PZarRe5XEys7X0HwxEJT2MQUEQRRfAh9X281gQjOGX+mCsx+d7MT7ty9Tnudu2aT8DE/iE1e7EoxJqF8nrJISZ+LPolsX2SrMlsvt7uymkl4wOenMHDs0zPsrNGKHGRtGnzAJixSGB6ZMABgpY11ZCCbBhugaTIaOtKxe8MAupdFCrJKBh+wmkUaN80+YA2LDGbZB6xlkcUs++gHs8hhlv23+94PqtvjA73XkTMjPTzyyF8CuUYi79pmkrFA8YZku47c/3uqL4DRLE5W7RVf6+uiP625enc/vbqX7TY3bdX04jK4AZ44kZo=
|
703,119
|
Search Pattern (KMP-Algorithm)
|
Given two strings, one is a text string,txt and the other is a pattern string, pat. The task is to print the indexes of all the occurrences of the pattern string in the text string. Use 1-based indexing while returning the indices.Note:Return an empty list in case of no occurrences of pattern. The driver will print -1 in this case.
Examples:
Input:
txt = "abcab", pat = "ab"
Output:
[1, 4]
Explanation:
The string "ab" occurs twice in txt, one starts are index 1 and the other at index 4.
Input:
txt = "abesdu", pat = "edu"
Output:
[-1]
Explanation:
There's not substring "edu" present in txt.
Input:
txt = "aaaaa", pat = "aa"
Output:
[1, 2, 3, 4]
Explanation:
The string "aa" occurs four times, starts from indexes 0, 1, 2, 3.
Constraints:
1 ≤ txt.size() ≤ 10**6
1 ≤ pat.size() < txt.size()
Both the strings consist of lowercase English alphabets.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1731402181,
"func_sign": [
"ArrayList<Integer> search(String pat, String txt)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while (t-- > 0) {\n String s, patt;\n s = sc.next();\n patt = sc.next();\n\n Solution ob = new Solution();\n\n ArrayList<Integer> res = ob.search(patt, s);\n if (res.size() == 0)\n System.out.print(\"[]\");\n else {\n for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + \" \");\n }\n System.out.println();\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1731402181,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n ArrayList<Integer> search(String pat, String txt) {\n // your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731402181,
"func_sign": [
"search(self, pat, txt)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n s = input().strip()\n patt = input().strip()\n ob = Solution()\n ans = ob.search(patt, s)\n if len(ans) == 0:\n print(\"[]\", end=\"\")\n else:\n for value in ans:\n print(value, end=' ')\n print()\n",
"solution": "class Solution:\n def computeLPSArray(self, pat, M, lps):\n length = 0\n\n # Initializing the longest prefix suffix array\n lps[0] = 0\n i = 1\n\n while i < M:\n # If the characters match, increment the length and store it in the lps array\n if pat[i] == pat[length]:\n length += 1\n lps[i] = length\n i += 1\n else:\n # If the characters don't match\n if length != 0:\n # Update the length to the value at the previous index in the lps array\n length = lps[length - 1]\n else:\n # If the length is 0, assign 0 to the lps array and move to the next index\n lps[i] = 0\n i += 1\n\n def search(self, pat, txt):\n res = []\n M = len(pat)\n N = len(txt)\n\n # Initializing the longest prefix suffix array\n lps = [0 for i in range(M + 1)]\n\n j = 0\n\n # Calculate the longest prefix suffix array\n self.computeLPSArray(pat, M, lps)\n\n f = 0\n i = 0 # index for txt[]\n\n while i < N:\n # If the characters match, move to the next characters\n if pat[j] == txt[i]:\n j += 1\n i += 1\n\n if j == M:\n # If the entire pattern is found, append the starting index to the result list\n f += 1\n res.append(i - j + 1)\n j = lps[j - 1]\n\n # If there is a mismatch\n elif i < N and pat[j] != txt[i]:\n if j != 0:\n # Update the j value to the value at the previous index in the lps array\n j = lps[j - 1]\n else:\n # If j is 0, move to the next character in the text\n i = i + 1\n\n if f == 0:\n # If the pattern is not found in the text, append -1 to the result list\n res.append(-1)\n\n return res\n",
"updated_at_timestamp": 1731402181,
"user_code": "#User function Template for python3\n\nclass Solution:\n def search(self, pat, txt):\n # code here"
}
|
eJzFVdtKxDAQ9cEHP2Po8ypNevdLBCPS27oVmi22C1UR/Aj9Ft/8NjOpxbqb6UUWTNPusKFzzpy59PX0/fPsRK+rD2VcP1uFrHaNdQkWEzJOzFd3Yq3AytsqT5s8u93umv49cMCDACJgDJgDzAMWAIuAMxDSelnBHshgJUMbUSgMDtw1emsfn0Z2f05SdxVxZmvavuasgDwz7SQd2UJ2BgHkgI/6cC1OiMoQ4TR53VB3d0qG4iGCg9qje3MQZVHXuKuqMJtCokFgcIXRKaXY84CSKaNuIb9Nwr8LodZI+bcnSweX/ocUhKvCdBVlX+U4RHFsXaFcx2CWH+nl67tNcW+yhMQfAs/XvH2j24dYZtuSegqJT7JyIiwaTCklOF4G5ROj9Aub+9zcw32DtX9sO8yDq0vVBu5Qsg1zQKRjTeaDYN53LBvp45mFQLc7Gc5c6M0k9mJoMpyjM5toFCIxB/Oo3JtN84aTGnw8HB8ec6fU1EdposJ+9n8lYMEHakYsR6eZxr/eTmazvHm7+AIvHAAl
|
702,833
|
Minimum Distinct Ids
|
Given an array of items, the i'th index element denotes the item id’s and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct id’s.
Examples:
Input:
n = 6
arr[] = {2, 2, 1, 3, 3, 3}
m = 3
Output:
1
Explanation :
Remove 2,2,1
Input:
n = 8
arr[] = {2, 4, 1, 5, 3, 5, 1, 3}
m = 2
Output:
3
Explanation:
Remove 2,4
Constraints
:
1 ≤ n ≤ 10**5
1 ≤ arr[i] ≤ 10**6
1 ≤ m ≤ 10**3
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617823396,
"func_sign": [
"int distinctIds(int arr[], int n, int m)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])\n {\n Scanner sc = new Scanner(System.in);\n \n int t = sc.nextInt();\n while (t-- > 0)\n {\n int n = sc.nextInt();\n \n int arr[] = new int[n];\n \n for (int i = 0;i < n;i++)\n {\n arr[i] = sc.nextInt();\n }\n int m = sc.nextInt();\n \n System.out.println(new Solution().distinctIds(arr, n, m));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n int distinctIds(int arr[], int n, int m) {\n HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();\n ArrayList<Integer> a = new ArrayList<Integer>();\n int count = 0;\n // Store the occurrence of ids\n for (int i = 0; i < n; i++) {\n if (mp.containsKey(arr[i])) {\n int val = mp.get(arr[i]);\n mp.put(arr[i], val + 1);\n } else {\n mp.put(arr[i], 1);\n }\n }\n // Store into the ArrayList frequencies of unique IDs\n Iterator it = mp.entrySet().iterator();\n while (it.hasNext()) {\n Map.Entry me = (Map.Entry) it.next();\n a.add((Integer) me.getValue());\n }\n // Sort the ArrayList\n Collections.sort(a);\n int size = a.size();\n // Start removing elements from the beginning\n for (int i = 0; i < size; i++) {\n // Remove if current value is less than\n // or equal to\n if (a.get(i) <= m) {\n m -= a.get(i);\n count++;\n }\n // Return the remaining size\n else break;\n }\n return size - count;\n }\n}\n",
"updated_at_timestamp": 1730468918,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n int distinctIds(int arr[], int n, int m)\n {\n // Complete this function\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617823396,
"func_sign": [
"distinctIds(self,arr : list, n : int, m : int)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n n = int(input())\n arr = [int(x) for x in input().split()]\n m = int(input())\n ob = Solution()\n print(ob.distinctIds(arr, n, m))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nfrom collections import defaultdict\n\n\nclass Solution:\n def distinctIds(self, arr: list, n: int, m: int):\n mp = defaultdict(int)\n count = 0\n\n # Store the occurrence of IDs.\n for i in arr:\n mp[i] += 1\n\n # Store the frequencies in the list\n a = list()\n for key, value in mp.items():\n a.append(value)\n\n # Sort the list\n a.sort()\n sz = len(a)\n # Start removing elements from the beginning\n for i in a:\n # Remove if current value is less than or equal to\n if i <= m:\n m -= i\n count += 1\n else:\n break\n return sz - count\n",
"updated_at_timestamp": 1730468918,
"user_code": "#User function Template for python3\n\nclass Solution:\n def distinctIds(self,arr : list, n : int, m : int):\n # Complete this function"
}
|
eJzNVctOwzAQ5MCFP+BWy+cK2U7ctHwJUo04QA5cTA+phISo+hHt/7LY8aNONo1DpZL1IVKS2Z3d2cn+9ji7uzHX0z3crL/ou95sG/pIKFfaHzontP7c1K9N/fbysW3aV5jSO3j4PSfJd/CAE04ERAFRQkgilZYoVJELxVAoiUBVFsliAZrSBYohEIyVwwgVAUiZjcNlLy2ygKgglqZcBLREQEV/rwIoxAqCM2Lamt9C8TtDIj2qQ3boLoPP4k5LOXP4hSEkQqsNpfKkgDh5mpibxALniXVSssAz5hrzjTnHvDvcQy2nRyTHtveqlfJuqa1WJ5SMiaijfZckkateKiUG1gBzHyvSRCCuAwwRaDWs0CE/OONSiV0M+wXKqSfBdXU6zVgwfouJq25dPWPjqzHGzv/i7H5SI35Vl9jqi/rkWZFkT/bfUfG2Mp7T8+HhB51XRGI=
|
711,597
|
Path With Minimum Effort
|
You are a hiker preparing for an upcoming hike. You are givenheights[][], a 2D array of sizerows x columns, whereheights[row][col]represents the height of cell(row, col). You are situated in the top-left cell,(0, 0), and you hope to travel to the bottom-right cell,(rows-1, columns-1)(i.e.,0-indexed). You can moveup,down,left, orright, and you wish to find the route with minimum effort.
Examples:
Input:
row = 3
columns = 3
heights = [[1,2,2],[3,8,2],[5,3,5]]
Output:
2
Explanation:
The route 1->3->5->3->5 has a maximum absolute difference of 2 in consecutive cells. This is better than the route 1->2->2->2->5, where the maximum absolute difference is 3.
Input:
row = 2
columns = 2
heights = [[7,7],[7,7]]
Output:
0
Explanation:
Any route from the top-left cell to the bottom-right cell has a maximum absolute difference of 0 in consecutive cells.
Constraints:
1 <= rows, columns <= 100
rows == heights.length
columns == heights[i].length
0 <= heights[i][j] <= 10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1714068859,
"func_sign": [
"public static int MinimumEffort(int rows, int columns, int[][] heights)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass IntMatrix {\n public static int[][] input(BufferedReader br, int n, int m) throws IOException {\n int[][] mat = new int[n][];\n\n for (int i = 0; i < n; i++) {\n String[] s = br.readLine().trim().split(\" \");\n mat[i] = new int[s.length];\n for (int j = 0; j < s.length; j++) mat[i][j] = Integer.parseInt(s[j]);\n }\n\n return mat;\n }\n\n public static void print(int[][] m) {\n for (var a : m) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n }\n\n public static void print(ArrayList<ArrayList<Integer>> m) {\n for (var a : m) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n }\n}\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n int rows;\n rows = Integer.parseInt(br.readLine());\n\n int columns;\n columns = Integer.parseInt(br.readLine());\n\n int[][] heights = IntMatrix.input(br, rows, columns);\n\n Solution obj = new Solution();\n int res = obj.MinimumEffort(rows, columns, heights);\n\n System.out.println(res);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public static int MinimumEffort(int rows, int columns,\n int[][] heights)\n {\n // code here\n int N = heights.length;\n int M = heights[0].length;\n\n // Priority queue containing pairs of cells and\n // their respective distance from the source cell\n PriorityQueue<int[]> pq = new PriorityQueue<>(\n (a, b) -> Integer.compare(a[0], b[0]));\n\n // Distance matrix with initially all the cells\n // marked as unvisited\n int[][] d = new int[N][M];\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n d[i][j] = Integer.MAX_VALUE;\n }\n }\n\n // Distance for the source cell (0, 0) is 0\n d[0][0] = 0;\n pq.add(new int[] { 0, 0, 0 });\n\n // Array to traverse in all four directions\n int[] dx = { -1, 0, 1, 0 };\n int[] dy = { 0, 1, 0, -1 };\n\n // Iterate through the matrix by popping the\n // elements out of the queue and pushing whenever a\n // shorter distance to a cell is found\n while (!pq.isEmpty()) {\n int[] cell = pq.poll();\n int diff = cell[0];\n int r = cell[1];\n int c = cell[2];\n\n // Return the current value of difference (which\n // will be min) if we reach the destination\n if (r == N - 1 && c == M - 1)\n return diff;\n\n for (int i = 0; i < 4; i++) {\n int nx = dx[i] + r;\n int ny = dy[i] + c;\n\n // Checking validity of the cell\n if (nx >= 0 && nx < N && ny >= 0\n && ny < M) {\n // Effort can be calculated as the max\n // value of differences between the\n // values of the node and its adjacent\n // nodes\n int nf = Math.max(\n Math.abs(heights[r][c]\n - heights[nx][ny]),\n diff);\n\n // If the calculated effort is less than\n // the previous value update as we need\n // the min effort\n if (nf < d[nx][ny]) {\n d[nx][ny] = nf;\n pq.add(new int[] { nf, nx, ny });\n }\n }\n }\n }\n // If unreachable\n return -1;\n }\n}",
"updated_at_timestamp": 1730481384,
"user_code": "\nclass Solution {\n public static int MinimumEffort(int rows, int columns, int[][] heights) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1714068859,
"func_sign": [
"MinimumEffort(self, rows : int, columns : int, heights : List[List[int]]) -> int"
],
"initial_code": "class IntMatrix:\n\n def __init__(self) -> None:\n pass\n\n def Input(self, n, m):\n matrix = []\n # matrix input\n for _ in range(n):\n matrix.append([int(i) for i in input().strip().split()])\n return matrix\n\n def Print(self, arr):\n for i in arr:\n for j in i:\n print(j, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n rows = int(input())\n columns = int(input())\n heights = IntMatrix().Input(rows, columns)\n obj = Solution()\n res = obj.MinimumEffort(rows, columns, heights)\n print(res)\n print(\"~\")\n",
"solution": "from collections import deque\n\n\nclass Solution:\n\n def check(self, a, mid):\n n = len(a)\n m = len(a[0])\n\n # Creating a boolean matrix to keep track of visited cells.\n vis = [[False] * m for _ in range(n)]\n\n q = deque()\n\n # Pushing the starting cell into the queue and marking it as visited.\n q.append((0, 0))\n vis[0][0] = True\n\n # Arrays to store the x and y directions for neighboring cells.\n xdir = [1, 0, -1, 0]\n ydir = [0, -1, 0, 1]\n\n # BFS traversal of the matrix.\n while q:\n temp = q.popleft()\n\n # If we reach the destination cell, return True.\n if temp[0] == n - 1 and temp[1] == m - 1:\n return True\n\n # Checking the neighboring cells and pushing them into the queue if valid.\n for k in range(4):\n x = temp[0] + xdir[k]\n y = temp[1] + ydir[k]\n\n # If the neighboring cell is out of bounds or already visited or the\n # difference in effort between the neighboring cell and the current\n # cell is greater than the mid value, skip it.\n if x < 0 or y < 0 or x >= n or y >= m or vis[x][y] or abs(a[x][y] - a[temp[0]][temp[1]]) > mid:\n continue\n\n # Pushing the valid neighboring cell into the queue and marking it as\n # visited.\n q.append((x, y))\n vis[x][y] = True\n\n # If we reach here, it means we couldn't reach the destination cell with the given mid value.\n return False\n\n def MinimumEffort(self, rows, columns, heights):\n n = len(heights)\n m = len(heights[0])\n\n l = 0\n h = 10**6\n\n # Binary search to find the minimum effort.\n while l < h:\n mid = l + (h - l) // 2\n\n # Checking if the mid value is feasible or not by using BFS.\n if self.check(heights, mid):\n h = mid # If feasible, update the high value\n else:\n l = mid + 1 # If not feasible, update the low value\n\n return l # Returning the minimum effort.\n",
"updated_at_timestamp": 1730481384,
"user_code": "\nfrom typing import List\nclass Solution:\n def MinimumEffort(self, rows : int, columns : int, heights : List[List[int]]) -> int:\n # code here\n \n"
}
|
eJzlVs2KwjAQ3oOnfYqQy16KNKlR9EkEu3jY7cFLt4cKgig+hL6vYTZOE5uZ2uJhWdOBhEzyzTd/oafRZfz+BmP5YRervdyU1baWCyFVXk5AlFApjPvZqtyGplW3OaNVt9nakomQxa4qvurie/2zrR2XOYy8PNoTh0SELA2IsiTgy8sWG5wDpYlvR+8gNkFQEdwyEIT0YtDYieqHBGIKogR+TO4C815ITE8FD9sQIfxJCVdmIB7CndXYyp2nCMV5G5L5gzgMk8He/wpdBfy9rhqibmuQSAvTUHiUAfRQ0s765gFdN7VygHsvVGVPK7M+T5QIDwyvtb/6VPUOI+062WCN+8RNw/aT7gZQcwoiSDYuwgy4tP7D/sBtz4qLJJf4R165NNJMTXz5dPVCVk+E1g7b/efxUBoj8HkeXwHpnZO2
|
710,141
|
Replace every element with the least greater element on its right
|
Given an array arr[] of N integers and replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with -1.
Examples:
Input:
arr[] = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28}
Output:
{18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1}
Explanation:
The least next greater element of 8 is 18.
The least next greater element of 58 is 63 and so on.
Input:
arr[] = {2, 6, 9, 1, 3, 2}
Output:
{3, 9, -1, 2, -1, -1}
Explanation:
The least next greater element of 2 is 3.
The least next greater element of 6 is 9.
least next greater element for 9 does not
exist and so on.
Constraints:
1 <= N <= 10**5
1<= A[i] <= 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1650387689,
"func_sign": [
"public static ArrayList<Integer> findLeastGreater(int n, int[] arr)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\nclass IntArray\n{\n public static int[] input(BufferedReader br, int n) throws IOException\n {\n String[] s = br.readLine().trim().split(\" \");\n int[] a = new int[n];\n for(int i = 0; i < n; i++)\n a[i] = Integer.parseInt(s[i]);\n \n return a;\n }\n \n public static void print(int[] a)\n {\n for(int e : a)\n System.out.print(e + \" \");\n System.out.println();\n }\n \n public static void print(ArrayList<Integer> a)\n {\n for(int e : a)\n System.out.print(e + \" \");\n System.out.println();\n }\n}\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while(t-- > 0){\n \n int n; \n n = Integer.parseInt(br.readLine());\n \n \n int[] arr = IntArray.input(br, n);\n \n Solution obj = new Solution();\n ArrayList<Integer> res = obj.findLeastGreater(n, arr);\n \n IntArray.print(res);\n \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public static ArrayList<Integer> findLeastGreater(int n, int[] arr) {\n // Initializing a TreeSet to store unique elements in sorted order\n TreeSet<Integer> ts = new TreeSet<>();\n\n // Initializing an array to store the result\n int a[] = new int[n];\n \n // Iterating over the input array in reverse order\n for (int i = n-1; i >= 0; i--) {\n // Finding the least element greater than arr[i] in the TreeSet\n if (ts.ceiling(arr[i] + 1) == null) {\n // If there is no such element, set a[i] to -1\n a[i] = -1;\n } else {\n // If there is a greater element, set a[i] to that element\n a[i] = ts.ceiling(arr[i] + 1);\n }\n \n // Adding the current element to the TreeSet\n ts.add(arr[i]);\n }\n \n // Converting the result array to an ArrayList and returning it\n ArrayList<Integer> A = new ArrayList<>();\n for (int i : a) {\n A.add(i);\n }\n return A;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n public static ArrayList<Integer> findLeastGreater(int n, int[] arr) {\n // code here\n }\n}\n \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1650387689,
"func_sign": [
"findLeastGreater(self, n : int, arr : List[int]) -> List[int]"
],
"initial_code": "class IntArray:\n def __init__(self) -> None:\n pass\n\n def Input(self, n):\n arr = [int(i) for i in input().strip().split()] # array input\n return arr\n\n def Print(self, arr):\n for i in arr:\n print(i, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n n = int(input())\n arr = IntArray().Input(n)\n obj = Solution()\n res = obj.findLeastGreater(n, arr)\n IntArray().Print(res)\n print(\"~\")\n",
"solution": "from typing import List\nfrom sortedcontainers import SortedList\n\n\nclass Solution:\n\n # Function to find the least greater element for each element in the array.\n def findLeastGreater(self, n, arr):\n s = SortedList([])\n ans = [0] * n\n for i in range(n-1, -1, -1):\n # Finding the index where the current element could be inserted in the sorted list.\n ind = s.bisect_right(arr[i])\n\n # If the index is at the end of the sorted list, there is no element greater than the current element.\n if ind == len(s):\n ans[i] = -1\n else:\n # Otherwise, set the answer as the least greater element found in the sorted list.\n ans[i] = s[ind]\n\n # Add the current element to the sorted list.\n s.add(arr[i])\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "\n\nfrom typing import List\nclass Solution:\n def findLeastGreater(self, n : int, arr : List[int]) -> List[int]:\n # code here\n \n"
}
|
eJztV81uE0EM5sAD8AjWnls09nj+eBIkUnGgOXBZekglJATiIeB9sb9NokI7myZpSVV1M2NNov2+sT2fvZufr39fvnmF6/2FLT58Gz6PV9er4R0NvBglLEZOxIEkUEykZgOlQDmQJpJEKVGxr7agkqgFqmYT1WCgMJzRsPx6tfy0Wl5+/HK9WhML6AR0xqJgybDTomyG0TTwGRnmOdNi/LEYh+9n9I+ryVwNflHzC7bCFtgMm2AVNsIKLMPaJiQUSS2cTIUM78EzEwtxJNZOSObX/JhnnYkr2hEk3FgNrABa5tl4DFqNlovzqfN5WokzcfNAxHMsShJJMkkjqSTFTrATRIYzzZgLnMtOUZ26+Q5t/eP0+7SL7yGbDabhG6xHP6rkwnIhCWnz1FQLTYslSLOHaadPqra52iGRioet7A6YZiwZsbmvEc7F4hmJcMw0aumI6tmKCCYKtMueMnPJvW1wuCI1BTnKPaV6CNENjii5yW6Km+qmuWHEyjhpBoiBmk6WgWMAGUgGlIEVYGVSCbACrAArwEqeyaWp3iXyLD6HltfL2I6eSmz0s9trql6lU1ftYNctd6bSt215w0Q7KM+3N/616qrfp5VhtaLM3kCsYK1fHKSkuT3uaOHdrnGr15+weh+D1B6U+xUwEC/zUeaRfeEh9KfxySvQXTzlPLVKnq4C9/qTEU78L2Onrxtnp5I40l0jSptFwZvgfu7e/eDSeu9Hl9+6Hz/f+9F44835wGzXo6RhVLelYc4cIo3eTg+s9v8t9/7L2453N7q5WJNf/Hr7ByzIb2s=
|
714,215
|
Wifi Range
|
There areN rooms in a straight line in Geekland State University's hostel, you are given a binary string S of length N where S[i] = '1' represents that there is a wifi in i**th room orS[i] = '0'represents no wifi. Each wifi has range X i.e. if there is a wifi in i**th room then its range will go upto X more rooms on its left as well as right. You have to find whether students inall rooms can use wifi.
Examples:
Input:
N = 3, X = 0
S = "010"
Output:
0
Explanation:
Since the range(X)=0, So Wifi is only
accessible in second room while 1st & 3rd
room have no wifi.
Input:
N = 5, X = 1
S = "10010"
Output:
1
Explanation:
Index 0 : Wifi is available
Index 1 : Since range of 0th Index is 1
so, here wifi will be available.
Index 2 : Since range of 3rd Index is 1
so, here also wifi available.
Index 3 : Wifi is available
Index 4 : here range of 3rd Index is available.
So all the rooms have wifi, so return true.
Constraints:
1 ≤ N≤ 10**6
0 ≤ X≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1678707319,
"func_sign": [
"boolean wifiRange(int N, String S, int X)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*; \nclass GFG{\n public static void main(String args[]) throws IOException { \n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n \n while(t-- > 0){\n String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n int N = Integer.parseInt(input_line[0]);\n int X = Integer.parseInt(input_line[1]);\n String S = read.readLine().trim();\n Solution ob = new Solution();\n boolean ans = ob.wifiRange(N, S, X); \n if(ans)\n System.out.println(1);\n else\n System.out.println(0);\n \nSystem.out.println(\"~\");\n}\n } \n} ",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\nclass Solution \n{ \n boolean wifiRange(int N, String S, int X) \n { \n int A[] = new int[N];\n Arrays.fill(A,(int)-1e9);\n int B[] = new int[N];\n Arrays.fill(B,(int)1e9);\n int cur = (int)-1e9;\n for(int i = 0; i < N; i++){\n if(S.charAt(i) == '1'){\n cur = i;\n }\n A[i] = cur;\n }\n cur = (int)1e9;\n for(int i = N - 1; i >= 0; i--){\n if(S.charAt(i) == '1'){\n cur = i;\n }\n B[i] = cur;\n }\n for(int i = 0; i < N; i++){\n if(Math.abs(i - A[i]) > X && Math.abs(i - B[i]) > X){\n return false;\n }\n }\n return true;\n }\n}",
"updated_at_timestamp": 1730482414,
"user_code": "//User function Template for Java\nclass Solution \n{ \n boolean wifiRange(int N, String S, int X) \n { \n // code here\n }\n} "
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1678707319,
"func_sign": [
"wifiRange(self, N, S, X)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, X = map(int, input().strip().split())\n S = input()\n ob = Solution()\n ans = ob.wifiRange(N, S, X)\n if ans:\n print(1)\n else:\n print(0)\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n def wifiRange(self, N, S, X):\n # creating an array A to store the index of the nearest access point to the left from the current position\n A = [-10**9]*N\n\n # creating an array B to store the index of the nearest access point to the right from the current position\n B = [1e9]*N\n\n # initializing a variable cur to -10^9\n cur = -10**9\n\n # iterating through the positions\n for i in range(N):\n # if an access point is present at the current position, update cur to the current position\n if S[i] == '1':\n cur = i\n\n # store the index of the nearest access point to the left from the current position in the array A\n A[i] = cur\n\n # initializing a variable cur to 10^9\n cur = 10**9\n\n # iterating through the positions in reverse order\n for i in range(N-1, -1, -1):\n # if an access point is present at the current position, update cur to the current position\n if S[i] == '1':\n cur = i\n\n # store the index of the nearest access point to the right from the current position in the array B\n B[i] = cur\n\n # iterating through the positions\n for i in range(N):\n # if the distance between the current position and the nearest access point to the left is greater than X\n # and the distance between the current position and the nearest access point to the right is greater than X\n if abs(i - A[i]) > X and abs(i - B[i]) > X:\n # return False as it is not possible to have WiFi coverage at the current position\n return False\n\n # return True as it is possible to have WiFi coverage at all positions\n return True\n",
"updated_at_timestamp": 1730482414,
"user_code": "#User function Template for python3\nclass Solution:\n def wifiRange(self, N, S, X): \n #code here"
}
|
eJxrYJlazcIABhElQEZ0tVJmXkFpiZKVgpJhTJ6hgkFMHhAp6SgopVYUpCaXpKbE55eWQFUAZeqAkrU6Cli0GeLUZohDm5ECkDAg3TqwPkNy7AM5k3T7TBVMQPoM8DgVl5WmCkYgL+LTistWM4hrQZAMvSBrwZpJdrKhgYIxyM0gDxuS7Ge8CQFPlMTEgEKL9IRAYQoioB+nFwm5GLsWaFrAk8Ow6oshQXEe3vSCMw8STi5EBGUeUWEZO0UPADW0ZUU=
|
712,039
|
Pattern 21
|
Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geekan integer n and asked him to build a pattern.
Examples:
Input:
4
Output:
****
* *
* *
****
Constraints:
1<= N <= 20
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1662635401,
"func_sign": [
"void printSquare(int n)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass Main {\n // Driver code\n public static void main(String[] args) throws Exception {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim());\n while (t-- > 0) {\n int n = Integer.parseInt(br.readLine().trim());\n Solution obj = new Solution();\n obj.printSquare(n);\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730481465,
"user_code": "class Solution {\n\n void printSquare(int n) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1663319519,
"func_sign": [
"printTriangle(self, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N = int(input().strip())\n ob = Solution()\n ob.printTriangle(N)\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n\n # Function to print a triangle pattern.\n def printTriangle(self, n):\n # iterating over rows of the triangle.\n for i in range(1, n + 1):\n # iterating over columns of the triangle.\n for j in range(1, n + 1):\n # printing '*' at the boundary of the triangle.\n if (i == 1 or i == n or j == 1 or j == n):\n print('*', end='')\n # printing space inside the triangle.\n else:\n print(' ', end='')\n # printing a new line after each row.\n print()\n",
"updated_at_timestamp": 1730481465,
"user_code": "#User function Template for python3\n\nclass Solution:\n def printTriangle(self, N):\n # Code here"
}
|
eJzs2r1u1HeDhuEt9kCsKREFJkBIim32JFbakVIkLtJMKIwUKUr0Ht4e1o6BED7MR14l8IT7uhRj+w/4N4/HnttB86///J//+r///o///eXw4+nJ0+vDtxeH+8fTw+Pp6+PpcPficPXzk6vvr69++O6np9cvfv/OjePpzsXFxduvnv/eby/e+v3PvfwjH3zjzh8f4fDr3YtXbtZXx9P5v0fH0+P33bKbj/X847xyK14c8L7Xb93wl7fq4t976z1LLo+n+/fe/+l9w8uP/CpXP9fVW++ht+/nB+f7+Xi6PN/Vl+dvqMtv3nOX33zQ1776XrvP/663X7/1H/ia+9Iu3HL/feR3not//cWP+446P3Jevvu76La/cf/Z33jfw+277vmVBxtX/9SD7lfPfnq5ecD9UGM/9kcYD4i+LXavfuS3xYMXP4jcPB4+/sAPI7fc05/+J5DXBn/+9z78nXHLPeTan7t2+1fyRz4GufjXX/y4x5aHz/7P/Ovzo8r51eXXHyrvzWHPP/hf9A8F7/nS2H33w1/mb98pLr166WMfLFZK7eqf+onl0bN/7Dv/nHJ587PLo+c/s3zw381enPq+17d8sfxxW/+aN9/zJfnGp+Wf+P6Hv+veuu9bVz7ygemz5z1y8R2PN7c/EE08RLr6p1Lx7F/4/p3/w/3nu/VT909lzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pdX96aL8jx9NvxdPj17sUvhx9PT55eH769ODw4nu4fT5f37p1/eXh++ep4Ov/36Hh6fDx9c/7Tdy8OVz8/ufr++uqH7356ev3ib9159pl59vE+zQ3/BF9UTnGKU5ziFKc4xSlOcYpTnOIUpzjFKU5xilOc4hSnOMUpTnGKU5ziFKc4xSlOcYpTnOIUp/y9p3ySZ9y9/dS+N/d9aRc+9Bl4/e/svvvWijee8nl5PN2/984ndt72tXDL17Wrn+vqu75bb7uXH9w8tff8cvMU38fPntn78PnzfO/fe//Te78cn+RR+VOxZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc2uL2/NF+R4+u14Ovx69+KXw4+nJ0+vD99eHL46ns7/PTqeHhxP94+ny3v3zr88PL+8/I3Hx9M3z3493L04XP385Or766sfvvvp6fWLj/DsA9958bl6dsTvp935/XP4rtd/3KqXf+GPX99xg1+9nZfnt+89uHnv/HJz9XwrL8839s3b/8aWdw65OfWVBX/3vfEJvlOc4hSnOMUpTnGKU5ziFKc4xSlOcYpTnOIUpzjFKU5xilOc4hSnOMUpTnGKU5ziFKc4xSlO+XtP+STPuHv9qX2vbvuU77z7Fv3jfXFP//3ct+GvY80ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXdbssmaXNbus2WXNLmt2WbPLml3W7LJmlzW7rNllzS5rdlmzy5pd1uyyZpc1u6zZZc0ua3ZZs8uaXTdrviDH02/H0+HXuxe/HH48PXl6ffj24nB5PN2/9+DB+dfj6fLe+eXh+eWb4+nFe/ePx+d/4uX7p8vHz//Ei1eHuxeHq5+fXH1/ffXDdz89vX7xcT/3VgDg0/qifgYEAD5M/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv0BoEb9AaBG/QGgRv3/v107WI3yAKMwfCthlkVKtFpqr2VKF5qFm9FFBEH0KnrBnaQK1uqiYKcvnufBxJgo37wSOCI/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCssf4AsMb6A8Aa6w8Aa6w/AKyx/gCwxvoDwBrrDwBrrD8ArLH+ALDG+gPAGusPAGusPwCsuVt/AGDK8fT+eDq8e3D19vDi9Or17eHXq8Pj4+n849Hx9PD6+vzu4fnj68d3vzq/3X32l/Pb0+Ppyfmnn46n84+fj6df7j+4//j41x/7/MtP79+fjz24Oty8eXXz7Pbm+e8vX99+OPrXi/nh439HfPhnyf3Lu//Cxw8v8Vdygf8OccUVV1xxxRVXXHHFFVdcccUVV1xxxRVXXHHFFVdcccUVV1xxxRVXXHHFFVdcccWV//bKRZ64+/ujfZ+2XfIXn72ifz4W+cVnIj/9/Bceevz6g5IffsNXH4j01KMrrrjiiiuuuOKKK6644oorrrjiiiuuuOKKK6644oorrrjiiiuuuOKKK6644oorrvy7Kxd54i751OMl0i/lIt8ul6KmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41Xd9fzXfkeHp/PB3ePbh6e3hxevX69vDr1eHh8fTo+vHx9PD6/Pboyfndk7vPHE9Pz7/1wdXh5s2rm2e3N89/f/n69sMf+b8zvqXv7tv1/34N346aLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdKnpUtOlpktNl5ouNV1qutR0qelS06WmS02Xmi41XWq61HSp6VLTpaZLTZeaLjVdarrUdN3VfEeOp/fH0+Hdb3/8+CcIemKa
|
713,137
|
Minimize number of Students to be removed
|
N Students of different heights are attending an assembly. The heights of the students are represented by an array H[]. The problem is that if a student has less or equal height than the student standing in front of him, then he/she cannot see the assembly. Find the minimum number of students to be removed such that all the remaining students can see the assembly.
Examples:
Input:
N = 6
H[] = {9, 1, 2, 3, 1, 5}
Output:
2
Explanation:
We can remove the students at 0 and 4th index.
which will leave the students with heights
1,2,3, and 5.
Input:
N = 3
H[] = {1, 2, 3}
Output:
0
Explanation:
All of the students are able to see the
assembly without removing anyone.
Constraints:
1 ≤ N ≤ 10**5
1 ≤ H[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1671443990,
"func_sign": [
"public int removeStudents(int[] H, int N)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out=new PrintWriter(System.out);\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int N = Integer.parseInt(read.readLine());\n \n String S[] = read.readLine().split(\" \");\n int[] H = new int[N];\n \n for(int i=0; i<N; i++)\n H[i] = Integer.parseInt(S[i]);\n\n Solution ob = new Solution();\n out.println(ob.removeStudents(H,N));\n \nout.println(\"~\");\n}\n out.close();\n }\n}",
"script_name": "GFG",
"solution": "// Back-end function Template for Java\n\nclass Solution {\n\n // Function to find the length of the Longest Increasing Subsequence\n public int lengthOfLIS(int[] nums) {\n int[] dp = new int[nums.length]; // Array to store the lengths of LIS\n int len = 0; // Variable to store the length of the LIS\n for (int num : nums) {\n int i = Arrays.binarySearch(dp, 0, len, num); // Binary search to find the position to insert the current number in the dp array\n if (i < 0) { // If the number is not found in the dp array\n i = -(i + 1); // Get the index to insert the number\n }\n dp[i] = num; // Insert the number at the correct position in the dp array\n if (i == len) { // If the number was inserted at the end of the dp array\n len++; // Increment the length of the LIS\n }\n }\n return len; // Return the length of the LIS\n }\n\n // Function to remove students from the class\n public int removeStudents(int[] H, int N) {\n int ans = N - lengthOfLIS(H); // Calculate the number of students to be removed by subtracting the length of the LIS from the total number of students\n return ans; // Return the answer\n }\n};",
"updated_at_timestamp": 1730481777,
"user_code": "//User function Template for Java\n\nclass Solution {\n public int removeStudents(int[] H, int N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1671443990,
"func_sign": [
"removeStudents(self, H, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N = int(input())\n H = list(map(int, input().split()))\n\n ob = Solution()\n print(ob.removeStudents(H, N))\n print(\"~\")\n",
"solution": "# Back-end function Template for python3\n\nclass Solution:\n\n def lengthOfLIS(self, nums):\n tails = [0] * len(nums)\n size = 0\n for x in nums:\n i, j = 0, size\n while i != j:\n m = (i + j) // 2\n if tails[m] < x:\n i = m + 1\n else:\n j = m\n tails[i] = x\n size = max(i + 1, size)\n return size\n\n def removeStudents(self, H, N):\n ans = N - self.lengthOfLIS(H)\n return ans\n",
"updated_at_timestamp": 1730481777,
"user_code": "#User function Template for python3\n\nclass Solution:\n def removeStudents(self, H, N):\n # code here"
}
|
eJytlM1OhEAMxzm4PkfDeWPofDHjk5iI8aAcvOAe2GQTo/Eh9HWN/yJsZKVE0OnQQJj+ptN2+nr2vjnPunH1scmy66f8odnt2/yScq4aj0mOLBnCV76lvD7s6ru2vr993Lf9Olc1L/j5vKWxcawahqmnEuaOAkUVYRUEF/IQUwIiAlZ2IK+CvAby4oyBWIiDeEiAlJBISSUGhWjgmumPx0xsifECPxGsRBYnh69MDruV5LEuUWAK2E6PZKF5382FRkZOrJvxjBkiXiw2/MoVBiUMUVFUKSqI8qKcKCvKiNL9S3Pb0A9ZzjmtiPDnkphAzmEmPSuGIx55UkorYd/DNUrtL2MXZ6D+/6mn4ZtuAEMHmI8Hq3dpini8z2t6y7jPddW+utetyG6XCOqb9aqEDPSbt4tPlqOzzg==
|
702,896
|
Type of array
|
You are given an array arr having unique elements. Your task is to return the type of array.Note: The array can be categorized into ascending,descending,descending rotated and ascending rotated followed by:
Examples:
Input:
arr[] = [2, 1, 5, 4, 3]
Output:
3
Explanation:
Descending rotated, rotate 2 times left.
Input:
arr[] = [3, 4, 5, 1, 2]
Output:
4
Explanation:
Ascending rotated, rotate 2 times right.
Constraints:
3 <= arr.size() <= 10**5
1 <= arr[i] <= 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int maxNtype(int arr[])"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n int res = obj.maxNtype(arr);\n\n System.out.println(res);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "// User function Template for Java\nclass Solution {\n int maxNtype(int arr[]) {\n int n = arr.length;\n int max = 0, index = 0, type = 0;\n // Find the maximum element and its index.\n for (int i = 0; i < n; i++) {\n if (arr[i] > max) {\n max = arr[i];\n index = i;\n }\n }\n // Determine the type based on the given conditions.\n if (arr[0] == max && arr[n - 2] > arr[n - 1]) {\n type = 2;\n } else if (arr[n - 1] == max && arr[1] > arr[0]) {\n type = 1;\n } else if (arr[(n + index - 1) % n] > arr[(n + index + 1) % n]) {\n type = 4;\n } else {\n type = 3;\n }\n return type;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n int maxNtype(int arr[]) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxNtype(self , arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n while t > 0:\n arr = list(map(int, input().split()))\n ob = Solution()\n res = ob.maxNtype(arr)\n print(res)\n print(\"~\")\n t -= 1\n",
"solution": "# User function Template for python3\nclass Solution:\n\n def maxNtype(self, arr):\n # code here.\n n = len(arr)\n max_value = 0\n index = 0\n\n # Find the maximum element and its index.\n for i in range(n):\n if arr[i] > max_value:\n max_value = arr[i]\n index = i\n\n # Determine the type based on the given conditions.\n if arr[0] == max_value and arr[n - 2] > arr[n - 1]:\n type_value = 2\n elif arr[n - 1] == max_value and arr[1] > arr[0]:\n type_value = 1\n elif arr[(n + index - 1) % n] > arr[(n + index + 1) % n]:\n type_value = 4\n else:\n type_value = 3\n\n return type_value\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def maxNtype(self , arr):\n #code here.\n \n \n"
}
|
eJytlE1OwzAQhVkgzvHkdUGZsWPHnASJIBaQBZvQRSpVQq04BNyXccJPgjppEsUbR3L86c1743m//HRXF+26u5aP+zfzUm93jbmFobL2CCgQQRkIDAuHvKzNBqbab6unpnp+fN013/+7sj7K4WGDISSXW1ZuU8JE4QV4FWIVCGXtQmxXtxUdVmWxxvopBf36RJ7ALMiBcpAHBVABiuAMTMhmF8452IMDuABHWME4sGhm4c2mnXag3UK3+Qkhaf4OvegwsyX+T1kc1iGakhOJ/OW1QJLcXsnrdLCw4xItau2rd5bGG2R13rOlL7dnAxezjBh/Equ9id+uVcfMlHam0fJXHDGcDnpThmeNmXGZKSW204fjaOYd4oyOh4+bLxoWsD4=
|
703,385
|
Transform the array
|
Given an array arr[] containing integers, zero is considered an invalid number, and the rest of the other numbers are valid. If the two nearest valid numbers are equal, then double the value of the first one and make the second number 0. At last, move all the valid numbers on the left.
Examples:
Input:
arr[] = [2, 4, 5, 0, 0, 5, 4, 8, 6, 0, 6, 8]
Output:
[2, 4, 10, 4, 8, 12, 8, 0, 0, 0, 0, 0]
Explanation:
After performing above given operation we get array as [2, 4, 10, 0, 0, 0, 4, 8, 12, 0, 0, 8], then shifting all zero's to the right, we get resultant array as - [2, 4, 10, 4, 8, 12, 8, 0, 0, 0, 0, 0]
Input:
arr[] = [0, 0]
Output:
[0, 0]
Explanation:
All elements in the array are invalid .
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public ArrayList<Integer> valid(int arr[])"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GfG {\n public static void main(String args[]) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n\n Solution ob = new Solution();\n ArrayList<Integer> res = ob.valid(arr);\n for (int i = 0; i < res.size(); i++) {\n System.out.print(res.get(i) + \" \");\n }\n System.out.println();\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GfG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public ArrayList<Integer> valid(int arr[]) {\n // code here.\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"valid(self,arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n ans = ob.valid(arr)\n for i in ans:\n print(i, end=\" \")\n print()\n print(\"~\")\n",
"solution": "class Solution:\n\n def swap(self, a, b):\n temp = a\n a = b\n b = temp\n return a, b\n\n def valid(self, arr):\n ans = []\n n = len(arr)\n i, j = 0, 0\n prev = 0\n c = 0\n\n # Iterating over the array\n while i < n:\n if arr[i] > 0:\n # If current element is equal to the previous element\n if arr[i] == prev:\n arr[i] += arr[i]\n prev = arr[i]\n\n # Swapping the current element with the element at index j\n arr[i], arr[j] = self.swap(arr[i], arr[j])\n arr[i] = 0\n\n # Incrementing the count of elements that are 0\n c += 1\n else:\n prev = arr[i]\n j = i\n else:\n # Incrementing the count of elements that are 0\n c += 1\n i += 1\n\n # Adding the non-zero elements to the resulting list\n for i in range(n):\n if arr[i] > 0:\n ans.append(arr[i])\n\n # Adding the 0 elements to the resulting list based on count\n ans.extend([0] * c)\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def valid(self,arr): \n # code here "
}
|
eJxrYJkaxM4ABhHeQEZ0tVJmXkFpiZKVgpJhTJ6Bko6CUmpFQWpySWpKfH5pCVTKQCEmry4mT6lWRwFVg6ECLi1AGVyaDBQMSddkiFOTET5NuO0CacNnG06f4dUItI9cGw0IOhavc4mAOA3HhAZYIE4vEwVxJi3iIOmW09p2AwODweSAAXIBuhPgSRndGaQFFwFHI1tBasrAHmy09wpRCkiKU5gDiQgkVEhccsbraNpkZ9wVAw4n41CPbrICuXUBPF0Qqhljp+gBAHxwxvw=
|
703,637
|
Previous number in one swap
|
Given a non-negative number N in the form of string. The task is to apply at most one swap operation on the number N so that the result is just a previous possible number.
Examples:
Input:
S = "12435"
Output:
12345
Explanation:
Although the number 12354
will be the largest smaller
number from 12435. But it is
not possible to make it using
only one swap. So swap
4 and 3 and get 12345.
Input:
S = " 12345"
Output:
-1
Explanation:
Digits are in increasing order.
So it is not possible to
make a smaller number from it.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static String previousNumber(String S)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0)\n {\n String S = read.readLine();\n\n Solution ob = new Solution();\n System.out.println(ob.previousNumber(S));\n }\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "//User function Template for Java\nclass Solution{\n static String previousNumber(String S){\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"previousNumber(ob,S)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n S = str(input())\n\n ob = Solution()\n print(ob.previousNumber(S))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def previousNumber(ob, S):\n index = -1\n S = list(S)\n n = len(S)\n # Traverse from right until we find\n # a digit which is greater than its\n # next digit. For example, in 34125,\n # our index is 4.\n for i in range(n - 2, -1, -1):\n if int(S[i]) > int(S[i + 1]):\n index = i\n break\n\n # We can also use binary search here as\n # digits after index are sorted in\n # increasing order.\n # Find the biggest digit in the right of\n # arr[index] which is smaller than arr[index]\n smallGreatDgt = -1\n for i in range(n - 1, index, -1):\n if (smallGreatDgt == -1 and int(S[i]) <\n int(S[index])):\n smallGreatDgt = i\n elif (index > -1 and int(S[i]) >=\n int(S[smallGreatDgt]) and\n int(S[i]) < int(S[index])):\n smallGreatDgt = i\n # If index is -1 i.e. digits are\n # in increasing order.\n if index == -1:\n return \"\".join([\"-1\"])\n else:\n\n # Swap both values\n S[index], S[smallGreatDgt] = S[smallGreatDgt], S[index]\n if S[0] == '0':\n return '-1'\n return \"\".join(S)\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def previousNumber (ob,S):\n # code here \n "
}
|
eJylVEEOgjAQ9OBDSM9otkuB4ktMxHhQDl6QAyQmRuMj9JXefIEFW01IBgQXSJp0dro7s+U6vT+nkyaWD7NYncQ+L6pSLDwh01ySC+F7IjsW2bbMdptDVVrMzIAuaS7OvtfK/MTgTKZAEYVRDDJrAKkaABhYqiAKdUwJYLAAihPEQO5BDHabGHURhHHCKtKIwQFIIwai98uIodk1H6zBmTfCg0AZfTVU0AJIIwVNVW8KxNB7tlv2lCA79BvVO9fOsLFGpul3DrCRAI99tdJ194VnU466jqMnYfhZwxLor98M/zot3B6X9W3+Asf/c78=
|
703,464
|
Reaching the heights
|
The teacher gives a mental ability question to Raju. The question is as follows:-
Examples:
Input:
arr[ ] = {2, 3, 4, 5}
Output:
5 2 4 3
Explanation:
Array can be arranged as {5,3,4,2} or
{4,3,5,2} or {4,2,5,3} but it will get
arranged as {5,2,4,3} because he always
prefer to move more number of floors up
and less number of floors down.
Input:
arr[ ] = {1, 1}
Output:
Not Possible
1≤N ≤10**5
1≤ arr[i]≤10**3
|
geeksforgeeks
|
Medium
|
{
"class_name": "Complete",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static ArrayList<Integer> reaching_height(int n, int arr[])"
],
"initial_code": "//Initial Template for Java\n\n//Initial Template for Java\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\nclass Array {\n \n // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t String line = br.readLine();\n\t\t String[] element = line.trim().split(\"\\\\s+\");\n\t\t int N = Integer.parseInt(element[0]);\n\t\t int arr [] = new int[N];\n\t\t line = br.readLine();\n\t\t String[] elements = line.trim().split(\"\\\\s+\");\n\t\t for(int i = 0;i<N;i++){\n\t arr[i] = Integer.parseInt(elements[i]); \n\t }\n\t\t \n\t\t \n\t\t Complete obj = new Complete();\n\t\t ArrayList<Integer> ans;\n\t\t ans = obj.reaching_height(N, arr);\n \t\n \tif(ans.size() == 1 && ans.get(0) == -1){\n \t System.out.println(\"Not Possible\");\n \t continue;\n \t}\n \t\n \tfor(int i: ans)\n \t System.out.print(i + \" \");\n \tSystem.out.println();\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}\n\n\n",
"script_name": "Array",
"solution": "None",
"updated_at_timestamp": 1730471046,
"user_code": "//User function Template for Java\nclass Complete{\n \n \n // Function for finding maximum and value pair\n public static ArrayList<Integer> reaching_height (int n, int arr[]) {\n //Complete the function\n }\n \n \n}\n"
}
|
{
"class_name": null,
"created_at_timestamp": 1615292571,
"func_sign": [
"reaching_height(n, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nfor _ in range(0, int(input())):\n n = int(input())\n arr = list(map(int, input().strip().split()))\n ans = reaching_height(n, arr)\n if len(ans) == 1 and ans[0] == -1:\n print(\"Not Possible\")\n else:\n print(*ans)\n print(\"~\")\n",
"solution": "def reaching_height(n, arr):\n # Function to find the heights reached by the person at different steps\n\n v = [] # Initialize an empty list to store the heights\n if (n == 1):\n # If only one step, return the height reached at that step and exit\n v.append(arr[0])\n return v\n arr.sort() # Sort the array in ascending order\n if (arr[0] == arr[n-1]):\n # If all steps have the same height, return -1 to indicate it is not possible to reach different heights\n v.append(-1)\n return v\n hi = n-1 # Initialize the index of highest step\n lo = 0 # Initialize the index of lowest step\n is_hi = 1 # Flag indicating whether to consider highest step or lowest step\n\n # Loop to iterate through the steps and add the corresponding height to the list\n while (lo <= hi):\n if (is_hi):\n v.append(arr[hi]) # Add the height at the highest step to the list\n hi -= 1 # Decrement the index of highest step\n else:\n v.append(arr[lo]) # Add the height at the lowest step to the list\n lo += 1 # Increment the index of lowest step\n is_hi ^= 1 # Toggle the flag to alternate between highest step and lowest step\n\n return v # Return the list of heights reached at different steps\n",
"updated_at_timestamp": 1730471046,
"user_code": "#User function Template for python3\n\ndef reaching_height (n, arr) : \n #Complete the function\n \n"
}
|
eJy1VNtKw0AQ7YPQ3xj2uchesm3WjxAfBVcENQ8F2RSagiCKH6H/69mlwbTNpHGJSXZbMmfnzJkz7efF93w+S9ftDF/u3sQ6bHaNuCKhfFASizQZKsjSklZUkiMlxYJE9bqpnprq+aHeNe0JSQpxDZQBtsAJ68OHD+J9QT2ZJcAlgIABbHBQTZAZAUsDN0NxXTd0U2+368eXikm98sFQ587PtIx9VVJCkXNI5UpWeFIepTto5zRrH3SqSdPRJ5PXpPjJYvLjvUUhWPmSYYuWZCB5v3OV/SLwMMmKOD2xNQdbfnGuZ86ZbJh/RDUwBsiCn8O9LdZ71Ba1HzRSGznwMzjXJMU5ddJl3rMUow56rJC/1tRrVsH/iSB2ZOyQaxPbFhs4ak61zmremSlo7VeZ/ie+dg76eBNX3sipiTn/kcr7LpmMbHIE3f3X5Q9aFOpA
|
705,822
|
Police and Thieves
|
Given an array of size n such that each element contains either a 'P' for policeman or a 'T' for thief. Find the maximum number of thieves that can be caught by the police.
Keep in mind the following conditions :
Examples:
Input:
N = 5, K = 1
arr[] = {P, T, T, P, T}
Output:
2
Explanation:
Maximum 2 thieves can be
caught. First policeman catches first thief
and second police man can catch either second
or third thief.
Input:
N = 6, K = 2
arr[] = {T, T, P, P, T, P}
Output:
3
Explanation:
Maximum 3 thieves can be caught.
Constraints:
1 ≤ n ≤10**5
1 ≤k ≤100
arr[i] = 'P' or 'T'
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int catchThieves(char arr[], int n, int k)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*; \n\n//Position this line where user code will be pasted.\nclass GFG{\n public static void main(String args[]) throws IOException {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n\n while(t > 0)\n {\n int n = sc.nextInt();\n int k = sc.nextInt();\n\t\t\tchar arr[] = new char[n];\n\t\t\tfor(int i=0; i<n; i++)\n\t\tarr[i] = sc.next().charAt(0);\n\n\t\t\tSolution ob = new Solution();\n System.out.println(ob.catchThieves(arr, n, k));\n t--;\n \nSystem.out.println(\"~\");\n}\n }\n} ",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static int catchThieves(char arr[], int n, int k) {\n int result = 0;\n ArrayList<Integer> thief = new ArrayList<Integer>();\n ArrayList<Integer> police = new ArrayList<Integer>();\n for (int i = 0; i < n; i++) {\n if (arr[i] == 'P') police.add(i);\n else if (arr[i] == 'T') thief.add(i);\n }\n // track lowest current indices of\n // thief: thi[l], police: pol[r]\n int l = 0, r = 0;\n while (l < thief.size() && r < police.size()) {\n // can be caught\n if (Math.abs(thief.get(l) - police.get(r)) <= k) {\n result++;\n l++;\n r++;\n } else if (thief.get(l) < police.get(r)) l++;\n else r++;\n }\n return result;\n }\n}\n",
"updated_at_timestamp": 1730272111,
"user_code": "//User function Template for Java\n\nclass Solution \n{ \n static int catchThieves(char arr[], int n, int k) \n\t{ \n // Code here\n\t} \n} \n\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"catchThieves(self, arr, n, k)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n line1 = list(map(int, input().strip().split()))\n n = line1[0]\n k = line1[1]\n arr = list(input().strip().split())\n obj = Solution()\n print(obj.catchThieves(arr, n, k))\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def catchThieves(self, arr, n, k):\n i = 0\n l = 0\n r = 0\n result = 0\n thief = []\n police = []\n\n while i < n:\n if arr[i] == 'P':\n police.append(i)\n elif arr[i] == 'T':\n thief.append(i)\n i += 1\n\n # track lowest current indices of\n # thief: thief[l], police: police[r]\n while l < len(thief) and r < len(police):\n # can be caught\n if (abs(thief[l] - police[r]) <= k):\n result += 1\n l += 1\n r += 1\n\n # increment the minimum index\n elif thief[l] < police[r]:\n l += 1\n else:\n r += 1\n\n return result\n",
"updated_at_timestamp": 1730272111,
"user_code": "#User function Template for python3\n\nclass Solution:\n def catchThieves(self, arr, n, k): \n # code here "
}
|
eJxrYJl6lI0BDCL2ARnR1UqZeQWlJUpWCkqGMXmGBgrGMXkhCgFAGKIAo4FYSUdBKbWiIDW5JDUlPr+0BKrFNCZPqVZHAc0QUwWjmDw0A+AYLIbDOHNsxhkZKJjC3AQzAM04BI3DYEMDrCabKhjCHAozEYuZaBiX4w0NsdlhbKBgggiMEBQfYPMHsUFliD3owR7CoQVrGIB14Ao27DoMwFoUMCDphgQoYEASDTGFhC0aJiW1UhhBeGLIhAQ34w4+rKZgT7l0SbpEBA35iReeIElMk2RGYgBhl+KKRETqJTv5kpvyyE16qPbR3UJk+6iTt2Kn6AEA0YDbYA==
|
703,668
|
Maximum prefix sum for a given range
|
You are given an array arr of integers and a list of queries. Each query consists of two indices, leftIndex and rightIndex, defining a range in the array. For each query, calculate the maximum prefix sum within the given range.
Examples:
Input:
arr = [-1, 2, 3, -5], leftIndex = [0, 1], rightIndex = [3, 3]
Output:
[4, 5]
Explanation:
For the range [0, 3], the prefix sums are [-1, 1, 4, -1]. The maximum is 4. For the range [1, 3], the prefix sums are [2, 5, 0]. The maximum is 5.
Input:
arr = [1, -2, 3, 4, -5], leftIndex = [0, 2, 1], rightIndex = [4, 3, 3]
Output:
[6, 7, 5]
Explanation:
For the range [0, 4], the prefix sums are [1, -1, 2, 6, 1]. The maximum is 6. For the range [2, 3], the prefix sums are [3, 7]. The maximum is 7. For the range [1, 3], the prefix sums are [-2, 1, 5]. The maximum is 5.
Constraints:
1 ≤ arr.size() ≤ 10^6
-10^4 ≤ arr[i] ≤ 10^4
1 ≤ queries ≤ 10^4
0 ≤ leftIndex[i] ≤ rightIndex[i] < arr.size()
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617565437,
"func_sign": [
"public List<Integer> maxPrefixes(List<Integer> arr, List<Integer> leftIndex,\n List<Integer> rightIndex)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim());\n\n while (t-- > 0) {\n // Read array\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n List<Integer> arr = new ArrayList<>();\n for (String token : tokens) {\n arr.add(Integer.parseInt(token));\n }\n\n // Read left index range\n line = br.readLine();\n tokens = line.split(\" \");\n List<Integer> leftIndex = new ArrayList<>();\n for (String token : tokens) {\n leftIndex.add(Integer.parseInt(token));\n }\n\n // Read right index range\n line = br.readLine();\n tokens = line.split(\" \");\n List<Integer> rightIndex = new ArrayList<>();\n for (String token : tokens) {\n rightIndex.add(Integer.parseInt(token));\n }\n\n Solution obj = new Solution();\n List<Integer> result = obj.maxPrefixes(arr, leftIndex, rightIndex);\n for (int i : result) {\n System.out.print(i + \" \");\n }\n System.out.println();\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n public List<Integer> maxPrefixes(\n List<Integer> arr, List<Integer> leftIndex, List<Integer> rightIndex) {\n int q = leftIndex.size();\n List<Integer> result = new ArrayList<>();\n // Iterate through each query\n for (int i = 0; i < q; i++) {\n int maxSum = arr.get(leftIndex.get(i));\n int currentSum = arr.get(leftIndex.get(i));\n // Calculate prefix sums and track maximum\n for (int j = leftIndex.get(i) + 1; j <= rightIndex.get(i); j++) {\n currentSum += arr.get(j);\n maxSum = Math.max(maxSum, currentSum);\n }\n\n result.add(maxSum);\n }\n return result;\n }\n}\n",
"updated_at_timestamp": 1730472387,
"user_code": "class Solution {\n public List<Integer> maxPrefixes(List<Integer> arr, List<Integer> leftIndex,\n List<Integer> rightIndex) {\n // code here.\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617565437,
"func_sign": [
"maxPrefixes(self, arr, leftIndex, rightIndex)"
],
"initial_code": "def main():\n import sys\n input = sys.stdin.read\n data = input().splitlines()\n t = int(data[0])\n index = 1\n\n solution = Solution()\n\n while t > 0:\n t -= 1\n arr = list(map(int, data[index].split()))\n index += 1\n leftIndex = list(map(int, data[index].split()))\n index += 1\n rightIndex = list(map(int, data[index].split()))\n index += 1\n\n result = solution.maxPrefixes(arr, leftIndex, rightIndex)\n print(\" \".join(map(str, result)))\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n\n def maxPrefixes(self, arr, leftIndex, rightIndex):\n # Initialize the result list to store maximum prefix sums for each query\n result = []\n\n # Iterate through each query using indices from leftIndex and rightIndex lists\n for i in range(len(leftIndex)):\n # Start with the first element of the subarray as initial values for maxSum and currentSum\n maxSum = currentSum = arr[leftIndex[i]]\n\n # Calculate prefix sums and track maximum within the range specified by the query\n for j in range(leftIndex[i] + 1, rightIndex[i] + 1):\n currentSum += arr[j]\n maxSum = max(maxSum, currentSum)\n\n # Append the maximum prefix sum found for this query to the result list\n result.append(maxSum)\n\n return result\n",
"updated_at_timestamp": 1730472387,
"user_code": "class Solution:\n def maxPrefixes(self, arr, leftIndex, rightIndex):\n # code here."
}
|
eJyVUstuwyAQ7CH9jxXnUBlsjNMv6C3XSiXqofWhF5KDI1WKUvUj2v/N7prg5rERBcRDDLPDzn7Pfpf3d9yen3DzslMfcbMd1CMoE6I2FeCYlhArsIA3DdRQqzmo/nPTvw39++t6O6SHFRA8xK8Q1X4Op5R0yZ22DRE1Mo3AYSpsJIeWvwfiNGARgSoleeOD9FCIoA0Ig2WDC7EDD60QYgJfZXeQ+khmx3QagcwmqJAKTilP4n9lN3RyVx/t5ezJ1macxIaZtexHTXPDW0dzm+xJBqUECGH48cRgZaNOygnPsu23ywm0zTE1B2XVmmSD521H8+Ki2NA5rAdosRy6EBdw1gU1Ln+uzXF9zl53LGyOd022Nl5gvgBKdXEORDWllJ6KpAxcykkJKRf6D1ZX/KtkauG/biFXPw8HcIFzqQ==
|
704,431
|
Count ways to N'th Stair(Order does not matter)
|
There are n stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).Note: Order does not matter means for n = 4:- {1 2 1},{2 1 1},{1 1 2} are considered same.
Examples:
Input:
n =
4
Output:
3
Explanation:
Three ways to reach at 4th stair. They are {1, 1, 1, 1}, {1, 1, 2}, {2, 2}.
Input:
n = 5
Output:
3
Explanation:
Three ways to reach at 5th stair. They are {1, 1, 1, 1, 1}, {1, 1, 2, 1} and {1, 2, 2}.
Constraints:
1 ≤ n ≤ 10**4
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1619084816,
"func_sign": [
"public int nthStair(int n)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n int n = Integer.parseInt(br.readLine().trim());\n Solution ob = new Solution();\n long ans = ob.nthStair(n);\n System.out.println(ans);\n\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1731579300,
"user_code": "class Solution {\n public int nthStair(int n) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619084816,
"func_sign": [
"nthStair(self,n)"
],
"initial_code": "# Initial Template for Python 3\n\nimport sys\nsys.setrecursionlimit(10**6)\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n = int(input())\n ob = Solution()\n ans = ob.nthStair(n)\n print(ans)\n",
"solution": "# Backend complete function template for Python 3\n\nclass Solution:\n # Function to find the number of ways to reach the nth stair.\n def nthStair(self, n):\n # Creating a list of size n+1 and initializing it with -1.\n dp = [-1] * (n + 1)\n\n # Recursive function to solve the problem.\n def solve(n):\n # If n is negative, then there are 0 ways to reach that stair.\n if n < 0:\n return 0\n # If n is 0 or 1, then there is only 1 way to reach that stair.\n if n <= 1:\n return 1\n # If the subproblem has already been solved, return the stored value.\n if dp[n] != -1:\n return dp[n]\n # Otherwise, calculate the number of ways to reach the current stair\n # by adding the number of ways to reach the previous 2 stairs.\n dp[n] = solve(n - 1) + solve(n - 2)\n return dp[n]\n\n # Calling the recursive function to find the number of ways to reach the nth stair.\n return solve(n)\n",
"updated_at_timestamp": 1727947200,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef nthStair(self,n):\n\t\t# Code here"
}
|
eJylmc2OpMURRVnwFKxGvUYoI/Iv0k9iyWMhgWfBpmExSEjIkh/Cfl+fk43FYroaMe4ZekpVlflF3rhx40byry//88NXX9yfv37Hi7/9+vTD808/f3z6y7uneP8crb1/fvr63dOHX3768P3HD//49sefP/728dw9xq4xWvSK3WpEY8nTP79+98kmj3fZrffW194RI7NiVkb1mXMU7/FqnL1bVOQ61VeftXvukauN02arHXPMzuqKs07vcx8+zXH4M1euiN27e802xskRe81zolVFLfbLxfqW2dfY0VaLbLP3PSIjd6/F6hP8nIp+OkfOOU/ttddp7cRh6Zj87dlH6/N1BOZbCKzcq7es1kbVmQC5mgB0guzjrBptToCeWbsR0xpzj86DgWqMUSc3geVcFbE80Bh7VonJzF1t5Ww9z6lByADDv2DF49aoyT/VGylsrBGBzga151mAFzWbz2sAmkBxTvZz+EKIcrQJ1PxTxHzMVx9ZSezRGx/sGMFOIArmRciNXAHwSoJZszoHONH3Zi/CAuw5OmDsvRKEi69NTt6auWa3vgRkdR7GHyIeGbOvAwGKVCaJysEx4IkciEwSJZRkiaiaMZxcexIEjCP9E3bBPkAUkZjstEgAYU/I1JpnO0eCk4zTeWaWH7e9iJNTk5YjjALNqRccmjMPJ4ZwEogj1VlrUhkQiQ/riHmPfSycPKsDG0dnQXN/8Obkg6eBUws4R+w+Z3C2TqRCQBZ23gjgMl8CjxiiHh2s+UVhnCoj43XCHZ7dQHwX2SN+KgfqkEIqbHEkKso9YQI/xHCCLFSjMOB8g2zmcRWnXlK/rc3unJMyZNWw+kGbD3wolUeE1gzZOCBIPYV8ZRvAWaSUDJSUspKo+KL6JjQAfRkK9TgaXKFOa7sxuIlKWwR7jmgc2RnzJM+vgFVtkWWyNOUtEcNS1IDNBjQh7Ww6FnGOPNA0RcIKIQ8whxxB3UOFTZKdJmXyLZm/ytTxddjExggSb4SplZtsPklWdY5DlKjFmRxj9Ch1bfgXzBZ1tEkhm5hpAAdDQKaSVllaMHhEvycYfJTrNRU5/DxUkd6tezbaPp1UcmSQWCF9rG6YTnU3zzAWyaT+SYqwIGXUi+9UiNZyZackJlI35TVQoW4oH+VN1XgkeQj+XfZaBSDDMfkA9NAT8Bq8mBcKKI7IDqr7KJ7I9yFla0E1ZImTF/liOZlH30IWFgJG4QOIoC6wQVYC5Mz46BYWgO2ZfHvK90EU9An2TKuweKynM9EIlKVNeRIwR4B0SOa6L4Bm9YsRCCGwKC5SHi4ALYqSfPE9WgtFYRjWNPmhMiQbcMNyME0ZY4sivXAT3py+GuRENJt9wZogNjoPAIEtiT7uQBWr/mzb0T1EgUhRJ6pVfZioCGy2DdDhqM1OqSfFQ2RkkX5BVbFzlp2S83GOfbV106jgJjEogHGFGfrBcLAGLGIkabd3scnhmSiJ1CMRbGuHnHZ0tAssES9EmLa4FaiLKMcIuUaM3a7AAwGDf6lV2WRvQLwkQUl3hDPJKSAi4RLEAiiKjGSuhHZ52369xDr9FhIDzyxjeIJm8XDVkIcuHQDSRuUCnFKzVUnajn2OSp1iCG+nAHCiXre6bOglLSH16Og/LIFCwEX/Sc4VUh0GpVzmXOxPmaT6yO4o1cGjIFVTHbDvHTsQXgRuEsMNN8SNR1AA6SPRZDXNjQO0U30hjxm25UvaUUo8JxodRIBHRDjU5Gv0hsxbp+gtK6QsSgwpMDg8NSzyeW2MddJFA3KZW3g23ZosSgqyDhnAzDpEh23X9Dibs+SF+ggxX6LsKblFMi1G7AVk4Q25y1nY67hOt4DIsZAmTmli4W7RTyWfqJc1jwzzLiSzzZO0cWXaVgbbTcbA9TQzQHMTDYhOC8ANEU+4vqMOaEoZJtnGRKTdW82Zt83oWWivREFSwjqF9GxOyFARJhAi6ot4EQTiDN1EAsVous7paWE0+CrnEhTZp6dyaFJMowXfTWSzLC9KHEOGqOkUKClqDlCt62uHBDqv5CMgsB9M4Qg2h8r2Q3gPbS0t2vTUC2FQ7Pr0cMop9X7UIim3L9Eaw9CpBw7E6ezAPFERonKxvSzQeZJLCx91gxf4loQY2yjRA7yLXuZYUtqhNGq0jBc2uCoVwF8wR07zfToEosI7vIDxJNPlbSvyQ9NpWnXdXcoi0Bqb2+pDCaAKoA81jGDZDvcNRMuBoLGy2W2O2YJ4BEtKEGN4g7XiYcfQoBFVZKPHmamkCBfFdK4lYVGsec9HpYZUwQqVSt90CmxMtVqTl82w1x6R9hKb3zjaO1CEKGRKjhsTDoeTpi2U3hSqwNTp8UvMKTQPihRYnaG3pPlrak0Wuk2jADRWkgrgBUg2JL+q2HUeBM+K5qFoXRXXcOrw0Hy+q2ITKtTbKtJ0LFj6TtJnUeBPiCVvNaxrA7VyaiXkTe01Ao752jwsHF8oKnrstu/DTfJAVmhTj0a0NyY9oC5nHziLLiqS1+wv5Q/c4AefdNMP3OOqC+JNUBYYeZSm9CxnChTmNhpVOPTPmi/UzzlNaYTEWKvbXNDCbsOmnaNpKiK+LuxBCjQPodqPpmSpEqEVb5oPRZh9p17KmWFARtmFdEKlbXMT7m1ZaDPgGq8p+3AsYRTpmnfI2/VDoUEdThtsjFG6c5Qk4eRaSLty2a2IgqqDrjQTVgGJ6eehcOtoyB0outCwJt3bgVOTm9ekDtkF1Ft1QCoY6BwPmg+wHOnEL+KusJBlehIizXiC2ON/KQELji6t3bMFc1oLujsA5jW/eBjeOBY+AgZgMAdgUEbOC9LILO0HiCgRElNOU7xB2esfwdl2TVAq3Z1n1C/1TVlK2XXVqTFldwuXIryTA5Lh2FY64Vu1UNj2QTOYjjmsYjW2XN+ir296IMd+dMGBXNMKKuihFgPcGSTqeibTNB3DeQd9mFpfAkG+KV2GOlt1+TBiwHuRPPwPKB+VgPTqzIHb5TwJWSinX7iSmiuFtxS6c00lzDZ8nbvK0g3GA+toul6nv9hX+s6ya9zmq2ECunZtn0LYZR00AGTkEjJrA4mLzBKkFmaqV3euYD3fWTaDa/MYkm+HI77hYOuUTcXlvTVhrGZ8NWwf6RhK1UtKa1INvA6W7tKcwnwM/EpnSaSnq/WD5sQG+46InHiImFRVLx0FUSAnZ8mELbFJlcNT17grBXgD7JxDoNMIg7SeDpjhN0BrHIYHwHpikFjPfxCMwvJqYM57GaRnOg7gx7sCsqlPP5ow7ReKGM7U5WAGh6C9P1rEcWcTp/RhoHmvQPhFAOHs75zM+TG82yZ4O/+098I9pVmAdZVsITZO1c57Nh6IuK1pZ1zvDFAkKpdThXvYHNiNXNJkQdaZB00Yt2Eif4w9u7nHvEXubMyybrKa+kJ+rSiKyWEXWqpCDqxQ34uBdJrUZZWf0dCPdc2Srn9R2PJefh1rmByUmqx7GDJFr1hO2Y7f17h2xWxykumQO7z6ctyzUYTTOlnSXkFqy51PXoY+bCY6Nu0uNEEIGrrh48wVTrDidfkC9UCcx5EiKwy8bA8OCLy7neqwOXoUItOyertAQb+UJrQFPviXd4JHCmyKdN3tYAbXMLOEzy+0kzSquHFd1rFzOLEM7bJ88W+agO0b0LlDMo3SnWUdfqeTGmCq6P3eDt47kHXv+phaHDeUcALWHFgbDoZIkK3Ie6lxZ0G7AMdkP4TVCfw4k2jjOQs+nmR6g6OPxmFBOl1Q3NkCsMN7TrhPRMqJF2jMet55cDx/lgo/vG1hf92NQ966FyoyC9+qjbTDHpXB68p12ZjXgqrazUd4pYHqOfbqGkdoMlrdMqP80/kRPSaP6qMNAzub9mkUD8sMu5zbyoEQieVLJIcqnBqo169/H/qKV7+eD7+er329P74Red3oPPx+nQdXt48D8i6Y2kfrbQRkrbTezAh3/ERktjcBXuPl9XxUJLrqbWU5woHtna28Z+aPphUMvRRDq7Ekjhq0jtdvg+LlNO//F+Ozv94+IXLwaKc/ueJtXF6nAf99GvDzy24vV1vxGYF/CsHz52LwYKvnz9mLnd7Iz58P77elnwP670H8AWv+LwDzhvg+Hq3yf/C47u///ua/SCno3w==
|
702,797
|
Search in a matrix
|
Given a matrix mat[][] of size NxM, where every row and column is sorted in increasing order, and a number X is given. The task is to find whether element X is present in the matrix or not.
Examples:
Input:
N = 3, M = 3
mat[][] = 3 30 38
44 52 54
57 60 69
X = 62
Output:
0
Explanation:
62 is not present in the
matrix, so output is 0
Input:
N = 1, M = 6
mat[][]
= 18 21 27 38 55 67
X = 55
Output:
1
Explanation:
55 is present in the
matrix at 5th cell.
Constraints
:
1 <= N, M <= 1005
1 <= mat[][] <= 10000000
1<= X <= 10000000
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1730658707,
"func_sign": [
"public static boolean matSearch(int mat[][], int x)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass gfg {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n\n while (t-- > 0) {\n int n = sc.nextInt();\n int m = sc.nextInt();\n\n int mat[][] = new int[n][m];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) mat[i][j] = sc.nextInt();\n }\n\n int x = sc.nextInt();\n\n if (new Solution().matSearch(mat, x))\n System.out.println(\"true\");\n else\n System.out.println(\"false\");\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "gfg",
"solution": "None",
"updated_at_timestamp": 1731402194,
"user_code": "class Solution {\n public static boolean matSearch(int mat[][], int x) {\n // your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1730658707,
"func_sign": [
"matSearch(self,mat, x)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n import sys\n input = sys.stdin.read\n data = input().split()\n\n t = int(data[0])\n index = 1\n for _ in range(t):\n r = int(data[index])\n c = int(data[index + 1])\n index += 2\n matrix = []\n for i in range(r):\n row = list(map(int, data[index:index + c]))\n matrix.append(row)\n index += c\n x = int(data[index])\n index += 1\n ob = Solution()\n if ob.matSearch(matrix, x):\n print(\"true\")\n else:\n print(\"false\")\n print(\"~\")\n",
"solution": "#Back-end complete function Template for Python 3\n\n\nclass Solution:\n\n #Function to check if element x is present in the matrix.\n def matSearch(self, mat, x):\n n = len(mat)\n m = len(mat[0])\n i = 0\n j = m - 1\n\n #iterating through the matrix\n while i < n and j >= 0:\n\n #if the current element is equal to x, return true\n if mat[i][j] == x:\n return True\n\n #if the current element is greater than x, move left\n if mat[i][j] > x:\n j -= 1\n\n #if the current element is less than x, move down\n else:\n i += 1\n\n #if x is not found in the matrix, return false\n return False\n",
"updated_at_timestamp": 1730899566,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef matSearch(self,mat, x):\n\t\t# Complete this function"
}
|
eJztltGKE0EQRX0QfNJvOMzzItvd1dXVfsmCERGNIMi4aAKCuOxHrP9r9STu5sEZzSQbBW1C0qRmbt97a6pqrh9+e/L4wbAuHvnm+ZfuXX+5XnXP6MKiD7Qv/3RndMvPl8vXq+Wblx/Wq+0lq4/r5aK/WvTd1zN+duv5Zt3t9geKxAHtFipSN+sQ1ERqqLH9CBld9AXDMesxwcIYtbev3n+atO5O4wyETN4SQtpWGfi4if63w0dCIgihXaaEQjBCJTZ7/T73PBGF2OJpf0MEadodj3SOtFOzg5Ey4pCxECupIObmOUs3sJLb4TPc93MGXT/kMq6WabFEpXGzgZ6HU2BLTxr3pI10ssa2iZKARMRPdcEuTZGmCdmIyYEcyYnsrDwlSi5kI1fUwxrQiCZUUGetaEENrRQPl0CJlEQRSqa4qkIxSsU8bAGLWMIEy5hirtqwSvVwDVQvlEQVaqYqtVDdlWZLi/83+jRGhzndaegAEy1q21qFwZtD+uAeOfUE/cVZ3fSVg3NbjpTcyf7+r9ZROnkh/frlQWalcHTAnmrCHkygHmXGMzHkk46Mee59zo+3qp0n4c/WkNmx+pam3c51n31rxlSKM+fSjDfYcpvrnST/dq3tCn9x8/Q764YuDw==
|
703,912
|
Edit Distance
|
Given two strings str1 and str2. Return the minimum number of operations required to convert str1 to str2.The possible operations are permitted:
Examples:
Input:
str1 = "geek", srt2 = "gesek"
Output:
1
Explanation:
One operation is required, inserting 's' between two 'e'.
Input:
str1 = "gfg", str2 = "gfg"
Output:
0
Explanation:
Both strings are same.
Constraints:
1 ≤ str1.length(), str2.length() ≤ 100
Boththe strings are inlowercase.
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1731309684,
"func_sign": [
"public int editDistance(String s1, String s2)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n String s1 = br.readLine();\n String s2 = br.readLine();\n\n Solution ob = new Solution();\n int ans = ob.editDistance(s1, s2);\n System.out.println(ans);\n }\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1731309684,
"user_code": "class Solution {\n public int editDistance(String s1, String s2) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731309684,
"func_sign": [
"editDistance(self, s1, s2)"
],
"initial_code": "if __name__ == '__main__':\n T = int(input())\n for i in range(T):\n s1 = input()\n s2 = input()\n ob = Solution()\n ans = ob.editDistance(s1, s2)\n print(ans)\n",
"solution": "class Solution:\n # Function to calculate the minimum edit distance between two strings\n def fun(self, s, t, pos1, pos2):\n # If one of the positions is at the beginning, return the other position\n if pos1 == 0:\n return pos2\n if pos2 == 0:\n return pos1\n # If the answer is already calculated, return it\n if self.dp[pos1][pos2] != -1:\n return self.dp[pos1][pos2]\n # If the characters at the current positions are the same, recursively call the function on the previous positions\n if s[pos1 - 1] == t[pos2 - 1]:\n self.dp[pos1][pos2] = self.fun(s, t, pos1 - 1, pos2 - 1)\n return self.dp[pos1][pos2]\n # If the characters are different, calculate the minimum of three cases (insertion, deletion, substitution)\n self.dp[pos1][pos2] = min(1 + self.fun(s, t, pos1, pos2 - 1),\n 1 + self.fun(s, t, pos1 - 1, pos2),\n 1 + self.fun(s, t, pos1 - 1, pos2 - 1))\n # Return the minimum edit distance\n return self.dp[pos1][pos2]\n\n # Function to calculate and return the edit distance between two strings\n def editDistance(self, s, t):\n # Create a memoization table to store already calculated values\n self.dp = [[-1 for i in range(len(t) + 1)] for i in range(len(s) + 1)]\n # Call the recursive function to calculate the edit distance\n return self.fun(s, t, len(s), len(t))\n",
"updated_at_timestamp": 1731309684,
"user_code": "class Solution:\n\tdef editDistance(self, s1, s2):\n\t\t# Code here"
}
|
eJztVs1yEzEM5sCVd+jk3GFIQ/94EmYww2htJevprmy0dtuUYYaHgFfgxjsie1OaNHG6pAF6IJNZSU5Wtj59kvzl+bcfL57lz9vvorz7NLLkYxi9ORhNFF3YEJAUdSItzRRNG7hSJA9ZnMU2PWh0eDDCa486oPngYrh7/UjRWNHo8+HBqltL4jVYJ07wGnXs1RYVzV1UFBhFDbWIgu9jRZNNvmVDqLTBqRz1WpR51uBG0Q0UXB3lY97zI549NJYMu3QqbB0bsg34gpPxqzUXr2VfghmDgCQSssJAxuWFXoL3jfivFlJb1tm2ei5K+cTj/J2sbSq4dLHq8GNE0rhkBAtNwoZBg0lCDGBzCXyhKJKu5XyyDdsuWA1NM1cb12rrvfMuQBs7iaa25DSy69K/nXYNBFxSu0IAAs1pRv28kMPEDyZItJAs3EDPj9XVbrEqW7nIveRSego8bBzNsAubIUsG4yVylxiQpWwDja+hwl+IkLu3VDhCH/B6xgQLkwCWQrJdjWbFhCqxQRa0aytXxR5fxhXTI3uUP2mxuedQbKfIi3ACg53VYer4ShKeuKYvklbOTaqsxLF1Tssv4lWo6TwaC3cW9GaoHbs4qxMwUr63amu7SEYADEL73EZWzK1J24jYwMIqVvFuFXeev3uDZEgcqhjCA61jZ7xPN0V4OwaGQr/WhuixfeiJNbbHvb0lb7sM2pPyoC3N77/fddhAM+zSMMk82z7Yg9mx7uqlXhQ2FceAG8Px8FvN/O5aw0PuNSc59gfvNXsNf59hDg3ycXx1aP7Q8N4P1/G3yD4+3pZu9b/9PpX2+88bz9liPL//+vIngV5Fuw==
|
705,889
|
Recursively remove all adjacent duplicates
|
Given a string s, remove all its adjacent duplicate characters recursively.Note: For some test cases, the resultant string would be an empty string. In that case, the function should return the empty string only.
Examples:
Input:
S = "geeksforgeek"
Output:
"gksforgk"
Explanation:
g(ee)ksforg(ee)k -> gksforgk
Input:
S = "abccbccba"
Output:
""
Explanation:
ab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->""(empty string)
Constraints:
1<=|S|<=10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"String rremove(String s)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main (String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases\n while(t-->0){\n String S = br.readLine();\n Solution ob = new Solution();\n String ans = ob.rremove(S).trim();\n System.out.println(ans);\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // This function recursively removes adjacent duplicate characters from the string\n // `s`.\n public String removeUtil(String s) {\n int len = s.length(); // Get the length of the input string.\n int n = len; // Store the original length for reference.\n StringBuilder sb =\n new StringBuilder(); // StringBuilder to construct the modified string.\n\n // Traverse the string character by character.\n for (int i = 0; i < n; i++) {\n // Check if the current character and the next character are the same.\n if (i < n - 1 && s.charAt(i) == s.charAt(i + 1)) {\n // Skip all consecutive duplicate characters.\n while (i < n - 1 && s.charAt(i) == s.charAt(i + 1)) {\n i++; // Move to the last duplicate character in the sequence.\n }\n } else {\n // If no duplicates are found, add the current character to the\n // StringBuilder.\n sb.append(s.charAt(i));\n }\n }\n\n // Convert the StringBuilder back to a string.\n String result = sb.toString();\n\n // If the length of the resultant string has changed (duplicates were removed),\n // recursively call the function to check for further adjacent duplicates.\n if (result.length() != len) {\n return removeUtil(result);\n }\n\n // Return the final string with no adjacent duplicates.\n return result;\n }\n}",
"updated_at_timestamp": 1730272499,
"user_code": "//User function Template for Java\n\nclass Solution{\n String rremove(String s) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"rremove(self, S)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n S = input()\n ob = Solution()\n print(ob.rremove(S))\n print(\"~\")\n",
"solution": "class Solution:\n\n # Function to recursively remove consecutive duplicate characters from a string\n def rremove(self, S):\n new = [] # Initialize a new empty list to store characters without consecutive duplicates\n i = 0 # Initialize a variable to keep track of the current index\n n = len(S) # Get the length of the string\n\n # Iterate through the string\n while i < len(S):\n flag = 0 # Initialize a flag variable to check if there are consecutive duplicates\n\n # Find consecutive duplicate characters\n while i < n-1 and S[i] == S[i+1]:\n flag = 1 # Set the flag to indicate that there are consecutive duplicates\n i += 1 # Move to the next index\n\n # If there are no consecutive duplicates, add the character to the new list\n if flag == 0:\n new.append(S[i])\n\n i += 1 # Move to the next index\n\n # If the length of the new list is less than the length of the original string,\n # recursively remove consecutive duplicates from the new list\n if len(new) < n:\n return self.rremove(''.join(new))\n\n # Convert the new list into a string and return it\n return ''.join(new)\n",
"updated_at_timestamp": 1730272499,
"user_code": "#User function Template for python3\n\nclass Solution:\n def rremove (self, S):\n\t\t#code here"
}
|
eJytVEsOgjAQdaH3IF0TE7bewJ1LE2uM/UEBy8eioNF4CL2vrbJCasLorNpM3pt5b6a9jR+LyegVy7k5rM5IqrzSaOahAKstVsj3EK9zTjVnm6zSbdJkriZ58b0Owg1xIQgdXoUQQGuEMs4oBGnqUcoY50KEYRRJOVTkycTWRGPDXga79NFCHA/nsCyWxzJZLssmBGBijIswknGS7lSWF+VeV4djbYQ19fFQ6X1Z5JnapUkso1AAPW+nhTFkXg6hWAAs6zbzu+sg03sUBeT94CAjdKw14C06ze7f+7/pbn8bUwdkgN3JQEH+uC8Q1ULW9+kT+XLZkQ==
|
707,516
|
Course Schedule
|
There are a total of n tasks you have to pick, labelled from 0 to n-1. Some tasks may have prerequisite tasks, for example to pick task 0 you have to first finish tasks 1, which is expressed as a pair: [0, 1]Given the total number of n tasks and a list of prerequisite pairs of size m. Find a ordering of tasks you should pick to finish all tasks.Note: There may be multiple correct orders, you just need to return any one of them. If it is impossible to finish all tasks, return an empty array. Driver code will print"No Ordering Possible", on returning an empty array.Returning any correct order will give the output as 1, whereas any invalid order will give the output 0.
Examples:
Input:
n = 2, m = 1
prerequisites = {{1, 0}}
Output:
1
Explanation:
The output 1 denotes that the order is valid. So, if you have, implemented your function correctly, then output would be 1 for all test cases.
One possible order is [0, 1].
Input:
n = 4, m = 4
prerequisites = {{1, 0},
{2, 0},
{3, 1},
{3, 2}}
Output:
1
Explanation:
There are a total of 4 tasks to pick. To pick task 3 you should have finished both tasks 1 and 2. Both tasks 1 and 2 should be pick after you finished task 0. So one correct task order is [0, 1, 2, 3]. Another correct ordering is [0, 2, 1, 3]. Returning any of these order will result in an output of 1.
Your Task:
The task is to complete the function
findOrder
() which takes two integers n, and m and a list of lists of size m*2 denoting the prerequisite pairs as input and returns any correct order to finish all the tasks. Return an empty array if it's impossible to finish all tasks.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1621263926,
"func_sign": [
"static int[] findOrder(int n, int m, ArrayList<ArrayList<Integer>> prerequisites)"
],
"initial_code": "//Initial template for JAVA\n\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass Main {\n public static void main(String[] args) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n\n while (t-- > 0) {\n ArrayList<ArrayList<Integer>> list = new ArrayList<>();\n String st[] = read.readLine().trim().split(\"\\\\s+\");\n int n = Integer.parseInt(st[0]);\n int m = Integer.parseInt(st[1]);\n\n for (int i = 0; i < n; i++)\n list.add(i, new ArrayList<Integer>());\n\n ArrayList<ArrayList<Integer>> prerequisites = new ArrayList<>();\n for (int i = 1; i <= m; i++) {\n String s[] = read.readLine().trim().split(\"\\\\s+\");\n int u = Integer.parseInt(s[0]);\n int v = Integer.parseInt(s[1]);\n list.get(v).add(u);\n ArrayList<Integer> pair = new ArrayList<>();\n pair.add(u);\n pair.add(v);\n prerequisites.add(pair);\n }\n\n int[] res = new Solution().findOrder(n, m, prerequisites);\n \n if(res.length==0)\n System.out.println(\"No Ordering Possible\");\n else\n {\n if (check(list, n, res) == true)\n System.out.println(\"1\");\n else\n System.out.println(\"0\");\n }\n \nSystem.out.println(\"~\");\n}\n }\n static boolean check(ArrayList<ArrayList<Integer>> list, int V, int[] res) {\n int[] map = new int[V];\n for (int i = 0; i < V; i++) {\n map[res[i]] = i;\n }\n for (int i = 0; i < V; i++) {\n for (int v : list.get(i)) {\n if (map[i] > map[v]) return false;\n }\n }\n return true;\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730267796,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n static int[] findOrder(int n, int m, ArrayList<ArrayList<Integer>> prerequisites) \n {\n // add your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1621263926,
"func_sign": [
"findOrder(self, n, m, prerequisites)"
],
"initial_code": "# Driver Program\n\nimport sys\nsys.setrecursionlimit(10**6)\n\n\ndef check(graph, N, res):\n map = [0]*N\n for i in range(N):\n map[res[i]] = i\n for i in range(N):\n for v in graph[i]:\n if map[i] > map[v]:\n return False\n return True\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n, m = list(map(int, input().strip().split()))\n adj = [[] for i in range(n)]\n prerequisites = []\n\n for i in range(m):\n u, v = map(int, input().split())\n adj[v].append(u)\n prerequisites.append([u, v])\n\n ob = Solution()\n\n res = ob.findOrder(n, m, prerequisites)\n\n if not len(res):\n print(\"No Ordering Possible\")\n else:\n if check(adj, n, res):\n print(1)\n else:\n print(0)\n print(\"~\")\n",
"solution": "# User function Template for python3\n\nfrom collections import defaultdict\n\n\nclass Solution:\n WHITE = 1\n GRAY = 2\n BLACK = 3\n\n def findOrder(self, n, m, prerequisites):\n # Code here\n numCourses = n\n # Create the adjacency list representation of the graph\n adj_list = defaultdict(list)\n\n # A pair [a, b] in the input represents edge from b --> a\n for dest, src in prerequisites:\n adj_list[src].append(dest)\n\n topological_sorted_order = []\n is_possible = True\n\n # By default all vertices are WHITE\n color = {k: Solution.WHITE for k in range(numCourses)}\n\n def dfs(node):\n nonlocal is_possible\n\n # Don't recurse further if we found a cycle already\n if not is_possible:\n return\n\n # Start the recursion\n color[node] = Solution.GRAY\n\n # Traverse on neighboring vertices\n if node in adj_list:\n for neighbor in adj_list[node]:\n if color[neighbor] == Solution.WHITE:\n dfs(neighbor)\n elif color[neighbor] == Solution.GRAY:\n # An edge to a GRAY vertex represents a cycle\n is_possible = False\n\n # Recursion ends. We mark it as black\n color[node] = Solution.BLACK\n topological_sorted_order.append(node)\n\n for vertex in range(numCourses):\n # If the node is unprocessed, then call dfs on it.\n if color[vertex] == Solution.WHITE:\n dfs(vertex)\n\n return topological_sorted_order[::-1] if is_possible else []\n",
"updated_at_timestamp": 1730267796,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findOrder(self, n, m, prerequisites):\n # Code here"
}
|
eJztmN2KHVUQhb3wKbwqznWQXft/+xDqpWCLoDnIgPSEZAKCKD6EPoN3PqPf2n0GhEzizJwzmkDnoijSfb6url6rqqd/+/iPvz75aP776k+Sr38+XK0vXt8cPrNDWtZiZVndwrJG82VNFpc1GweC5WWtVu8+WnQ06Lczizol6ZR51C0entnh+NOL4/c3x+ffXr++OV3x82v74uXz48ur9Qf78vrVq6vvfjwu693/C+3XZT388sz+UTIFeLDxjqqqqmoqvFtb1mFdWVC5/XR0/qzoF6eaq45GndzeUvhWzJ0lufhDBJ+3Lv5EZ6Fni6ou3FRWOLWtPrBFb14zUfF9r9pPJQ7zMBvo+pGbq510Q8+MVvBTz+ZSRDHXo6/mALyZg/Burs4Pi+o914cSubYuHi1CiTwM6SFbVJ+LRSiRm4USm0Uosc+647Dwzl6/ecfgUnh/73grbUOdTphV3F7rBNpOnjXf1lTPlIJqz0/RmIc+ocLU+LA1KYHhrCSDuSUoiXvQTSRLUBKDBkpCilBStQQlNUtQUrcEJQ3LUDK90HBxy5pP0TKUTC/UDAQAJTOwoORqGUpulqHkPnuYH+4PD0zGvf2Xan8JU9BFunYrUEq0ojWTrEAp9FRNZYVCKWwWKKVZgVK6FShlWIVSg1Uo1a1CqdEqlJqsal2xfbQPeDZ6OGxcKJX9pWXVrUKprCUoLViD0twalBatQWnJGpSWrWntFWtQGs9YD7lZg9LYg1AamxBKZw1qY7l1KJ0ZBaUn61B6tg6lF+tan9U6lI5WJJZuHUofNqAMlAZluA2tzWgDykg2oIxsA8ooNqCMakNruNmAMvpU6HjE8Efcvqt7V/cHoW5G8TaPPczBjPLCfHVFe0HiC6gvSH4B/QUJMKDAIAkGNBgkwoAKg2QY0GGQEAPkKeip6ClpyFPUUvWUtXQ9hS1lT2lL21PcUveUt/Q9BS6FT4mjcZfICSQiR7ll2gWypE4gERm1u+ROIBEZxbskTyARGdW7ZE/AbiKjfJf0CSQiJzlxWhGyDEAgERkPuExAIBEZH7iMQCARGS+4zEAgERk/uAxBIBE5y+XT5pBlCwKJyDjDZQ0Cici4w2UPAkNB5KI3uvmGBVkmIZCIjE9cRiGQzBECWWYhkIiMX1yGIZCIjGdcpiGQiFz1AigyznFZh0AiMu5x2YdAMscTZFmIQCIyLnLZiMDoEhknuaxEIBEZN7nsRCARGUe5LEUgEblp8s3RB1nGIpCIjLdc5iKQiIy/XAYjkIiMx1wmI5CIjM9cRiOQiNw1VedYhSy7ERiwIg8Nd5HxnMt0BBKRh16dRcZ5LusRSETGfS77EUhEHn1bEv6IDVO2PwPv2i4q0fI5b+kX/bt1vdgfrvtW3bfqvlX3rbpv1X2r3nOrooJtgE5BPGTHnrkDl/5vX2/bY7bgU2/m/j8UpVaVba9z5iW7pQu85VfnfBa/1HdxNeve5T3dZ9PbfXDeB+737mXsv/vC/c3vn/4NH+ztBQ==
|
705,824
|
Geek in a Maze
|
Geek is in a maze of size N * M (N rows, M columns). Each cell in the maze is made of either '.' or '#'. An empty cell is represented by '.' and an obstacle is represented by '#'. If Geek starts at cell (R, C), find how many different empty cellshe can pass through while avoiding the obstacles. He can move in any of the four directions but he can move up at most U times and he can move down atmost D times.
Examples:
Input:
N = 3, M = 3
R = 1, C = 0
U = 1, D = 1
mat = {{'.', '.', '.'},
{'.', '#', '.'},
{'#', '.', '.'}}
Output:
5
Explanation:
Geek can reach
(1, 0), (0, 0), (0, 1), (0, 2), (1, 2)
Input:
N = 4, M = 3
R = 1, C = 0
U = 1, D = 2
mat = {{'.', '.', '.'},
{'.', '#', '.'},
{'.', '.', '.'},
{'#', '.', '.'}}
Output:
10
Explanation:
Geek can reach all the
cells except for the obstacles.
Constraints:
1 ≤ N*M ≤ 10**6
mat[i][j] = '#" or '.'
0 ≤ R ≤ N-1
0 ≤ C ≤ M-1
mat[R][C] = '.'
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int numberOfCells(int n, int m, int r, int c, int u, int d, char mat[][])"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n//Position this line where user code will be pasted.\n\npublic class GFG {\n\tpublic static void main (String[] args) {\n\t Scanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();\n\t\twhile (t-- > 0)\n\t\t{\n\t\t int n = sc.nextInt();\n\t\t int m = sc.nextInt();\n\t\t int r = sc.nextInt();\n\t\t int c = sc.nextInt();\n\t\t int u = sc.nextInt();\n\t\t int d = sc.nextInt();\n\t\t \n\t\t char mat[][] = new char[n][m];\n\n for(int i = 0; i < n; i++)\n {\n String s = sc.next();\n for(int j = 0; j < m; j++)\n {\n mat[i][j] = s.charAt(j);\n }\n }\n \n Solution obj = new Solution();\n System.out.println(obj.numberOfCells(n, m, r, c, u, d, mat));\n\t\t \n\t\t}\n\t}\n}\n\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "//User function Template for Java\n\nclass Solution{\n\n\tpublic static int numberOfCells(int n, int m, int r, int c, int u, int d, char mat[][])\n\t{\n\t\t// code here\n\t\t\n\t\t\n\t}\n\n}\n"
}
|
{
"class_name": null,
"created_at_timestamp": 1615292571,
"func_sign": [
"numberOfCells(n, m, r, c, u, d, mat)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for tcs in range(t):\n n, m, r, c, u, d = [int(x) for x in input().split()]\n\n mat = []\n for i in range(n):\n matele = [x for x in input()]\n mat.append(matele)\n\n print(numberOfCells(n, m, r, c, u, d, mat))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nimport heapq as hq\n\n# Function to check if given coordinate is valid or not.\n\n\ndef isValid(row, col, n, m):\n if 0 <= row < n and 0 <= col < m:\n return True\n\n# Function to find the number of cells accessible from given coordinates.\n\n\ndef numberOfCells(n, m, r, c, u, d, mat):\n # If the starting cell is a block, return 0.\n if mat[r][c] == '#':\n return 0\n\n # Using a priority queue to store cells based on their priority.\n pque = []\n # Creating a matrix to keep track of visited cells.\n vis = [[0 for i in range(m)] for j in range(n)]\n\n # Pushing the starting cell into the priority queue.\n hq.heappush(pque, ((0, 0), (r, c)))\n vis[r][c] = 1\n\n # Iterating until the priority queue is empty.\n while pque:\n up, down = pque[0][0][0], pque[0][0][1]\n x, y = pque[0][1][0], pque[0][1][1]\n\n # Removing the cell with highest priority from the priority queue.\n hq.heappop(pque)\n\n # Checking all the adjacent cells and adding them to the priority queue if they meet the conditions.\n if isValid(x - 1, y, n, m):\n if up + 1 <= u and not vis[x - 1][y] and down <= d and mat[x - 1][y] == '.':\n hq.heappush(pque, (((up + 1), down), (x - 1, y)))\n vis[x - 1][y] = 1\n\n if isValid(x + 1, y, n, m):\n if down + 1 <= d and not vis[x + 1][y] and up <= u and mat[x + 1][y] == '.':\n hq.heappush(pque, ((up, (down + 1)), (x + 1, y)))\n vis[x + 1][y] = 1\n\n if isValid(x, y - 1, n, m):\n if down <= d and not vis[x][y - 1] and up <= u and mat[x][y - 1] == '.':\n hq.heappush(pque, ((up, down), (x, y - 1)))\n vis[x][y - 1] = 1\n\n if isValid(x, y + 1, n, m):\n if down <= d and not vis[x][y + 1] and up <= u and mat[x][y + 1] == '.':\n hq.heappush(pque, ((up, down), (x, y + 1)))\n vis[x][y + 1] = 1\n\n # Counting the number of visited cells.\n ans = 0\n for i in range(n):\n for j in range(m):\n if vis[i][j] == 1:\n ans += 1\n\n # Returning the total number of accessible cells.\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\ndef numberOfCells(n, m, r, c, u, d, mat):\n # code here"
}
|
eJztWN1KwzAU9sJH8AFCcztCk27CfBLBihe6CxHqkA0EUXwIfV9PTk9Okrl0xrnRSpN2TdPky3d+cnq699PPp7MTLJcP0Lh6Ke6b5XpVXIhC140uBRwzqEaYulFcJNxIJaWyp23bFlTl+7GN16AtbXFA0o+3o3AMthDTIdr+YiKKxfNycbta3N08rlfEsKybN3j4OhExbVMKg8zhqEQVEvcFV1O8SHvT0mEp2x+WY2O2coIyTyetn49ykLSS+zy616efKomYY0gkvY6YWcjFryAj6SJd09MNgVWoCamCdd3wyGYBnoyZoLwyFs2t4VaQ1JdpUy20KNsKeInJOjHZejBPJh/sumRyow1CmyRQP2mIHIifpdhXCXzwYSSvUXYCQtA01g4oAPsplOmQegrVIJQztIsH4aXT4PMk0xkIDOABfBg+8j0I48EcahUHs++BjZ00cmz2dQpOWyfzHuYdEwzqNH91fsBwVteu798ENDPwiNZ3s9otPpq27cuMskcxba9tOyZdiv2uR36cZjr0LRcnNkHKYJOGxiU6tWi6wKfbwPdKGXOI9ilHydTR+NE1hP1fHitHOZBVdS/Niu9ShzEc0/5FqNk/zuR+C8V/A/wqykBiNX4NHdofd76/rz/UF+38hQ4=
|
700,217
|
BFS of graph
|
Given aconnected undirected graphrepresented by an adjacency listadj, which is a vector of vectors where eachadj[i]represents the list of vertices connected to vertexi. Perform aBreadth First Traversal (BFS)starting from vertex0, visiting vertices from left to right according tothe adjacency list, and return a list containing the BFS traversal of the graph.
Examples:
Input:
adj = [[2,3,1], [0], [0,4], [0], [2]]
Output:
[0, 2, 3, 1, 4]
Explanation: Starting from 0, the BFS traversal will follow these steps:
Visit 0 → Output:
0
Visit 2 (first neighbor of 0) → Output:
0, 2
Visit 3 (next neighbor of 0) → Output:
0, 2, 3
Visit 1 (next neighbor of 0) → Output:
0, 2, 3,
Visit 4 (neighbor of 2) → Final Output:
0, 2, 3, 1, 4
Input:
adj = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]
Output:
[0, 1, 2, 3, 4]
Explanation:
Starting from 0, the BFS traversal proceeds as follows:
Visit 0 → Output:
0
Visit 1 (the first neighbor of 0) → Output:
0, 1
Visit 2 (the next neighbor of 0) → Output:
0, 1, 2
Visit 3 (the first neighbor of 2 that hasn't been visited yet) → Output:
0, 1, 2, 3
Visit 4 (the next neighbor of 2) → Final Output:
0, 1, 2, 3, 4
Constraints:
1 ≤ adj.size() ≤ 10**4
1 ≤ adj[i][j] ≤ 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1731499322,
"func_sign": [
"public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj)"
],
"initial_code": "import java.util.*;\n\n// Driver code\nclass GFG {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n int testcases = sc.nextInt(); // Taking number of test cases as Input:\n while (testcases-- > 0) {\n int V = sc.nextInt(); // Number of vertices\n int E = sc.nextInt(); // Number of edges\n\n // Initialize adjacency list\n ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n for (int i = 0; i < V; i++) {\n adj.add(new ArrayList<>()); // Create a new list for each vertex\n }\n\n // Add edges to the adjacency list\n for (int i = 0; i < E; i++) {\n int u = sc.nextInt();\n int v = sc.nextInt();\n adj.get(u).add(v); // Adding edge u -> v\n adj.get(v).add(u); // Adding edge v -> u (undirected graph)\n }\n\n // Create Solution object and call bfsOfGraph\n Solution obj = new Solution();\n ArrayList<Integer> result = obj.bfsOfGraph(V, adj);\n\n // Print the result\n for (int node : result) {\n System.out.print(node + \" \");\n }\n System.out.println();\n }\n\n sc.close(); // Close the scanner\n }\n}\n",
"script_name": "GFG",
"solution": "// Class representing the solution\nclass Solution {\n // Function to return Breadth First Traversal of the given graph.\n public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {\n ArrayList<Integer> bfsResult =\n new ArrayList<>(); // List to store BFS traversal result\n boolean[] visited = new boolean[V]; // Visited array to track visited nodes\n\n Queue<Integer> queue = new LinkedList<>();\n queue.add(0); // Starting BFS from vertex 0\n visited[0] = true; // Marking vertex 0 as visited\n\n while (!queue.isEmpty()) {\n int node = queue.poll(); // Dequeue a vertex from queue\n bfsResult.add(node); // Add the dequeued node to the result\n\n // Traverse all the adjacent vertices of the dequeued node\n for (int neighbor : adj.get(node)) {\n if (!visited[neighbor]) {\n visited[neighbor] = true; // Mark neighbor as visited\n queue.add(neighbor); // Enqueue the neighbor\n }\n }\n }\n\n return bfsResult; // Return the BFS traversal result\n }\n}",
"updated_at_timestamp": 1731499322,
"user_code": "// User function Template for Java\nclass Solution {\n // Function to return Breadth First Traversal of given graph.\n public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731499322,
"func_sign": [
"bfsOfGraph(self, adj: List[List[int]]) -> List[int]"
],
"initial_code": "if __name__ == '__main__':\n T = int(input()) # Number of test cases\n for i in range(T):\n V = int(input()) # Number of vertices\n E = int(input()) # Number of edges\n adj = [[] for i in range(V)] # Adjacency list\n for _ in range(E):\n u, v = map(int, input().split())\n adj[u].append(v)\n adj[v].append(u) # Undirected graph\n\n ob = Solution()\n ans = ob.bfsOfGraph(adj)\n print(\" \".join(map(str, ans))) # Print the BFS traversal result\n",
"solution": "# Back-end complete function Template for Python 3\nfrom queue import Queue\nfrom typing import List\n\n\nclass Solution:\n # Function to return Breadth First Traversal of given graph.\n def bfsOfGraph(self, adj: List[List[int]]) -> List[int]:\n ans = []\n V = len(adj)\n # boolean list to mark all the vertices as not visited.\n vis = [False for i in range(V)]\n\n # creating a queue for BFS and pushing first vertex in queue.\n q = Queue(maxsize=0)\n q.put(0)\n\n # initially we mark the first vertex as visited.\n vis[0] = True\n\n while not q.empty():\n # adding front element in output list and popping it from queue.\n v = q.get()\n ans.append(v)\n\n # traversing over all the connected components of front element.\n for i in adj[v]:\n # if they aren't visited, we mark them visited and add to queue.\n if not vis[i]:\n vis[i] = True\n q.put(i)\n\n # returning the output list.\n return ans\n",
"updated_at_timestamp": 1731499322,
"user_code": "#User function Template for python3\nclass Solution:\n # Function to return Breadth First Traversal of given graph.\n def bfsOfGraph(self, adj: List[List[int]]) -> List[int]:\n # code here"
}
|
eJztWMuKXFUUdeA/OF30OMh5P/wSwRIHmoGTMoMOBETwI/QLnfkVrrX3vkmnH2U1SIjQgRRV1fesu/dej3Nu/f7ln39/9YX9+/Yvvvnu15ufz2/e3t58g5t8OufE/+V0Tsh64buMqpd2Ohd0vYzTuWKezg3rdO7Yp/PQx6V3G+nmFW5ev3vz+sfb1z/98Mvb28AmIAo2Kho6BpbW3Pz2Cvfur1ukj+9/bRGqfSJn1aIeNrJWEYrrcrbvcvEvq3/Z4Gvaxap52VG20Hhjlk/0Yjd7pImkKfajDeugqIOqDpo66OrA5jbVQQzPpp8M9al6NaDckbk8sxwCZNZPiMymCZI3NL/C2RGl8N66eUEhSqkoGmFD0RA7ClHKQCFKmShEKQuFKIVEEaUmVKJUjp8olT2oiYpKlMqhEKV2VJExUIlSJypR6kIlSt1oRGkJjSiN/BGlFTSiNM5Cw2hoRGkdjShtoInUiUaUttCI0jY0yp7QidIzOlE6dUCUXtGJ0jlTDbWjE6UPdKL0iS5xLHSi9I1BlJEwiDIyBlEGhUSUUTGIMhoGUQa5ETkDgyhjYhBlLAyJbGNKMQmTKDNjEmUWTKJM6oIos2ESZXZMokxyLJInJlEmVU+UubGIshKWxJqxiLIKFlFWxSLKorCJsjoWURb9IotRKxLLwiLK2thE2QmbKDtjS/P0GFF2xSbKbthE2TQIUfbAJsqe2ETZ1JxEt5HCacXVacI0TR5yDB2GAEN5LrlDayGyUFfIyvV0CCkUFNIJzbhYDpWEPEIXIQhXwiGB4D5ID7ad5oPfIDYYDSqdw4O8YC3oCp6coIOZoCS4CBJ8+sfYY94x6Jiwj/ZSDHLkXLUsU0TGsGQRSc2TheQpKrOY5c1gWUDOeX9YEkBKIAfKAUgjpEUpAKmHTCkDIF0pBUgOVcf2YP6HtEhy5H5IpeRL3of0SwrlfEjZ8j5Zo+45PZjrITeQNXke8gmJlOMhB5Fb+R3ylhxPOuk8kgPzOuRH0imnQ04lw/I55GGSLpebwx/LU98YPmwK6f1+kN/vB0VpWqXcqjRt+tj1cejj1IoF3xYupr1HPZuGRfPDcooJ+qo90sppXo666Jbt3Sw1LNmH+Wpari8z1/ZUT26x7KluzWWDy4Yn7pM7MfseUHwPqLYHmFk74gq7oFze47o1nl2MvHxKf7bNmfpcd7HJPJxJN2O9bHj/0Yb3v4jkSxnXlHHNM47dSVPNDKUAsGgjnCuLg3FxtRKJxsF5nLEAzzIOljV5lmnkI7JMZLTIMtFUIstEYDJiH0pVzbf+7CPuv54uu1MyXLzTmVku3m0EiRkZMTtPxcVbna7m4u3O2nDxTidvuXi3cZhMu9ml68q1Pw+7ttvCZijTIJfhu1NMPuujyPAYUpF3/Fa9j+J9ZO8jWR9ut2VdTGtiWA/dWnCnVW/A6s9Wvsi4mD8iELYVSStqjfVrN7Jta4tsFsA2rXzppigaJZ2SLJpMOvnRp4phe/pLOn1Wx/EU23j12fvEY8Yx1Qi0mFzMyqdzzCMmED1Hl9FXdBIHyKg26vOKLkVY18Mqryl2hKEo1YiOBjyy2QGGf6W77JGw6AjDkTQXZ5UaOShNrps4h8XZUOop5qblWraTUVa6WWBL5GRHdHnAdflBJHalm+W3ck1c+0nt8ePSg2foq45LH84nw3iYJvVlSr/KC5cf/T3izd3x+FxtdA72yCnL1PypT1kW0dUjunlEdzOr4rvdPWgVP2iZKi+4235h6Kp8I/aEy8dP/dZgzwOajib10fnLtsWIOleN7Ylxs6eTr79E30v0XRl9R/Cx3nIn+PL96OvpbvrZjO6k36ePPk1Ven2isftXX3fZy4HxmQfGz+DEF0Jwz10rB1tz8h/rbOkzFj5HdiLj6kv71Vc+jfn9H1//A2C/4UI=
|
700,812
|
Count Odd Even
|
Given an array arr[] of positive integers. The task is to return the count of the number of odd and evenelements in the array.
Examples:
Input:
arr[] = [1, 2, 3, 4, 5]
Output:
3 2
Explanation:
There are 3 odd elements (1, 3, 5) and 2 even elements (2 and 4).
Input:
arr[] = [1, 1]
Output:
2 0
Explanation:
There are 3 odd elements (1, 1) and no even elements.
Constraints:
1 <= arr.size <= 10**6
1 <= arr[i] <= 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617248832,
"func_sign": [
"public int[] countOddEven(int[] arr)"
],
"initial_code": "// Initial Template for Java\n\n// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n String[] S = br.readLine().trim().split(\" \");\n int n = S.length;\n int[] arr = new int[n];\n for (int i = 0; i < n; i++) {\n arr[i] = Integer.parseInt(S[i]);\n }\n Solution obj = new Solution();\n int[] result = obj.countOddEven(arr);\n for (Integer t : result) {\n System.out.print(t + \" \");\n }\n System.out.println(\" \");\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730465377,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int[] countOddEven(int[] arr) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617248832,
"func_sign": [
"countOddEven(self, arr)"
],
"initial_code": "if __name__ == \"__main__\":\n # Testcase input\n testcase = int(input())\n\n for _ in range(testcase):\n arr = list(map(int, input().split()))\n\n # Creating an object of the Solution class\n ob = Solution()\n\n # Calling the function to count even and odd\n res = ob.countOddEven(arr)\n\n # Printing the result\n print(*res)\n print(\"~\")\n",
"solution": "class Solution:\n\n def countOddEven(self, arr):\n # Initializing count variables for odd and even elements\n countOdd = 0\n countEven = 0\n sizeof_array = len(arr)\n\n # Iterating through the array\n for i in range(sizeof_array):\n # Checking if the element is even\n if arr[i] % 2 == 0:\n countEven += 1\n # If not even, it must be odd\n else:\n countOdd += 1\n\n # Returning a list containing the count of odd and even elements\n return [countOdd, countEven]\n",
"updated_at_timestamp": 1730465377,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef countOddEven(self, arr):\n\t\t#Code here"
}
|
eJy1VMFKxDAU9CB+x5DzIpmkaapfIljxoD0IS91DFwRR/Aj9X2Oyhc3al7JdNpBOk/ImMy/v9evyZ311EcddF17u39VLv9kO6haKbU+1gureNt3T0D0/vm6H8RN023+2vfpYIY8wQoQGhQjqOI6Ou4njaIGEwcEUOBxcWTKSBORLgc3AiIosHDwCEUELOtCDojUtJx8VajRBEBicVWANNjCF5Ippyi3GZ5PAJ6gTuARVApvAJJDKR87sv7uZnnJqZEMxMuQlJ6OXrr8uivQjQcZmD3cWCN1nPzO9yH5m9aEm41YjHPDXCcWuX9D2WtPuKpoTXbugb+etnui19JvB5FXOFYadNrNPNtqJsgotyHw167OC3R398H39C7dLrFg=
|
703,807
|
Non Repeating Numbers
|
Given an array A containing 2*N+2 positivenumbers, out of which 2*N numbers exist inpairswhereasthe other two numberoccur exactly once and are distinct. Find the other two numbers. Return in increasing order.
Examples:
Input:
N = 2
arr[] = {1, 2, 3, 2, 1, 4}
Output:
3 4
Explanation:
3 and 4 occur exactly once.
Input:
N = 1
arr[] = {2, 1, 3, 2}
Output:
1 3
Explanation:
1 3 occur exactly once.
Constraints:
1 <= N <= 10**6
1 <= arr[i] <= 5 * 10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1730658714,
"func_sign": [
"public List<Integer> singleNumber(int[] arr)"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.util.*;\nimport java.util.HashMap;\n\n//Position this line where user code will be pasted.\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n\n // int k = Integer.parseInt(br.readLine());\n // Create Solution object and find closest sum\n Solution ob = new Solution();\n List<Integer> ans = ob.singleNumber(arr);\n\n // Print the result as a space-separated string\n for (int num : ans) {\n System.out.print(num + \" \");\n }\n System.out.println(); // New line after printing the results\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730905964,
"user_code": "// User function Template for Java\n\nclass Solution {\n public List<Integer> singleNumber(int[] arr) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1730658714,
"func_sign": [
"singleNumber(self, arr)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n\n ob = Solution()\n ans = ob.singleNumber(arr)\n\n print(\" \".join(map(str, ans)))\n tc -= 1\n print(\"~\")\n # This is an adjustment to correctly format an indentation error\n # The template had an incorrect indentation previously corrected now.\n",
"solution": "class Solution:\n def singleNumber(self, nums):\n diff = 0\n for i in nums:\n diff ^= i\n diff &= -diff\n\n ans1 = 0\n ans2 = 0\n for i in nums:\n if i & diff:\n ans1 ^= i\n else:\n ans2 ^= i\n\n if ans1 > ans2:\n return ans2, ans1\n else:\n return ans1, ans2\n",
"updated_at_timestamp": 1731325169,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef singleNumber(self, arr):\n\t\t# Code here\n"
}
|
eJy9lMFOwzAMhjkgnsPqeUKxkzQJT4JEEQfYgUvhsElICMRDwANx47H4nXWdBvOmbYhJdtss/p04n/N2+vF1dlJ/l594uXpu7vvH+ay5oIa7vu16JiFPgSK1eAox3hLlZkLN9Olxejub3t08zGdDjCOEvHZ98zKhdakMKUcMgUDcEmcSRyIkgaQlyeQdedERL6Z4NsTZqUHeMQw5nIchkYswZHMJlmGFWJfBPMwpZi7V3JjMd72WgLUS7PXJeEmmkDd0YtdLrNuOFByFSNHpJ7yOo+COkjNloyEbaimgoc6rC+qiulZdUpfXp4xjZrpgpEugROMRTUWr5hYVxukyNsPYGcc6AcOmejLUZQEgV/SCGS5GOGAslHFYLc4qDPwuaQbFBBx0YXvTXHRdvrZC0ZVBLtMOvpUZ0f/ErkOxN7JsxBXux7bkCGD8WwJXuv9Jsk49gN+hlvtfAwvwOf9GH+ynH/Drx4DNIV1wNMey9Vre+74d2xLo+21VtxpzhUi9UDstI0u/EcSRoLgboev3828r4slp
|
710,036
|
Max Sum without Adjacents 2
|
Given an array arrcontaining positive integers. Find the maximum sum that can be formed which has no three consecutive elements present from the array.
Examples:
Input:
arr[] = [1, 2, 3]
Output:
5
Explanation:
All three element present in the array is consecutive, hence we have to consider just two element sum having maximum,which is 2+3 = 5
Input:
arr[] = [3000, 2000, 1000, 3, 10]
Output:
5013
Explanation:
3000 + 2000 + 3 + 10 = 5013. Here no three elements is consecutive in that subsequence.
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1646227380,
"func_sign": [
"public int findMaxSum(int arr[])"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n long res = obj.findMaxSum(arr);\n\n System.out.println(res);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\n\nclass Solution {\n public int findMaxSum(int[] arr) {\n int n = arr.length;\n if (n == 0) return 0; // Handle empty array\n\n int[] sum = new int[n];\n\n // Base cases (process first three elements)\n if (n >= 1) {\n sum[0] = arr[0];\n }\n\n if (n >= 2) {\n sum[1] = arr[0] + arr[1];\n }\n\n if (n > 2) {\n sum[2] = Math.max(sum[1], Math.max(arr[1] + arr[2], arr[0] + arr[2]));\n }\n\n // Process rest of the elements\n // We have three cases\n // 1) Exclude arr[i], i.e., sum[i] = sum[i-1]\n // 2) Exclude arr[i-1], i.e., sum[i] = sum[i-2] + arr[i]\n // 3) Exclude arr[i-2], i.e., sum[i] = arr[i] + arr[i-1] + sum[i-3]\n for (int i = 3; i < n; i++) {\n sum[i] = Math.max(Math.max(sum[i - 1], sum[i - 2] + arr[i]),\n arr[i] + arr[i - 1] + sum[i - 3]);\n }\n\n return sum[n - 1];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "\n\nclass Solution {\n public int findMaxSum(int arr[]) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1646227414,
"func_sign": [
"findMaxSum(self,arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n # n = int(input())\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n ans = ob.findMaxSum(arr)\n print(ans)\n tc -= 1\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n\n def findMaxSum(self, arr):\n n = len(arr)\n if n == 0:\n return 0 # Handle empty array\n\n # Initialize a list to store the sums\n sum_arr = [0] * n\n\n # Base cases (process first three elements)\n if n >= 1:\n sum_arr[0] = arr[0]\n\n if n >= 2:\n sum_arr[1] = arr[0] + arr[1]\n\n if n > 2:\n sum_arr[2] = max(sum_arr[1], max(arr[1] + arr[2], arr[0] + arr[2]))\n\n # Process the rest of the elements\n for i in range(3, n):\n sum_arr[i] = max(max(sum_arr[i - 1], sum_arr[i - 2] + arr[i]),\n arr[i] + arr[i - 1] + sum_arr[i - 3])\n\n return sum_arr[n - 1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef findMaxSum(self,arr):\n\t\t# code here"
}
|
eJzFVk1PhEAM9eDFf9Fw3pjpfDDgH9HEVQ/KwQvugU02MRp/hP5f+wAJMdsRcF05dIa00M7r45W304/bs5P2urqUzfVz9lhvtk12QRmvazbGkIVxMB4mwOQwEaaAKWEQbNZ1tqKs2m2q+6Z6uHvaNv3bfOd9lYCXFX1LY50PFLyzTL/Yq7mdK2xkJXmJi5hmrmqyHH6vnbTDE3ACTYAJLAElkASQLY7EiGSEMmIZwYxoRjgjnvEAl32H1HrYRx34rml0oFWvAV6tAa2zp8/iRU0dTYp4Zlz+wTZpHNRqOmYtsmk2OrX9lhx5CpRTpIKE1mCe8E5YJ5wTxgnfhG3CNWGa8CzFMiVJGJTDDWrCg5Dscag5rEtjpzzW4fOX1Jveu2J081+UhYzMpq31PxS1TNbMcl2zLqFr03r3dewj9xevTcIpI0099N7JYpTwo8+g9JeYHkVjLZo+8hdIVQzOaoowW32VJGH8F3Dzfv4JTY9H2Q==
|
714,125
|
Binary matrix having maximum number of 1s
|
Given a binary matrix (containing only 0 and 1) of order NxN. All rows are sorted already, We need to find the row number with the maximum number of 1s. Also, find the number of 1s in that row.Note:
Examples:
Input:
N=3
mat[3][3] = {0, 0, 1,
0, 1, 1,
0, 0, 0}
Output:
Row number = 1
MaxCount = 2
Explanation:
Here, max number of 1s is in row number 1
and its count is 2.
Input:
N=3
mat[3][3] = {1, 1, 1,
1, 1, 1,
0, 0, 0}
Output:
Row number = 0
MaxCount = 3
Constraints:
1 <= N<= 10**3
0 <= mat[][]<= 1
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1677586163,
"func_sign": [
"public int[] findMaxRow(int mat[][], int N)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nclass FastReader{ \n BufferedReader br; \n StringTokenizer st; \n\n public FastReader(){ \n br = new BufferedReader(new InputStreamReader(System.in)); \n } \n\n String next(){ \n while (st == null || !st.hasMoreElements()){ \n try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } \n } \n return st.nextToken(); \n } \n\n String nextLine(){ \n String str = \"\"; \n try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } \n return str; \n } \n \n Integer nextInt(){\n return Integer.parseInt(next());\n }\n} \n\nclass GfG {\n public static void main(String[] args) {\n FastReader sc = new FastReader();\n PrintWriter out = new PrintWriter(System.out);\n int t = sc.nextInt();\n while(t-- > 0) {\n int B = sc.nextInt();\n int arr[][] = new int[B][B];\n for(int i = 0; i < B; i++) {\n for(int j = 0; j < B; j++) {\n arr[i][j] = sc.nextInt();\n }\n }\n Solution obj = new Solution();\n int ans[] = obj.findMaxRow(arr, B);\n for(int i = 0; i < 2; i++) {\n out.print(ans[i] + \" \");\n }\n out.println();\n \nout.println(\"~\");\n}\n out.flush();\n }\n}",
"script_name": "GfG",
"solution": "class Solution {\n public int[] findMaxRow(int mat[][], int N) {\n int row = 0, i = 0, j = N - 1;\n for (; i < N; i++) {\n while (j >= 0 && mat[i][j] == 1) {\n row = i;\n j--;\n }\n }\n return new int[]{row, N - 1 - j}; \n }\n};",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n public int[] findMaxRow(int mat[][], int N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1677586163,
"func_sign": [
"findMaxRow(self, mat, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n = int(input())\n mat = []\n for i in range(n):\n A = [int(x) for x in input().split()]\n mat.append(A)\n ob = Solution()\n ans = []\n ans = ob.findMaxRow(mat, n)\n for i in range(2):\n print(ans[i], end=\" \")\n print()\n print(\"~\")\n",
"solution": "class Solution:\n def findMaxRow(self, mat, N):\n # initializing the variables\n j = N - 1\n ind = 0\n\n # iterating over the matrix rows\n for i in range(N):\n # searching for the last occurrence of 1 in the row\n while j >= 0 and mat[i][j] == 1:\n j -= 1\n ind = i\n # returning the row index and the number of zeros after the last 1\n return [ind, N - j - 1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findMaxRow(self, mat, N):\n # Code here"
}
|
eJxrYJlawsYABhG5QEZ0tVJmXkFpiZKVgpJhTB4QGSjpKCilVhSkJpekpsTnl5ZAZQ0UDBRi8upi8pRqdRQwdBni1GWIS5cR0C4FAzBBupVAzYYKhmACp2YjvDYb4rcZv7Px2myI22ZTsD4IBNsPgQSZOJ1piscmJIOItxSnn4i0iXhLcdhkRIZNBCzFYZMxDpsMcGcCdJXEK0VNs0TEDwUhiyNwyMgp5IU4ieENy1RkZ0miXWlAbMLAGSAg3VAbqehOQ/wRilpk4c44JvgKaHIjk9SSHXd+iJ2iBwDubsKz
|
704,506
|
Nth item through sum
|
Given two arrays A and B of length L1and L2, we can get a set of sums(add one element from the first and one from second). Find the Nth element in the set considered in sorted order.Note:Set of sums should have unique elements.
Examples:
Input:
L1 = 2, L2 = 2
A = {1, 2}
B = {3, 4}
N = 3
Output:
6
Explanation:
The set of sums are in
the order 4, 5, 6.
Input:
L1 = 5, L2 = 4
A = {1, 3, 4, 8, 10}
B = {20, 22, 30, 40}
N = 4
Output:
25
Explanation:
The numbers before it
are 21, 23 and 24.
Constraints:
1 ≤ L1, L2 ≤ 500
1 ≤ A[i], B[i] ≤ 10000
1 ≤ N ≤ L1*L2
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int nthItem(int L1, int L2, int A[], int B[], int N)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n public static void main(String args[])throws IOException\n {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while(t-- > 0){\n String val[] = in.readLine().trim().split(\"\\\\s++\");\n int L1 = Integer.parseInt(val[0]);\n int L2 = Integer.parseInt(val[1]);\n String arr[] = in.readLine().trim().split(\"\\\\s++\");\n int [] A = new int[L1];\n for(int i = 0;i < L1; i++)\n A[i] = Integer.parseInt(arr[i]);\n String arr1[] = in.readLine().trim().split(\"\\\\s++\");\n int [] B = new int[L2];\n for(int i = 0;i < L2; i++)\n B[i] = Integer.parseInt(arr1[i]);\n int N = Integer.parseInt(in.readLine());\n \n Solution ob = new Solution();\n System.out.println(ob.nthItem(L1, L2, A, B, N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static int nthItem(int L1, int L2, int A[], int B[], int N) {\n // Insert each pair sum into set. Note that a set\n // stores elements in sorted order and unique elements\n HashSet<Integer> s = new HashSet<>();\n for (int i = 0; i < L1; i++) for (int j = 0; j < L2; j++) s.add(A[i] + B[j]);\n // If set has less than N elements\n if (s.size() < N) return -1;\n ArrayList<Integer> arr = new ArrayList<>();\n for (int element : s) {\n arr.add(element);\n }\n Collections.sort(arr);\n return arr.get(N - 1);\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n static int nthItem(int L1, int L2, int A[], int B[], int N)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"ntItem(self, L1, L2, A, B, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n L1, L2 = [int(x) for x in input().split()]\n A = input().split()\n for itr in range(L1):\n A[itr] = int(A[itr])\n B = input().split()\n for it in range(L2):\n B[it] = int(B[it])\n N = int(input())\n\n ob = Solution()\n print(ob.nthItem(L1, L2, A, B, N))\n print(\"~\")\n",
"solution": "class Solution:\n def nthItem(self, L1, L2, A, B, N):\n # create an empty set to store the sums of pairs\n seen = set()\n # create an empty list to store the unique sums\n new = []\n # iterate through each element in list A\n for i in range(len(A)):\n # iterate through each element in list B\n for j in range(len(B)):\n # calculate the sum of the current pair\n s = A[i] + B[j]\n # if the sum is not already in the set, add it to the list and set\n if s not in seen:\n new.append(s)\n seen.add(s)\n # sort the list of unique sums in ascending order\n new.sort()\n\n # if the desired position N is greater than the length of the unique sums list, return -1\n if N > len(new):\n return -1\n # otherwise, return the Nth element in the unique sums list\n else:\n return new[N-1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def ntItem(self, L1, L2, A, B, N):\n # code here"
}
|
eJytVctOwzAQ5IDEb4x8LsjPpOFLkAjiADlwMVWVSiAE4iPgf9ldN0ClLmlJnMiysuvJzGSzfj/9fD47kXG1psX1i3nIq01vLmFcmx14Gm6zgOmeVt1d393fPm76bZ5v8xsFXxfY3ewRBMHSaHOiGTQ5nmhLVPFckg17MSOiYEKYecjV5qCCnTsF6VtaoafL4wQNRF7e0BhUOn7wN5YmbT+WbpOqLLDv5KHggN0kcF56fhjK11BhY1IZJiRhhYDIy4QKNZZo2MXjeVaoxH74QguxVAgqUW9LpDDmmAQlymFdQQiqAsemlKIkbEImXEIlTNQWS4vGqpQog1M4p1jLJqskUqNxGGTPrzuqug8pCU7Twb1eFrOYWk90dcYvW/+fxE+7TCNdZfSv2GUaZqiPqPQeq+RPMjlM/H8q1eRtn/RHNV31FBhXFA+u3l9H5ai+4dC8+bj4AmOmAdw=
|
712,184
|
Grid Path 2
|
You are given a grid of n * m having 0 and 1 respectively, 0 denotes space, and 1 denotes obstacle. Geek is located at the top-left corner (i.e. grid[0][0]) and wants to reach the bottom right corner of the grid. A geek can move either down or right at any point in time. return the total number of ways in which Geek can reach the bottom right corner. answer may be large take the modulo by 1e9+7.
Examples:
Example:
Input:
n = 3, m = 3
grid= [[0,0,0],[0,1,0],[0,0,0]]
Output:
2
Explanation:
There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach
the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
Example 2:
Input:
n = 2, m = 2
grid = [[0,1],[0,0]]
Output:
1
Expected Time Complexity:
O(m * n)
Expected Space Complexity:
O(n)
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1667973466,
"func_sign": [
"public int totalWays(int N, int M, int grid[][])"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while (t-- > 0) {\n int N = sc.nextInt();\n int M = sc.nextInt();\n int[][] grid = new int[N][M];\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n grid[i][j] = sc.nextInt();\n }\n }\n Solution obj = new Solution();\n int res = obj.totalWays(N, M, grid);\n System.out.println(res);\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n\n public int totalWaysUtil(int i, int j, int[][] grid,\n int[][] dp)\n {\n // Base cases\n if (i < grid.length && j < grid[0].length\n && grid[i][j] == 1)\n return 0;\n if (i == grid.length - 1 && j == grid[0].length - 1)\n return 1;\n if (i >= grid.length || j >= grid[0].length)\n return 0;\n\n if (dp[i][j] != -1)\n return dp[i][j];\n\n int down = totalWaysUtil(i + 1, j, grid, dp);\n int right = totalWaysUtil(i, j + 1, grid, dp);\n\n // Store the result in the DP table and return it\n return dp[i][j] = (down + right) % 1000000007;\n }\n\n public int totalWays(int N, int M, int grid[][])\n {\n // Code here\n int[][] dp\n = new int[N][M]; // DP table to memoize results\n for (int[] row : dp)\n Arrays.fill(row, -1);\n return totalWaysUtil(0, 0, grid, dp);\n }\n}",
"updated_at_timestamp": 1730481588,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int totalWays(int N, int M, int grid[][]) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1667977122,
"func_sign": [
"totalWays(self, n, m, grid)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n, m = list(map(int, input().split()))\n grid = [list(map(int, input().split())) for _ in range(n)]\n ob = Solution()\n res = ob.totalWays(n, m, grid)\n print(res)\n print(\"~\")\n",
"solution": "class Solution:\n\n # Function to calculate the total number of ways to reach the bottom-right corner of the grid.\n def totalWays(self, n, m, grid):\n\n # If the starting position is blocked, return 0.\n if grid[0][0]:\n return 0\n\n # Constant value to reduce the final result.\n M = 10**9 + 7\n\n # Create a 2D array to store the number of ways to reach each cell.\n t = [[0 for i in range(m)] for i in range(n)]\n\n # Fill the first row and column based on whether each cell is blocked or not.\n for i in range(n):\n if grid[i][0] != 1:\n t[i][0] = 1\n else:\n break\n\n for j in range(m):\n if grid[0][j] != 1:\n t[0][j] = 1\n else:\n break\n\n # Iterate through the remaining cells and calculate the number of ways by summing the values from the top and left cells.\n for i in range(1, n):\n for j in range(1, m):\n if grid[i][j] != 1:\n t[i][j] = (t[i-1][j] + t[i][j-1]) % M\n\n # Return the number of ways to reach the bottom-right cell.\n return t[n - 1][m - 1] % M\n",
"updated_at_timestamp": 1730481588,
"user_code": "#User function Template for python3\n\nclass Solution:\n def totalWays(self, n, m, grid):\n # Code here"
}
|
eJzdVUtuwjAQ7YJNbzHyGlV2Pk7oSUCAqNRm0U3KIkiVqiIOAffFmdjUjj3UICWqGkv+vvl43nhymJxeHh/wmy/UZPnF3uvtrmHPwNJVnYLqOKjWDqIbcJVAglu4saozyPSRgf6A2wmugbMpsOpzW7021dvmY9doS0rVXmGwT7Fn31OwXFGAHHKjT1zcMeb0orXD7V09lSAtlI0TDtLRa5/0YcQ9SvQ94aErqNsJpcjV45p1219Feo0IhsgIJksoPT1dhlwz7zl5p47eRgGF4VwEiPa0eqfXZWMC1aULlTQzmAWi7lMW4mZ8FHHFnHoRGFAqgQghLD0oKX6JKSGrWb3LronEjXat6uXmhVO9QgDCUBp8Xb3o3OLkgCV2tBrL8SciKHJ8tIxDhp/hf3mHYzE/NPUyks3Ww0ikSahYPAlbH5/OOFRNtw==
|
703,228
|
Minimum steps to get desired array
|
Consider an array with all values zero. We can perform the following operations on the array : 1. Incremental operations: Choose 1 element from the array and increment its value by 1. 2. Doubling operation: Double the values of all the elements of an array.Given an integer array arr[]. Return the least possible number of operations needed to change the original array containing only zeroes to arr[].
Examples:
Input:
arr[] = [16, 16, 16]
Output:
7
Explanation:
First apply an incremental operation to each element. Then apply the doubling operation four times. Total number of operations is 3+4 = 7.
Input:
arr[] = [2, 3]
Output:
4
Explanation:
To get the target array from [0, 0], we first increment both elements by 1 (2 operations), then double the array (1 operation). Finally increment second element (1 more operation). Total number of operations is 2+1+1 = 4.
Constraints:
1 ≤ arr.size() ≤ 10**5
0 ≤ arr[i] ≤ 10**9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int countMinOperations(int[] arr)"
],
"initial_code": "import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int t = Integer.parseInt(scanner.nextLine()); // Read number of test cases\n\n while (t-- > 0) {\n String line = scanner.nextLine(); // Read each line of input\n String[] elements = line.split(\" \");\n int[] arr = new int[elements.length]; // Create an array for input numbers\n\n for (int i = 0; i < elements.length; i++) {\n arr[i] = Integer.parseInt(\n elements[i]); // Populate the array with input numbers\n }\n\n Solution ob = new Solution();\n System.out.println(ob.countMinOperations(arr)); // Print the result\n }\n scanner.close(); // Close the scanner\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n // Method to count the minimum operations required\n int countMinOperations(int[] arr) {\n Arrays.sort(arr);\n int ans = 0;\n int n = arr.length;\n\n while (true) {\n boolean allZero = true;\n\n for (int i = n - 1; i >= 0; i--) {\n if (arr[i] % 2 == 1) {\n arr[i]--;\n ans++;\n }\n arr[i] /= 2;\n if (arr[i] > 0) {\n allZero = false;\n }\n }\n \n if (allZero) break;\n ans++;\n }\n\n return ans;\n }\n}",
"updated_at_timestamp": 1727947200,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Method to count the minimum operations required\n int countMinOperations(int[] arr) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"countMinOperations(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input()) # Read the number of test cases\n while tc > 0:\n # Read and parse input array\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n ans = ob.countMinOperations(arr) # Calculate the number of operations\n print(ans) # Print the result\n tc -= 1 # Decrement the test case counter\n",
"solution": "class Solution:\n\n def countMinOperations(self, arr):\n arr.sort() # Sort the array to process elements\n ans = 0\n while True:\n all_zero = True # Flag to check if all elements are zero\n for i in range(len(arr) - 1, -1, -1):\n if arr[i] % 2 == 1:\n arr[i] -= 1 # Decrement odd elements\n ans += 1 # Count the decrement operation\n if arr[i] != 0:\n all_zero = False # Check if the element is non-zero\n arr[i] //= 2 # Halve the element\n if all_zero:\n break # Break if all elements are zero\n ans += 1 # Count the halving operation\n return ans # Return the total number of operations\n",
"updated_at_timestamp": 1727947200,
"user_code": "#User function Template for python3\n\nclass Solution:\n def countMinOperations(self, arr):\n # code here"
}
|
eJy9VMtOAzEM5ID4DmvPFYofeSxfgkRRD1AkLksPrYSEkPgI+F+cdBNQG7ecmD3saLOxx/HEH5dfT1cXBbcrJXdvw/O02W2HGxhwOaGrgC4dFjCsXzfrh+36cfWy2847Q1pOw/sCDoIBgUACDMAEQQApAfkAHkljkhjRCHvRxgJIBRALIBSALwApAC4AKgAsMFJpZb1cWWAWmgWrblWvNSQtRokVaewewc8hjhWNpcZiY6Ex35g0xo1RY5Ygwm5THBw9RoD+ybR6pDFujI4tA74t+ro2Mwh7Arz/Yp2sxBNHW3NWFVVXzQthfsf5nWo/DpSaDgn97JGjYCIBzyFFN2bLhCTsJRuHhTDGbJ+ILqVsIvZepFhJnUvZUKwLTm2Fo7BTc7kxoidDiHT7gVqIOlNvAqj/gU84lP6toec72p8X+3DJ2MXU3WRNEaNtp3pN3T3zPbNUdc3p8+z7NUHOTQ/q1jZfcA03oWUL7mr2VqLulPpLGmtOmtcm/3//ef0Ni76ojA==
|
700,233
|
Postorder from Inorder and Preorder
|
Given a preOrder and inOrder traversal of a binary treeyour task is to print the postOrder traversal of the tree .You are required to complete the function printPostOrder which prints the node of the tree in post order fashion .You should not read any input from stdin/console.There are multiple test cases. For each test case, this method will be called individually.
Examples:
Input:
6
4 2 5 1 3 6
1 2 4 5 3 6
Output:
4 5 2 6 3 1
|
geeksforgeeks
|
Easy
|
{
"class_name": "GfG",
"created_at_timestamp": 1730192192,
"func_sign": [
"void printPostOrder(int in[], int pre[])"
],
"initial_code": "import java.util.*;\n\nclass PostOrder {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n int T = sc.nextInt();\n while (T > 0) {\n int N = sc.nextInt();\n int pre[] = new int[N];\n int in[] = new int[N];\n for (int i = 0; i < N; i++) in[i] = sc.nextInt();\n for (int i = 0; i < N; i++) pre[i] = sc.nextInt();\n GfG g = new GfG();\n g.printPostOrder(in, pre);\n System.out.println();\n T--;\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "PostOrder",
"solution": "None",
"updated_at_timestamp": 1730204396,
"user_code": "/*prints the post order traversal of the\ntree */\nclass GfG {\n void printPostOrder(int in[], int pre[]) {\n // Your code here\n }\n}"
}
|
{
"class_name": null,
"created_at_timestamp": 1730192192,
"func_sign": [
"printPostOrder(inorder, preorder)"
],
"initial_code": "# Driver Program\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n = int(input())\n ino = list(map(int, input().strip().split()))\n pre = list(map(int, input().strip().split()))\n printPostOrder(ino, pre)\n print()\n print(\"~\")\n\n# contributed by: Harshit Sidhwa\n",
"solution": "# Your task is to complete this function\n# Function should print postorder traversal of Tree\ndef search(arr, x, n):\n for i in range(n):\n if arr[i] == x:\n return i\n return -1\n\n# This function is used to print the postorder traversal of a binary tree\ndef printPostOrder(inorder, preorder):\n n = len(inorder)\n \n if n == 0:\n return\n \n # Finding the root in the inorder array using the first element in the preorder array\n root = search(inorder, preorder[0], n)\n \n # If root is not the first element in inorder array, then recursively call the function for the left subtree\n if root != 0:\n printPostOrder(inorder[:root], preorder[1:1+root])\n \n # If root is not the last element in inorder array, then recursively call the function for the right subtree\n if root != n - 1:\n printPostOrder(inorder[root + 1:], preorder[1+root:])\n \n # Print the root of the current subtree\n print(preorder[0], end=\" \")\n",
"updated_at_timestamp": 1730204396,
"user_code": "# Your task is to complete this function\n# Function should print postorder traversal of Tree\ndef printPostOrder(inorder, preorder):\n # Code here\n"
}
|
eJy1VMtOw0AM5MCBz7ByrtB619tke+MvkAjiAD1wCT20UiUE4iPgf7G92zZIcUpfVSpFu2PP2GPn6/rn7uZKf/czfnl4r167xWpZzaDCtsPYdgQeIiAEmEKCGtBBA+gBEZAAAwgIGUQMGwFVE6jm68X8eTl/eXpbLQuLRDEuKog0wEus4yyJs/EptN1n21UfE/irruYnQ9OGK7Rd4iMVkFNhMIh7IoNgk0WTpA8ZrKXtqhJ+IYp6JRe5AIuSgSkLVpTCPac0iJH/sRB4B57b6yBEIAcUITqI3Hk+4jsGRYXprWAKwFCiYNScXvFR8ZTDnanIMyEzTaE0HrN1U8BGJQrG6RzUDGr00qvARlAeDT1B0TUovKRDjVOZlhzuDz9mjUYY++ZloPPYWmb5sdErIx9k6MUk4lfOafm+gVrpKCuirSYgUxWN6UInCYRLljZvkBilg6QaqXdqrmSuXUc+77OpXCZi58S+oRiZgOGSLIn7hBxE8o8y6hPrGKToztqqo8zI+IEws/rekEkCYxFOkt4i9dVTHHahfP0u2agzfIAv5yhTHeJpdFu7jvXJ2ev4+H37C8/AHWE=
|
705,898
|
Theft at World Bank
|
The worlds most successful thief Albert Spaggiari was planning for his next heist on the world bank. He decides to carry a sack with him, which can carry a maximum weight of c kgs. Inside the world bank there were n large blocks of gold. All the blocks have some profit value associated with them i.e. if he steals i**th block of weight w[i] then he will have p[i] profit. As blocks were heavy he decided to steal some part of them by cutting themwith his cutter.The thief does not like symmetry, hence, he wishes to not take blocks or parts of them whose weight is a perfect square. Now, you need to find out the maximum profit that he can earn given that he can only carry blocks of gold in his sack.
Examples:
Input:
n = 3, c = 10, w[] = {4, 5, 7}, p[] = {8, 5, 4)
Output:
7.857
Explanation:
As first blocks weight is 4 which is a perfect square, he will not use this block. Now with the remaining blocks the most optimal way is to use 2
**nd
block completely and cut 5kg piece from the 3
**rd
block to get a total profit of 5 + 2.857 = 7.857
Constraints:
1 ≤ n ≤ 10**3
1 ≤ c ≤ 10**18
1 ≤ w
i
≤10**9
1 ≤ p
i
≤10**9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public double maximumProfit(int N, long C, long w[], long p[])"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String s1 = br.readLine().trim();\n String []S1 = s1.split(\" \");\n int n = Integer.parseInt(S1[0]);\n long C = Long.parseLong(S1[1]);\n String s2 = br.readLine().trim();\n String []S2 = s2.split(\" \");\n long [] w = new long[n];\n long [] p = new long[n];\n for(int i = 0; i < n; i++){\n w[i] = Long.parseLong(S2[2*i]);\n p[i] = Long.parseLong(S2[(2*i)+1]);\n }\n Solution ob = new Solution();\n double ans = ob.maximumProfit(n, C, w, p);\n String a1 = String.format(\"%.3f\",ans);\n System.out.println(a1);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public double maximumProfit(int N, long C, long w[], long p[]) {\n Pair v[] = new Pair[N]; // Create an array of Pairs to store weight and profit\n for (int i = 0; i < N; i++) {\n v[i] = new Pair(); // Initialize each Pair object\n }\n \n // Calculate the profit-to-weight ratio and store in the Pair objects\n // If weight is a perfect square, set profit to 0\n for (int i = 0; i < N; i++) {\n long temp = (long) Math.sqrt(w[i]);\n if (temp * temp == w[i]) {\n p[i] = 0;\n }\n v[i].first = (double) p[i] / (double) w[i]; // Profit-to-weight ratio\n v[i].second = w[i]; // Weight\n }\n \n Arrays.sort(v); // Sort the array based on the profit-to-weight ratio\n \n double ans = 0; // Initialize the total profit\n int itr = N - 1; // Start from the last element (highest profit-to-weight ratio)\n while (itr >= 0 && C > 0) { // Keep going until either all items are included or no more capacity\n long t = Math.min(C, v[itr].second); // Take the minimum weight between remaining capacity and the weight of current item\n ans += (double) t * v[itr].first; // Add the product of weight and profit-to-weight ratio to the total profit\n C -= t; // Reduce the remaining capacity by the weight of current item\n itr--; // Move to the next item\n }\n \n return ans; // Return the maximum profit\n }\n \n \n static class Pair implements Comparable<Pair> {\n double first;\n long second;\n \n public int compareTo(Pair o) {\n if (this.first > o.first)\n return 1;\n else if (this.first < o.first)\n return -1;\n else {\n if (this.second > o.second)\n return 1;\n else if (this.second < o.second)\n return -1;\n else\n return 0;\n }\n }\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public double maximumProfit(int N, long C, long w[], long p[])\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maximumProfit(self, N, C, w, p)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n, C = input().split()\n n = int(n)\n C = int(C)\n temp = list(map(int, input().split()))\n w = []\n p = []\n for i in range(2 * n):\n if (i % 2) == 0:\n w.append(temp[i])\n else:\n p.append(temp[i])\n ob = Solution()\n ans = ob.maximumProfit(n, C, w, p)\n print(\"{:.3f}\".format(ans))\n print(\"~\")\n",
"solution": "# User function Template for python3\n\nclass Solution:\n\n # Function to find the maximum profit.\n def maximumProfit(self, N, C, w, p):\n l = []\n # zers=[]\n\n # iterating over all the items.\n for i in range(N):\n # if weight of item is not zero, add it to the list.\n if w[i] != 0:\n l.append((p[i], w[i]))\n\n # sorting the items in descending order of their profit to weight ratio.\n l.sort(key=lambda x: x[0] / x[1], reverse=True)\n prof = 0\n\n # iterating over the items.\n for i in l:\n # checking if the weight of item is perfect square.\n if self.isperf(i[1]):\n continue\n else:\n # if weight of item is less than or equal to the remaining capacity\n # of the knapsack, add its profit to the total profit and deduct the\n # weight of item from the remaining capacity of the knapsack.\n if C - i[1] >= 0:\n C -= i[1]\n prof += i[0]\n if C == 0:\n return prof\n\n # if weight of item is greater than the remaining capacity\n # of the knapsack, calculate the fraction of the item that can\n # be taken, add its fraction of profit to the total profit and return.\n else:\n fractn = C / i[1]\n prof += i[0] * fractn\n return prof\n\n return 9.9\n\n # Function to check if the number is perfect square or not.\n def isperf(self, num):\n # checking if the square root of number is an integer.\n if num ** (0.5) == int(num ** (0.5)):\n return True\n",
"updated_at_timestamp": 1731586317,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef maximumProfit(self, N, C, w, p):\n\t\t# Code here"
}
|
eJzNVsFOwzAM5cCFv7B6nqrYibOE/0BCoogD7MClcNgkJATiI+B/eU66A0ibIGUT1bR6dfL8/Gynezv9GM5OynV5AePqubsfHzfr7pw6HkYlds4NYybviCOJI1FSRz5ScBSy+YexW1C3enpc3a5XdzcPm/UEkPts3lcseFnQV2QGkjktAkVKtCRW3FjsgUUTC8Xe4nCgADtZZFCIjSGNuXnZWFMwAoQMtKTGy5KbSEmOU8kuO2OmRoDBQ5jEqIEmPALKEbcK5M2Cj2G18YtF7MoQgPUHdABdrmYADalmLMSLmbHRF1OQQK4IDfFligmLlDwyV6tCKUwp17YmSlUEr/bQdBGrD4Sw+kRS2AlVsmURi4HhbDGE9EuCsj5RUtsIFYNQhh3aO4nwZdvbdyPfnZul192KkbPQJtRuANe7PQA89WOdrtZR0oICGQ0pl4JthxUf9LMv7YwaxGC6Jy4D5erOWbLV3mwQ7xuETH2PS5vg2qYbehxtwCeKPE3ZYY8h10xz76Gv80794yngmGZo8PuzMPyPw/CPBT6cwrPfdnNfd7P+gdgrByr/KPD1e/8Ji0FG+g==
|
703,264
|
Maximum difference Indexes
|
Given an array arr[] of integers, find the maximum possible gap. The gap is defined as the difference between the indices of an element's first and last appearance in the array. If an element appears only once, its gap is 0.
Examples:
Input:
arr[] = [2, 1, 3, 4, 2, 1, 5, 1, 7]
Output:
6
Explanation:
For the array with 0-based indexing, the number 1's first appearance is at index 1 and its last appearance is at index 7. The gap is 7 - 1 = 6, which is the maximum gap in this array.
Input:
arr[] = [5, 3, 4, 3, 5, 2, 5, 3]
Output:
6
Explanation:
For the array with 0-based indexing, the number 3's first appearance is at index 1 and its last appearance is at index 7. The gap is 7 - 1 = 6, which is the maximum gap in this array.
Constraints:
1 ≤ arr.size() ≤ 10**6
-10**5≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int maxGap(List<Integer> arr)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\n//Position this line where user code will be pasted.\n\npublic class Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int t = scanner.nextInt();\n scanner.nextLine(); // Consume the newline character\n for (int i = 0; i < t; i++) {\n String input = scanner.nextLine();\n List<Integer> arr = Arrays.stream(input.split(\" \"))\n .map(Integer::parseInt)\n .collect(Collectors.toList());\n Solution solution = new Solution();\n System.out.println(solution.maxGap(arr));\n System.out.println(\"~\");\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "import java.util.*;\n\nclass Solution {\n public int maxGap(List<Integer> arr) {\n Map<Integer, int[]> indices = new HashMap<>();\n // Track the first and last occurrences of each element\n for (int i = 0; i < arr.size(); i++) {\n int num = arr.get(i);\n if (!indices.containsKey(num)) {\n indices.put(num, new int[] {i, i});\n } else {\n indices.get(num)[1] = i;\n }\n }\n // Calculate the maximum gap\n int maxGap = 0;\n for (int[] indexPair : indices.values()) {\n int gap = indexPair[1] - indexPair[0];\n maxGap = Math.max(maxGap, gap);\n }\n return maxGap;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "import java.util.*;\n\nclass Solution {\n public int maxGap(List<Integer> arr) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxGap(self, arr)"
],
"initial_code": "if __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n arr = list(map(int, input().split()))\n solution = Solution()\n print(solution.maxGap(arr))\n print(\"~\")\n",
"solution": "class Solution:\n def maxGap(self, arr):\n firstIndex = {}\n lastIndex = {}\n maxGap = 0\n\n for i, num in enumerate(arr):\n if num not in firstIndex:\n firstIndex[num] = i\n lastIndex[num] = i\n\n for num in firstIndex:\n gap = lastIndex[num] - firstIndex[num]\n maxGap = max(maxGap, gap)\n\n return maxGap\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def maxGap(self, arr):\n # code here.\n"
}
|
eJytVUtOwzAQZYHENUZZN8jjTz6cBIkgFtAFm9BFKyGhIg4Bx2THAZjJJKnzmdBWJI7Hdl/n2W/G9sfl18/VRfPcflPj7i15rje7bXIDiatqBAsOPCAEyCCHgloloKlqAylCVBHWgDUwqZMVJOvXzfpxu356eNltW+dlVb9XdRbVyX4FEbtlj+ybqtCUvksfT23xVWiFCoPGaJ0PGbQmC95Z7MxgsKqDMTIVNqn0DMgM6VH4vfDP0dNg7ybEXrtB6S4ubOTSc5xm3y5czoBvxM0M5AYKA6UIjfQ7cgwJgQRBDgCBkFBIMCz5//SxH8JZwlnCWcJZwlnCWcLZkkmIL+2kKvkRU4jJxWRighgvxomxYlCMOWRml5eclYo0KHKbST0NQDfH1h7iuxhUp2RTtNKSfMVd1oP3TWqb4ppCS/aLFLN54/7cC12yKhnVpj1kecHBH7c1VWUPycS8ogC5mMQpyoWxvv2AxmkizrnzYpDSw26/u2b2VtxRqIO+TtLX/G/inCPbGZLRsoM+Oe14UuDqlhofa+l8Fp7u/KQbgs+lwcC5t4ScQ8dpdqS0vPQzArF8T9CBvXgHJfv7z+tfjJgGSA==
|
702,088
|
Word Search
|
Given a 2D board of letters and a word. Check if the word exists in the board. The word can be constructed from letters of adjacent cells only. ie - horizontal or vertical neighbors. The same letter cell can not be used more than once.
Examples:
Input:
board = {{a,g,b,c},{q,e,e,l},{g,b,k,s}},
word = "geeks"
Output:
1
Explanation:
The board is-
a
g
b c
q
e
e
l
g b
k s
The letters which are used to make the
"geeks" are colored.
Input:
board = {{a,b,c,e},{s,f,c,s},{a,d,e,e}},
word = "sabfs"
Output:
0
Explanation:
The board is-
a b c e
s f c s
a d e e
Same letter can not be used twice hence ans is 0
Constraints:
1 ≤ N, M ≤ 100
1 ≤ L ≤ N*M
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public boolean isWordExist(char[][] board, String word)"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String[] S = br.readLine().trim().split(\" \");\n int n = Integer.parseInt(S[0]);\n int m = Integer.parseInt(S[1]);\n char [][] board = new char[n][m];\n for(int i = 0; i < n; i++){\n String[] s = br.readLine().trim().split(\" \");\n for(int j = 0; j < m; j++){\n board[i][j] = s[j].charAt(0);\n }\n }\n String word = br.readLine().trim();\n Solution obj = new Solution();\n boolean ans = obj.isWordExist(board, word);\n if(ans)\n System.out.println(\"1\");\n else\n System.out.println(\"0\");\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "//Back-end Complete function Template for JAVA\n\nclass Solution {\n // Function to check if a word exists in a grid\n // starting from the first match in the grid\n // wIdx: index till which pattern is matched\n // x, y: current position in 2D array\n static boolean findMatch(char[][] mat, String word, int x, int y, int wIdx) {\n int wLen = word.length();\n int n = mat.length;\n int m = mat[0].length;\n\n // Pattern matched\n if (wIdx == wLen) return true;\n\n // Out of Boundary\n if (x < 0 || y < 0 || x >= n || y >= m) return false;\n\n // If grid matches with a letter while recursion\n if (mat[x][y] == word.charAt(wIdx)) {\n // Marking this cell as visited\n char temp = mat[x][y];\n mat[x][y] = '#';\n\n // finding subpattern in 4 directions\n boolean res = findMatch(mat, word, x - 1, y, wIdx + 1) ||\n findMatch(mat, word, x + 1, y, wIdx + 1) ||\n findMatch(mat, word, x, y - 1, wIdx + 1) ||\n findMatch(mat, word, x, y + 1, wIdx + 1);\n\n // marking this cell as unvisited again\n mat[x][y] = temp;\n return res;\n }\n\n // Not matching then return false\n return false;\n }\n\n // Function to check if the word exists in the matrix or not\n static public boolean isWordExist(char[][] mat, String word) {\n int wLen = word.length();\n int n = mat.length;\n int m = mat[0].length;\n\n // if total characters in matrix is less than word length\n if (wLen > n * m) return false;\n\n // Traverse in the grid\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n\n // If first letter matches, then recur and check\n if (mat[i][j] == word.charAt(0)) {\n if (findMatch(mat, word, i, j, 0)) return true;\n }\n }\n }\n return false;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution\n{\n public boolean isWordExist(char[][] board, String word)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isWordExist(self, board, word)"
],
"initial_code": "if __name__ == '__main__':\n T = int(input())\n for tt in range(T):\n n, m = map(int, input().split())\n board = []\n for i in range(n):\n a = list(input().strip().split())\n b = []\n for j in range(m):\n b.append(a[j][0])\n board.append(b)\n word = input().strip()\n obj = Solution()\n ans = obj.isWordExist(board, word)\n if (ans):\n print(\"1\")\n else:\n print(\"0\")\n",
"solution": "class Solution:\n\n # Function to check if a word exists in the board\n def isWordExist(self, board, word):\n # Iterate through all cells in the board\n for i in range(len(board)):\n for j in range(len(board[0])):\n # If the first character of the word is found\n # and adjacent characters also match, check further\n if board[i][j] == word[0] and self.adjacentSearch(board, word, i, j, 0):\n return True\n return False\n\n # Recursive function to search for adjacent characters in the board\n def adjacentSearch(self, board, word, i, j, length):\n # Base case, check if the entire word has been found\n if length == len(word):\n return True\n\n # Check for out of bound conditions\n if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]):\n return False\n\n # Check if the current cell's character matches with the word's character\n if board[i][j] != word[length]:\n return False\n\n # Mark the current cell as visited\n board[i][j] = '*'\n\n # Recursively check the adjacent cells\n ans = self.adjacentSearch(board, word, i - 1, j, length + 1) or \\\n self.adjacentSearch(board, word, i + 1, j, length + 1) or \\\n self.adjacentSearch(board, word, i, j - 1, length + 1) or \\\n self.adjacentSearch(board, word, i, j + 1, length + 1)\n\n # Restore the current cell's original value\n board[i][j] = word[length]\n return ans\n",
"updated_at_timestamp": 1727947200,
"user_code": "class Solution:\n\tdef isWordExist(self, board, word):\n\t\t#Code here"
}
|
eJzVlUtOwzAQhlmw4hS/sq5Q09eCkyAxCMWJ82o7zaJt0iIkDgF3YMcVcR4yQYaqToOq+osiK5Jn/P8Zj1+v3z9vrqpx/6EmD89Owtlm7dzBcYndIdwhsQcDYgEDYh8GxAEMiCUMiEMYEEcwII5hQJzAgDiFgVIk/ECGUZykzgCOLDLpr2XwtNqsv8U7LwP8tGOKacuMlgUt4S25LZFqmQx88Uey4W/JZpgR76Eh3kFDXEBDnENDvIWGeAONilbk2/3OZhMTTErFQimr5ITK/croFHMsiJdgrJC1DZ0vlrzKbJKMMW5sbSxt7Kyi1o9NOBfqpUJ5Nr92hFEltNyB7dqmLNRC1IttpqLBSuGBY3nZH/Ww8b+pH1EfPln3jLg8+570o8CTIvz3mrcq+LO0VT7cV8/aWHsv6Auv6FM6Cjq1lGMycq9NrM54msiOKmviy7zBYXmF91FLXfO5ZZBu92F+KOfj2+0XVSQ77Q==
|
704,510
|
Subset with sum divisible by k
|
Given an array arr[] of positive integers and a value k. Return 1 if the sum of any subset(non-empty) of the given array is divisible by k otherwise, return 0.
Examples:
Input:
arr[] = [3, 1, 7, 5] , k=6
Output:
1
Explanation:
If we take the subset {7, 5} then sum will be 12 which is divisible by 6.
Input:
arr[] = [1, 2, 6] , k=5
Output:
0
Explanation:
All possible subsets of the given set are {1}, {2}, {6}, {1, 2}, {2, 6}, {1, 6} and {1, 2, 6}. There is no subset whose sum is divisible by 5.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int DivisibleByM(int[] arr, int k)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n\n int k = Integer.parseInt(br.readLine());\n // Create Solution object and find closest sum\n Solution ob = new Solution();\n int ans = ob.DivisibleByM(arr, k);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "// User function Template for Java\nclass Solution {\n public int DivisibleByM(int[] arr, int k) {\n int n = arr.length;\n if (n > k) return 1;\n // This array will keep track of all\n // the possible sums (after modulo k)\n // which can be made using subsets of arr[]\n // initializing boolean array with all false\n boolean[] DP = new boolean[k];\n // We'll loop through all the elements of arr[]\n for (int i = 0; i < n; i++) {\n // anytime we encounter a sum divisible by k, we are done\n if (DP[0]) return 1;\n // To store all the new encountered sums (after modulo).\n // It is used to make sure that arr[i] is added only to\n // those entries for which DP[j] was true before current iteration.\n boolean[] temp = new boolean[k];\n // For each element of arr[], we loop through\n // all elements of DP table from 0 to k-1 and\n // we add the current element, i.e., arr[i] to\n // all those elements which are true in DP table\n for (int j = 0; j < k; j++) {\n // if an element is true in DP table\n if (DP[j]) {\n if (!DP[(j + arr[i]) % k]) {\n // We update it in temp and update\n // DP once loop of j is over\n temp[(j + arr[i]) % k] = true;\n }\n }\n }\n // Updating all the elements of temp\n // to DP table since iteration over j is over\n for (int j = 0; j < k; j++) {\n if (temp[j]) {\n DP[j] = true;\n }\n }\n // Also since arr[i] is a single element\n // subset, arr[i] % k is one of the possible sums\n DP[arr[i] % k] = true;\n }\n return DP[0] ? 1 : 0;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int DivisibleByM(int[] arr, int k) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"DivisibleByM(self,arr, k)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n k = int(input().strip())\n ob = Solution()\n ans = ob.DivisibleByM(arr, k)\n print(ans)\n print(\"~\")\n tc -= 1\n",
"solution": "# User function Template for python3\nclass Solution:\n\n def DivisibleByM(self, arr, k):\n n = len(arr)\n if n > k:\n return 1\n\n # This array will keep track of all the possible sums (after modulo k)\n # which can be made using subsets of arr[]\n # initializing boolean array with all False\n DP = [False] * k\n\n # We'll loop through all the elements of arr[]\n for i in range(n):\n # anytime we encounter a sum divisible by k, we are done\n if DP[0]:\n return 1\n\n # To store all the new encountered sums (after modulo).\n # It is used to make sure that arr[i] is added only to\n # those entries for which DP[j] was true before the current iteration.\n temp = [False] * k\n\n # For each element of arr[], we loop through all elements of DP table\n # from 0 to k-1 and we add the current element, i.e., arr[i], to\n # all those elements which are true in DP table\n for j in range(k):\n # if an element is true in DP table\n if DP[j]:\n if not DP[(j + arr[i]) % k]:\n # We update it in temp and update DP once the loop of j is over\n temp[(j + arr[i]) % k] = True\n\n # Updating all the elements of temp to DP table since iteration over j is over\n for j in range(k):\n if temp[j]:\n DP[j] = True\n\n # Also, since arr[i] is a single element subset, arr[i] % k is one of the possible sums\n DP[arr[i] % k] = True\n\n return 1 if DP[0] else 0\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef DivisibleByM(self,arr, k):\n\t\t# Code here"
}
|
eJy1ksFKxEAMhj2Iz/Ez50WSzEyn45MIVjxoD17qIl1YEcWH0Pc1GRGXhbo7pduhobTpn+T783H+9XJxVq7rZ324eXWPw3ozuis47gYmcIREeEIgROoGIbeC67fr/n7sH+6eNuNf+ns3uLcV9jQE3EKCafgGQbohVUq00A6QwQEi8B4xmm6lSlINQYMWrHNwrJ2DCKK3J2NhMKi8rOaBo46SrhTOSMqJ9V8PTuAM0YEzvH7ztcgFwUA18IosgEUtjA0iyzx0hV2BV+gVfITGQrLQWsgWLFnJWmYtWm+KqqLt2uLq3WpdXWLR5ZVUymtWdfsHvGq5UP9V/8c6OtK6eZ7xDuVlVrRw3D8GdZmxd/xazq38wy5Njz3VzhS/aYNOVCKBZlfwJCeAOgeNVeoOrcTt5+U3d028Sw==
|
701,297
|
Strings Rotations of Each Other
|
You are given two strings of equal lengths,s1 ands2. The task is to checkifs2is a rotated version of the strings1.
Examples:
Input:
s1 = "geeksforgeeks", s2 = "forgeeksgeeks"
Output:
true
Explanation:
s1 is geeksforgeeks, s2 is forgeeksgeeks. Clearly, s2 is a rotated version of s1 as s2 can be obtained by left-rotating s1 by 5 units.
Input:
s1 = "mightandmagic", s2 = "andmagicmigth"
Output:
false
Explanation:
Here with any amount of rotation s2 can't be obtained by s1.
Constraints:
1 <= s1.size(), s2.size() <= 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1619091325,
"func_sign": [
"public static boolean areRotations(String s1, String s2 )"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n \n\tpublic static void main (String[] args)throws IOException{\n\t\t\n\t\t//taking input using BufferedReader class\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\t//taking total count of testcases\n\t\tint t = Integer.parseInt(br.readLine());\n\t\twhile(t-->0)\n\t\t{\n\t\t //Reading the two Strings\n\t\t String s1 = br.readLine();\n\t\t String s2 = br.readLine();\n\t\t \n\t\t //Creating an object of class Rotate\n\t\t Solution obj = new Solution();\n\t\t \n\t\t //calling areRotations method \n\t\t //of class Rotate and printing\n\t\t //\"1\" if it returns true\n\t\t //else \"0\"\n\t\t if(obj.areRotations(s1,s2))\n\t\t {\n\t\t System.out.println(\"1\");\n\t\t }\n\t\t else\n\t\t {\n\t\t System.out.println(\"0\");\n\t\t }\n\t\t}\n\t}\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1727947200,
"user_code": "\nclass Solution\n{\n //Function to check if two strings are rotations of each other or not.\n public static boolean areRotations(String s1, String s2 )\n {\n // Your code here\n }\n \n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619091325,
"func_sign": [
"areRotations(self,s1,s2)"
],
"initial_code": "# Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\n\[email protected]\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n s1 = str(input())\n s2 = str(input())\n if Solution().areRotations(s1, s2):\n print(1)\n else:\n print(0)\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\ndef KMPSearch(pat, txt):\n M = len(pat)\n N = len(txt)\n # create lps[] that will hold the longest prefix suffix\n # values for pattern\n lps = [0]*M\n j = 0 # index for pat[]\n # Preprocess the pattern (calculate lps[] array)\n computeLPSArray(pat, M, lps)\n i = 0 # index for txt[]\n while (N - i) >= (M - j):\n if pat[j] == txt[i]:\n i += 1\n j += 1\n if j == M:\n return True # pattern found\n # mismatch after j matches\n elif i < N and pat[j] != txt[i]:\n # Do not match lps[0..lps[j-1]] characters,\n # they will match anyway\n if j != 0:\n j = lps[j-1]\n else:\n i += 1\n return False\n\n# Function to compute LPS array\n\n\ndef computeLPSArray(pat, M, lps):\n length = 0 # length of the previous longest prefix suffix\n lps[0] = 0 # lps[0] is always 0\n i = 1\n # the loop calculates lps[i] for i = 1 to M-1\n while i < M:\n if pat[i] == pat[length]:\n length += 1\n lps[i] = length\n i += 1\n else:\n if length != 0:\n length = lps[length-1]\n # Also, note that we do not increment i here\n else:\n lps[i] = 0\n i += 1\n\n\nclass Solution:\n\n # Function to check if two strings are rotations of each other or not.\n def areRotations(self, s1, s2):\n\n # we concatenate first string to itself and check if other\n # string occurs in it as substring. If yes, then it\n # is rotated version and we return true else false.\n s = s1 + s1\n if len(s1) == len(s2) and KMPSearch(s2, s):\n return True\n return False\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to check if two strings are rotations of each other or not.\n def areRotations(self,s1,s2):\n #code here"
}
|
eJy1VEuOwjAMZTHiHFXWCMGWk4w0RihN0w9Qp7QpXzGaQ8zcd5ICLQhSkVDeIrWSvth+tvPz8Tfv9yp8MmV8HUiCWSnJxCNjQAroA5KBR/g240zyYCZKeT4fAX6rw+PAuyUVNOWX1UAdG6jUZwFgwKi9V03lYRQDxmfT2nsRi1wCLgVGPC9knqD5DmMYNW5tayE03dp7LiSViai/j3YcSqJ1TeaLZaroKLKVEqdcb7a7vZs8vgbTCDS4RqgB2NiP/nQOPu0m+uvOfo/aVx7AVlo1q03KTcJ1si61Arhv5pYuf3VqadvYtt1xejTMDWLOsSK71dbRZetAgYvwlfLdl/eJAbLvgOnv8B8Ly0hR
|
704,716
|
Learn Geometry
|
Find max number of squares (S) of side 2 units that can fit in an Isosceles triangle with a right angle and its shortest side equal to "B" units.Note: The squares don't have to fit completely inside the Triangle.
Examples:
Input:
B
=
1
Output:
0
Explanation:
We can't fit any squares.
Input:
B
=
10
Output:
10
Explanation:
We can fit 10 squares of 2 unit sides
in an Isosceles Right Traingle with
the shortest side being 10 unit length.
Constraints:
1 <= B <= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static Long maxSquares(Long B)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n Long B = Long.parseLong(read.readLine());\n\n Solution ob = new Solution();\n System.out.println(ob.maxSquares(B));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static Long maxSquares(Long B) {\n Long n = B / 2; // Calculating half of B\n Long ans = (n * (n - 1)) / 2; // calculating the Answer\n return ans;\n }\n}\n;\n",
"updated_at_timestamp": 1730476047,
"user_code": "//User function Template for Java\n\nclass Solution {\n static Long maxSquares(Long B) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxSquares(self, B)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n B = int(input())\n\n ob = Solution()\n print(ob.maxSquares(B))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def maxSquares(self, B):\n n = B//2 # Calculating half of B\n ans = (n*(n-1))//2 # calculating the Answer\n return ans\n",
"updated_at_timestamp": 1730476047,
"user_code": "#User function Template for python3\n\nclass Solution:\n def maxSquares(self, B):\n # code here"
}
|
eJytk0FOxDAMRVnAPaqsRyix4yTmJEgUsYAu2JRZdKSREKM5BByPHQchTScVRThBlL+KVOfF/9s9nr99XJwlXb/Hw82zeuy3u0FdNcq0PWe1vdo0qttvu/uhe7h72g25COxUAaST4q1DrH7ZNEuU0Vl1lqe59EcWVVF4YoWMkroCtOR8KBhkTYY9BNCWLEj24kuOLI7fRXeGERwaD8yGAcSe9JxkJaiKOaBaTD5MKDyRBJDPkkHkoq+A1mjLGCAIJMySvWFIcmyTSEopSyaN89AcjGcd5yyB5pbWNlQd2RiyeHk5r1/8K1BqpLY8ad7F/att37QxZTtFY99Of3O6gLd6ZW5faatx+j9yLHvMk56GJr2T4bevl5/WkrFs
|
703,090
|
Convert array into Zig-Zag fashion
|
Given an arrayarr of distinct elements of sizen, the task is to rearrange the elements of the array in a zig-zag fashion so that the converted array should be in the below form:
Examples:
Input:
n = 7, arr[] = {4, 3, 7, 8, 6, 2, 1}
Output:
1
Explanation:
After modification the array will look like 3 < 7 > 4 < 8 > 2 < 6 > 1, the checker in the driver code will produce 1.
Input:
n = 5, arr[] = {4, 7, 3, 8, 2}
Output:
1
Explanation:
After
modification the array will look like 4 < 7 > 3 < 8 > 2 hence output will be 1.
Constraints:
1 <= n <= 10**6
0 <= arr
i
<= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1672718077,
"func_sign": [
"public static void zigZag(int n, int[] arr)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass IntArray {\n public static int[] input(BufferedReader br, int n) throws IOException {\n String[] s = br.readLine().trim().split(\" \");\n int[] a = new int[n];\n for (int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]);\n\n return a;\n }\n\n public static void print(int[] a) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n\n public static void print(ArrayList<Integer> a) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n}\n\nclass GFG {\n\n public static boolean isZigzag(int n, int[] arr) {\n int f = 1;\n\n for (int i = 1; i < n; i++) {\n if (f == 1) {\n if (arr[i - 1] > arr[i]) return false;\n } else {\n if (arr[i - 1] < arr[i]) return false;\n }\n f ^= 1;\n }\n\n return true;\n }\n\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n int n;\n n = Integer.parseInt(br.readLine());\n\n int[] arr = IntArray.input(br, n);\n\n Solution obj = new Solution();\n obj.zigZag(n, arr);\n boolean flag = false;\n for (int i = 0; i < n; i++) {\n if (arr[i] == i % 2) {\n flag = false;\n } else {\n flag = true;\n break;\n }\n }\n if (!flag) {\n System.out.println(\"0\");\n } else {\n\n boolean check = isZigzag(n, arr);\n if (check) {\n System.out.println(\"1\");\n } else {\n System.out.println(\"0\");\n }\n }\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public static void zigZag(int[] arr) {\n int n = arr.length;\n boolean flag = true;\n\n for (int i = 0; i <= n - 2; i++) {\n if (flag) { // \"<\" relation expected\n if (arr[i] > arr[i + 1]) {\n // Swap arr[i] and arr[i + 1]\n int temp = arr[i];\n arr[i] = arr[i + 1];\n arr[i + 1] = temp;\n }\n } else { // \">\" relation expected\n if (arr[i] < arr[i + 1]) {\n // Swap arr[i] and arr[i + 1]\n int temp = arr[i];\n arr[i] = arr[i + 1];\n arr[i + 1] = temp;\n }\n }\n flag = !flag; // flip flag\n }\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "\nclass Solution {\n public static void zigZag(int n, int[] arr) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1672832258,
"func_sign": [
"zigZag(self, n : int, arr : List[int])"
],
"initial_code": "class IntArray:\n\n def __init__(self) -> None:\n pass\n\n def Input(self, n):\n arr = [int(i) for i in input().strip().split()] # array input\n return arr\n\n def Print(self, arr):\n for i in arr:\n print(i, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n\n def isZigzag(n: int, arr: List[int]) -> bool:\n f = 1\n\n for i in range(1, n):\n if f:\n if arr[i - 1] > arr[i]:\n return False\n else:\n if arr[i - 1] < arr[i]:\n return False\n f = f ^ 1\n\n return True\n\n t = int(input())\n for _ in range(t):\n\n n = int(input())\n\n arr = IntArray().Input(n)\n\n obj = Solution()\n obj.zigZag(n, arr)\n check = True\n check = isZigzag(n, arr)\n\n flag = False\n for i in range(n):\n if arr[i] == i % 2:\n flag = False\n else:\n flag = True\n break\n\n if not flag:\n print(\"0\")\n else:\n if check:\n print(\"1\")\n else:\n print(\"0\")\n print(\"~\")\n",
"solution": "from typing import List\n\n\nclass Solution:\n\n def zigZag(self, n: int, arr: List[int]) -> None:\n flag = True\n\n for i in range(1, n):\n if flag: # \"<\" relation expected\n if arr[i - 1] > arr[i]:\n # Swap arr[i - 1] and arr[i]\n arr[i - 1], arr[i] = arr[i], arr[i - 1]\n else: # \">\" relation expected\n if arr[i - 1] < arr[i]:\n # Swap arr[i - 1] and arr[i]\n arr[i - 1], arr[i] = arr[i], arr[i - 1]\n flag = not flag # flip flag\n",
"updated_at_timestamp": 1729753320,
"user_code": "\nfrom typing import List\nclass Solution:\n def zigZag(self, n : int, arr : List[int]) -> None:\n # code here\n \n"
}
|
eJzdVc2KFDEQ9uDFt/jo8yKpSlKp+CSCKx50Dl7GPczCgig+hL6hN1/Cr5IR2V0d6N5B1GECc5j+fitdnx5/+fbk0fg8/8ofL94vb/dX14flGRa53Hd+YahoyHAUKGS5wLK7udq9PuzevHp3ffj574+X++XDBW5DSIqDzsfbgCqE2gBT40AgQ0QmiCixRAhJfCNDg69E1RDXAzUMEr8GdAvUHqgeJBacZLIgdqSVHDXFQekoTLChGApTIGRGoQVBScgd2ZGpwpArMkOiRUUW5ATtUIc2KDVUKCNghgoVaEIY8HBAhRFRCQ/UTRNnDP7MqGmMBYE6uqM3dDZY0Qt6Rld0NsD8yeNwFmvwCi9wzqHCBZ7QWDllNDRD44wWNJanaILGieDkOowqDVZhBZZhrFNgCbWjOmpDpQn2XlAzqqJynv7dsnLMGsc5no3rGpe3DZ40qOTIFkJsaGkhJ2TKUKohNkzY8EETa69UjLsO+cx52JnserxU5YfzPJjTUUUwz6RkkM8Ea2iZyVJOBD0Tz1HAsYk2ipkNyShsNldnkSvlW4rzn47HX2hOfuVO8/Z3VdfTayJt2RN3to/ZOfZPSr9bJSe3qPvDXrx3gHraCnVqsYk9YGK0/enldr9Xz7NZbKoW97HPB367RXHvuiaDl5+ffgf4dFF2
|
707,603
|
License Key Formatting
|
Given a string Sthat consists of only alphanumeric characters and dashes.The string is separated intoN + 1groups byNdashes. Also given an integerK.
Examples:
Input:
S = "5F3Z-2e-9-w", K = 4
Output:
"5F3Z-2E9W"
Explanation:
The string
S
has been split into two
parts, each part has 4 characters. Note that two
extra dashes are not needed and can be removed.
Input:
S = "2-5g-3-J", K = 2
Output:
"2-5G-3J"
Explanation:
The string s has been split
into three parts, each part has 2 characters
except the first part as it could
be shorter as mentioned above.
Constraints:
1 ≤ S.length() ≤ 10**5
1 ≤ K ≤ 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1621842262,
"func_sign": [
"static String ReFormatString(String S, int K)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n public static void main(String args[])throws IOException\n {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while(t-- > 0){\n String s = in.readLine();\n int k = Integer.parseInt(in.readLine());\n \n Solution ob = new Solution();\n System.out.println(ob.ReFormatString(s, k));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Backend complete function Template for Java\n\nclass Solution{\n // Function to reformat the string by adding '-' every K characters from right to left\n static String ReFormatString(String S, int K){\n StringBuilder res = new StringBuilder(); // StringBuilder to store the reformed string\n int cnt = 0; // Counter variable to keep track of the number of characters added\n \n // Loop from right to left through the string\n for(int i=S.length()-1; i>=0; i--){\n // Check if the current character is not '-'\n if(S.charAt(i) != '-') {\n Character cap = Character.toUpperCase(S.charAt(i)); // Convert the character to uppercase\n \n // Check if cnt is not zero and divisible by K\n if(cnt != 0 && cnt % K == 0) {\n cnt = 1; // Reset the counter to 1\n res.insert(0,'-'); // Insert '-' character to separate groups\n res.insert(0,cap); // Insert the uppercase character\n }\n else {\n cnt++; // Increment the counter\n res.insert(0,cap); // Insert the uppercase character\n }\n }\n }\n \n return res.toString(); // Return the reformed string\n }\n}",
"updated_at_timestamp": 1730270076,
"user_code": "// User function Template for Java\n\nclass Solution{\n static String ReFormatString(String S, int K){\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1621842028,
"func_sign": [
"ReFormatString(self,S, K)"
],
"initial_code": "# Initial Template for Python 3\nimport atexit\nimport io\nimport sys\nfrom collections import defaultdict\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\n\[email protected]\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n s = str(input())\n k = int(input())\n obj = Solution()\n print(obj.ReFormatString(s, k))\n print(\"~\")\n",
"solution": "# Backend complete function Template for python3\n\nclass Solution:\n # Function to reformat the string.\n def ReFormatString(self, S, K):\n res = [] # list to store the reformatted string\n cnt = 0 # variable to count the characters\n\n # iterating over the input string from right to left\n for i in range(len(S)-1, -1, -1):\n if S[i] != '-':\n # converting character to uppercase and adding it to the result string\n res.append(S[i].upper())\n cnt += 1 # incrementing character count\n\n # if character count becomes equal to K, add '-' to the result string and reset count.\n if cnt == K:\n cnt = 0\n res.append('-')\n\n # if last character in the result string is '-', remove it.\n if len(res) and res[-1] == '-':\n res.pop()\n\n res = res[::-1] # reverse the string\n res = \"\".join(res) # convert list to string\n\n return res # return the reformatted string.\n",
"updated_at_timestamp": 1730270076,
"user_code": "#User function Template for python3\n\nclass Solution:\n def ReFormatString(self,S, K):\n #code here"
}
|
eJy1VclSwkAU9ODBL/BmFZUzbbElgDfCJrK6o8ayWMImDKigqKXlR+j/+jKBAjQzIOCbHKjKdDev35KPza+drQ0exW36cfWqNFlv0Ff2XIrXYF6fPwBVC4YQjuioVE3UDOY3mOJ2KeawZ1b6ZvWmO+iPET4/AqqGYCiMiB5FLJ4w2Dtdf3O7ZolL5QqqZg31RrOF23aHodszmCpkjkCPEhuS+6mDNDLZXL4gYAZFCWWQOuJIgJKQsY7vCdjCFAhRIEgBjcJgPiEhXeb3wQHgCFgQR/IihqIj+9dFCI9AKMLN496RdcgXDo9wfHJ6hvPixaXBAmKDyJ+x7XDEOur1cId7PKCPAR7xRAk940XmWwGcFZwWQt5wKKipAb/P60FJr1DdaslGqpVuZxn55RFXhWCwcZYTmFgh6SHeRNSkoJ5HHQ00QZ2KNjpgshmwLQNJYNSqAhEvHI7MJHo98yxZbFm1p5EW0MJJ6jzHpzUZNVJxlJnWWZeQsOxVeTp831mjAvIP2VxsUZl/0vm1Y9vzlqw97UnwDiDmjHDLOk04H/G/1Eu8DlbtPG7hMp+ZmQkQGTt3whabwrXOYfmH5SuYoNv6k/yvP3e/AevTdZU=
|
701,301
|
Remove common characters and concatenate
|
Given two stringss1ands2. Modify both the strings such that all the common characters of s1 and s2 are to be removed and the uncommon characters of s1 and s2 are to be concatenated.Note:If all characters are removedprint-1.
Examples:
Input:
s1 = aacdb
s2 = gafd
Output:
cbgf
Explanation:
The common characters of s1
and s2 are: a, d. The uncommon characters
of s1 and s2 are c, b, g and f. Thus the
modified string with uncommon characters
concatenated is cbgf.
Input:
s1 = abcs
s2 = cxzca
Output:
bsxz
Explanation:
The common characters of s1
and s2 are: a,c. The uncommon characters
of s1 and s2 are b,s,x and z. Thus the
modified string with uncommon characters
concatenated is bsxz.
Constraints:
1 <= |Length of Strings| <= 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1619116376,
"func_sign": [
"public static String concatenatedString(String s1,String s2)"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG{\n public static void main(String args[]){\n Scanner in=new Scanner(System.in);\n int t=in.nextInt();\n \n while(t--!=0){\n String s1=in.next(),\n s2=in.next();\n \n Solution obj = new Solution();\n \n System.out.println(obj.concatenatedString(s1,s2));\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution\n{\n //Function to remove common characters and concatenate two strings.\n public static String concatenatedString(String s1,String s2)\n {\n String res = \"\";\n int i;\n \n //using map to store all characters of s2 in map.\n HashMap<Character, Integer> m = new HashMap<Character, Integer>();\n for (i = 0; i < s2.length(); i++)\n m.put(s2.charAt(i), 1);\n \n //finding characters of s1 that are not present in s2\n \t//and appending them to result.\n for (i = 0; i < s1.length(); i++)\n if (!m.containsKey(s1.charAt(i)))\n res += s1.charAt(i);\n else\n m.put(s1.charAt(i), 2);\n \n //finding characters of s2 that are not present in s1\n \t//and appending them to result.\n for (i = 0; i < s2.length(); i++)\n if (m.get(s2.charAt(i)) == 1)\n res += s2.charAt(i);\n \n if(res == \"\")\n \tres = \"-1\";\n \t\n //returning the result.\n return res;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "\n\nclass Solution\n{\n //Function to remove common characters and concatenate two strings.\n public static String concatenatedString(String s1,String s2)\n {\n // Your code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619116376,
"func_sign": [
"concatenatedString(self,s1,s2)"
],
"initial_code": "# Initial Template for Python 3\n\nimport atexit\nimport io\nimport sys\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\n\[email protected]\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n s = str(input())\n p = str(input())\n obj = Solution()\n print(obj.concatenatedString(s, p))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to remove common characters and concatenate two strings.\n def concatenatedString(self, s1, s2):\n res = \"\"\n m = {}\n\n # using map to store all characters of s2 in map.\n for i in range(0, len(s2)):\n m[s2[i]] = 1\n\n # finding characters of s1 that are not present in s2\n # and appending them to result.\n for i in range(0, len(s1)):\n if not s1[i] in m:\n res = res + s1[i]\n else:\n m[s1[i]] = 2\n\n # finding characters of s2 that are not present in s1\n # and appending them to result.\n for i in range(0, len(s2)):\n if m[s2[i]] == 1:\n res = res + s2[i]\n\n if res == \"\":\n res = \"-1\"\n\n # returning the result.\n return res\n",
"updated_at_timestamp": 1729753320,
"user_code": "\n#User function Template for python3\n\nclass Solution:\n \n #Function to remove common characters and concatenate two strings.\n def concatenatedString(self,s1,s2):\n #code here\n "
}
|
eJydVNsOgjAM9UH/g+xZTXj1S0ycMRsM7xMVvMxo/Aj9Rt/8BrcB3mLLsBBC0p61pzvtuX69N2rWujf90zuQsYzThHQ84lPJ7EuaHhG7WASJCAeLNMn9LR1w0t5j0/tC8YDK3V6BSB1g3RA6LL5/ZTZQAWKN6yfWPJXzMc4DnTIMhYgimK8NK4JA1iIajsaT6WwuF/FytU7SzVa3iTF9BarEX7VwZd/qdDOjkueGUM7sFfgPbUxBGA7M5b+rCxYY2ABKn81DJsOEgfLGoUqW9P6j+WUjyhyvQWVH/WiQ8uFSHWRSJIbOKOoCWfPge8yAQiOjFmzpOMzw826dhhlZQm/VSVxoCPGyfeC0AT4PyZP1L+0HCPwXlA==
|
701,357
|
Minimum Cost of ropes
|
Given an array arr containing the lengths of the different ropes, we need to connect these ropes to form one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost.
Examples:
Input:
arr[] = [4, 3, 2, 6]
Output:
29
Explanation:
We can connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3. Which makes the array [4, 5, 6]. Cost of this operation 2 + 3 = 5.
2) Now connect ropes of lengths 4 and 5. Which makes the array [9, 6]. Cost of this operation 4 + 5 = 9.
3) Finally connect the two ropes and all ropes have connected. Cost of this operation 9 + 6 =15
Total cost for connecting all ropes is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes.
Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three rope of 3, 2 and 10), then connect 10 and 3 (we gettwo rope of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38.
Input:
arr[] = [4, 2, 7, 6, 9]
Output:
62
Explanation:
First, connect ropes 4 and 2, which makes the array [6, 7, 6, 9]. Cost of this operation 4 + 2 = 6.
Next, add ropes 6 and 6, which results in [12, 7, 9]. Cost of this operation 6 + 6 = 12.
Then, add 7 and 9, which makes the array [12,16]. Cost of this operation 7 + 9 = 16. And
finally, add these two which gives [28]. Hence, the total cost is 6 + 12 + 16 + 28 = 62.
Constraints:
1 ≤ arr.size() ≤ 20**5
1 ≤ arr[i] ≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1731573276,
"func_sign": [
"public int minCost(int[] arr)"
],
"initial_code": "\nimport java.io.*;\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine()); // Number of test cases\n\n while (t-- > 0) {\n String[] input = br.readLine().split(\" \");\n int[] a = new int[input.length]; // Change long to int\n\n for (int i = 0; i < input.length; i++) {\n a[i] = Integer.parseInt(\n input[i]); // Change Long.parseLong to Integer.parseInt\n }\n\n Solution ob = new Solution();\n System.out.println(\n ob.minCost(a)); // Ensure minCost accepts int[] as argument\n }\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n // Function to return the minimum cost of connecting the ropes.\n public int minCost(int[] arr) {\n // implementing MinHeap using priority queue.\n PriorityQueue<Integer> pq = new PriorityQueue<>();\n\n // adding elements to the priority queue\n for (int num : arr) {\n pq.add(num);\n }\n\n int res = 0;\n\n // using a loop while there is more than one element in priority queue.\n while (pq.size() > 1) {\n // storing the first and second numbers from priority queue.\n int first = pq.poll();\n int second = pq.poll();\n\n // adding their sum in result.\n res += first + second;\n\n // pushing the sum of first and second numbers in priority queue.\n pq.add(first + second);\n }\n\n // returning the result.\n return res;\n }\n}",
"updated_at_timestamp": 1731573276,
"user_code": "class Solution {\n // Function to return the minimum cost of connecting the ropes.\n public int minCost(int[] arr) {}\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731573276,
"func_sign": [
"minCost(self, arr: List[int]) -> int"
],
"initial_code": "# Initial Template for Python 3\nimport atexit\nimport io\nimport sys\nimport heapq\nfrom collections import defaultdict\n# Contributed by : Nagendra Jha\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\n\[email protected]\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\n\nif __name__ == '__main__':\n test_cases = int(input())\n for cases in range(test_cases):\n a = list(map(int, input().strip().split()))\n ob = Solution()\n print(ob.minCost(a))\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n # Function to return the minimum cost of connecting the ropes.\n def minCost(self, arr):\n # list containing our min heap.\n min_heap = []\n\n # inserting all elements in heap.\n for num in arr:\n heapq.heappush(min_heap, num)\n\n total_cost = 0\n\n # using a loop while there is more than one element in min heap.\n while len(min_heap) > 1:\n # storing the first and second numbers from min heap.\n val_1 = heapq.heappop(min_heap)\n val_2 = heapq.heappop(min_heap)\n\n val = val_1 + val_2\n\n # adding their sum in result.\n total_cost += val\n # pushing the sum first and second numbers in min heap.\n heapq.heappush(min_heap, val)\n\n # returning the result.\n return total_cost\n",
"updated_at_timestamp": 1731573276,
"user_code": "#User function Template for python3\n\nclass Solution:\n #Function to return the minimum cost of connecting the ropes.\n def minCost(self, arr: List[int]) -> int:\n \n # code here"
}
|
eJzNVE1LAzEQ9SD4Nx45F8nkO/0B3rwLVjzoHrysPWyhIEJ/hP5fk2lF0cy6tSq+XUggycubN5PZHD+fnxwxLs7K5PJB3fXL1aDmULToSc2guvWyuxm62+v71bBb0otePc7wYbNm7HUEkz6BMqURGfinoxjLdllw6ZXjt2aCKuvrYnSCz8gaSSNqBA2v4TSshqmxCoQUbTNEX6QYWDgERCTkUYq2HHz3l1PSzsZWqH8nFVScNCALcqASTABFUALlYofEH5q+ZgYSA5GBwIBnwDFgGTCMIqFCMs1V0uSFCw/z7+fljtRI0rb4Tkly1RhnmgVSj9sp5z2F8RJ9azJfFquVWtTu6dg9no7Pn22RNjfuPKwTZA6XmtFMZBa5SwWNsDco/7D3heaTEZPEGbp6On0B8mnIwQ==
|
703,853
|
LCM And GCD
|
Given two integers a and b, write a function lcmAndGcd() to compute their LCM and GCD. The function takes two integers a and b as input and returns a list containing their LCM and GCD.
Examples:
Input:
a = 5 , b = 10
Output:
10 5
Explanation:
LCM of 5 and 10 is 10, while their GCD is 5.
Input:
a = 14 , b = 8
Output:
56 2
Explanation:
LCM of 14 and 8 is 56, while their GCD is 2.
Constraints:
1 <= a, b <= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1730109383,
"func_sign": [
"static Long[] lcmAndGcd(Long a, Long b)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n Long A = Long.parseLong(S[0]);\n Long B = Long.parseLong(S[1]);\n\n Solution ob = new Solution();\n Long[] ptr = ob.lcmAndGcd(A, B);\n\n System.out.print(ptr[0]);\n System.out.print(\" \");\n System.out.println(ptr[1]);\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1731672080,
"user_code": "class Solution {\n static Long[] lcmAndGcd(Long a, Long b) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1730109383,
"func_sign": [
"lcmAndGcd(self, a , b)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n A, B = map(int, input().split())\n\n ob = Solution()\n ptr = ob.lcmAndGcd(A, B)\n\n print(ptr[0], ptr[1])\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def lcmAndGcd(self, A, B):\n arr = [0] * 2\n\n g = math.gcd(A, B) # gcd of 2 numbers.\n # product of 2 numbers divided by their gcd gives their lcm.\n l = (A * B) // g\n\n arr[0], arr[1] = l, g\n\n return arr\n",
"updated_at_timestamp": 1731672080,
"user_code": "#User function Template for python3\n\nclass Solution:\n def lcmAndGcd(self, a , b):\n # code here "
}
|
eJylVTtOAzEQpUCcw9o6Qp7/mJMgEUQBKWiWFImEhEAcAs5Cx9kwCZu/vZsw1Ug7fvvmzRv7/fzz++JsEddfObl5aR7b6XzWXIUGxi0gsah5CslNhQmhGYVm8jyd3M8mD3dP81lXTMIeLeYTigoMIY3bt3HbvI7CNmZaBln4yzAVMJefXTX+BrNRgAIoxC461FRHzbE+UkJNjiygQkHMPWel7kVdc0cI0RUBqEwUgY2dlC1ANDKG/I8CKlIUZ4rRgVISBPQhAqzT0qwO1fZKsMpKuu5XVhzgtBiU1aakmHmR2JCmZXjP0tPyakS6HlGp6YO1A90kPXZSw8QaPVLFT1vbtKttbbPi4lTM232E/Tf9++9VWFO1uhHM0RJx1Qq7XNNwshxVEmqenZwqdPtfpTelqAqRF4KhDLTvx+rdkm9rE0pZhfKOdU8A978BCIlQCSSaJs18+RQ5jzfu7cflD64V0oY=
|
705,701
|
Earthquake and the Paint Shop
|
Geek'sPaint Shop is one of the famous shop in Geekland,but 2014 Earthquake caused disarrangement of the items in his shop. Each item in his shop is a 40-digit alpha numeric code .
Now Chunky wants to retain the reputation of his shop, for that he has to arrange all the distinct items in lexicographical order.
Your task is to arrange the all the distinct items in lexicographical ascending order and print them along with their count.
Examples:
Input:
N = 3
A[] =
["2234597891 zmxvvxbcij 8800654113 jihgfedcba",
"1234567891 abcdefghij 9876543219 jihgfedcba",
"2234597891 zmxvvxbcij 8800654113 jihgfedcba"]
Output:
1234567891 abcdefghij 9876543219 jihgfedcba 1
2234597891 zmxvvxbcij 8800654113 jihgfedcba 2
Explanation:
We have 3 items (40 digit alphanumeric codes)
here. We arrange the items based on the
lexicographical order of their alpha-numeric
code. Distinct items are printed only once.
The count of the items describes how many
such items are there, so items that appear
more than once have their count greater than 1.
Input:
N = 2
A[] =
["3122049353 onafrnbhtr 9822827304 yzfhdgzcvx",
"2992299540 lpvkgykmlk 6946169466 vdqwvywwgg",
Output:
2992299540 lpvkgykmlk 6946169466 vdqwvywwgg 1
3122049353 onafrnbhtr 9822827304 yzfhdgzcvx 1
Explanation:
Out of the 2 items here no one is repeated.
Constraints:
1 ≤ N ≤ 10000
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"alphanumeric[] sortedStrings(int N, String A[])"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int N = Integer.parseInt(read.readLine());\n String s[] = new String[N];\n for (int i = 0; i < N; i++) s[i] = read.readLine();\n Solution ob = new Solution();\n alphanumeric ans[] = ob.sortedStrings(N, s);\n for (int i = 0; i < ans.length; i++)\n System.out.println(ans[i].name + \" \" + ans[i].count);\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class alphanumeric {\n public String name; // declaring a String variable to store the name\n public int count; // declaring an integer variable to store the count\n\n alphanumeric(String name, int count) { // constructor to initialize the name and count variables\n this.name = name; // assigning the passed name value to the name variable\n this.count = count; // assigning the passed count value to the count variable\n }\n};\n\nclass Solution {\n alphanumeric[] sortedStrings(int N, String A[]) {\n TreeMap<String,Integer> tm=new TreeMap<>(); // creating a TreeMap to store the strings and their counts\n\n for(int i=0;i<N;i++){ // iterating through the input array\n tm.put(A[i],tm.getOrDefault(A[i],0)+1); // adding each string to the TreeMap with its count incremented\n }\n\n alphanumeric ans[]=new alphanumeric[tm.size()]; // creating an alphanumeric array with the size of the TreeMap\n int in=0; // initializing an index variable\n\n for(Map.Entry<String,Integer> e:tm.entrySet()){ // iterating through the entries of the TreeMap\n ans[in++]=new alphanumeric(e.getKey(),e.getValue()); // creating a new alphanumeric object with the key and value of each entry and storing it in the ans array\n }\n\n return ans; // returning the ans array\n }\n};",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass alphanumeric {\n public String name;\n public int count;\n alphanumeric(String name, int count) {\n this.name = name;\n this.count = count;\n }\n};\nclass Solution {\n alphanumeric[] sortedStrings(int N, String A[]) {}\n};"
}
|
{
"class_name": null,
"created_at_timestamp": 1615292571,
"func_sign": [
"sortedStrings(self,N,A)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N = int(input())\n a = []\n for i in range(N):\n x = input()\n a.append(x)\n ob = Solution()\n ans = ob.sortedStrings(N, a)\n for i in ans:\n print(i.name, end=\" \")\n print(i.count)\n print(\"~\")\n",
"solution": "class Alphanumeric:\n # defining a class to store alphanumeric data with name and count attributes\n def __init__(self, name, count):\n self.name = name\n self.count = count\n\n\nclass Solution:\n def sortedStrings(self, N, A):\n # creating a dictionary to store counts of each element in A\n mp = {}\n for el in A:\n if el not in mp:\n mp[el] = 1\n else:\n mp[el] += 1\n\n # creating a list of Alphanumeric objects with empty names and counts 0\n ans = [Alphanumeric(\"\", 0) for _ in range(len(mp))]\n i = 0\n # iterating over the sorted keys of the dictionary\n for el in sorted(mp):\n # assigning the name and count attributes of the Alphanumeric object\n ans[i].name = el\n ans[i].count = mp[el]\n i += 1\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\n'''class alphanumeric:\n def __init__(self,name,count):\n self.name=name\n self.count=count\n'''\nclass Solution:\n def sortedStrings(self,N,A):\n #code here"
}
|
eJztW0mS2jAUzSIHUbHu6sLMZJNrpCpOpRjM2AhsbMCkksohkvtll2tEsgF9tSX5y3QzpN0r2vqSvt4f9Qw/3//++/Fd8vfpD/vw+VtlSldRWPlAKo5Lmy51avVGs9XudKvE33pBGEfT5YpUu512q9mo1xzSWw9H48ls/rRwqfhM6HLlB+sw2myhsFjCpWA5MA8I73eDTZ8uHh5dqnpKlKpZalx5IBVvt/IGoTf8uozCw9nx+xHHakdSs0KJr47HiUv/YGf6/kBkO7bZpv3B0GOTpzPCph/2JWzjXbznYyQd5GO6A4HdgWlWy2kUh4G39cmC9jeD3f5pPiOT8Wi47vExyTZCVbAY2EIsBjUWCqf6QkugpI6LJU/IQTidL09JxBIpy4Np/AgPJLedtZJiEsqwsvjZqPLlLEDiro+3v9aXnap0ZqXSkulnU6aONxz0ezBolE/V8AAwNUMufQ4UUctnhjiCdMEwE+rs4912E4XrwNcPSSGah4aUPvPQUEFAUsXNA8y4suLEcCg4ZmnO/Iyda3DHCr5nQZY7s1YYQl185jsgn1nUBflcixhJo76Az/KJBV3EmAwOOeWUUEQ6EdnkIAPhFRZTPYMxI/RQPXOpnCDFatXTckeJLHKnBavyiEuhVBZeMQ82CCcM1Ji49DSrK7BRbSRvL44ttoKqCmV0DpdKIILXjDX3A+wRuCxWMTnwzJ7BZfHgPJc2WZLL4n1JFYc6b5LbyBwvSeIUH1Pa2OzwZTRZAbov6HoA6DAUr1lci/W/mi6xaHeh1xoC+dI9qNIa16tReKDPK1H5UCsqmVZOXbZMfbjAWmNQzFTT1iJj6Q+Rm6gNcOq2rud71/H/NASPB+VjmcTNMiL3EJbYArm3ivdQlsulzw3hgdkIExzH/5N8i1RLC1eN9zZdv7Nte62gGTbielSbOsvqat/rrNvD1qg5bkzqs9rcSVbltSMbFWnAqPsa4UfplFM5g7F2sCxb7pAm4G3J7+236x2bF4w24bgfT2g0W0zny6cV3NFc/0QfhalmqDrmUr6xuT0IfGTJxxVDWDP0GloaFNPqYFsGBu/Tcj6dRZN4HI4CNn+7Zubbrbfs42YUMPPRSYy2PM7XMJ0PesvclKT1Z/nCpzcPl8N4DrYNRbeV2C4xXw4mYYyN+G0V50BJUUW4kFyqDRYldVzIE2SiQTa5SfHGRyFgrYwJQJ/Gm6ZmAUaL3l4wDKTipC4ufAReftQeehg3tCJCuaQLVUVa9jaFz/fIjIm5iqBKM9IvfTkidGc9Pkfe73Ad4wLJO1whT9dt7vl5oGVbV7zb4IIpXwN7sgefOKyqVRZC4iBVQgsObGqgDW2CzDLI7tn0hkJHxtj7mvE9iJT00PQNLxPIylxD53BzEZcpWVSxd+xSG76UYwV9m+qLJqLM93G52UFl4fvim7v/D+G8N5CqAqySe0ayyYUwVdHQBhe7eR76TniUpvJ+Aw5cUiolpVJSKiWl8oKUikXOuVF2xeadgtvHvFUYZV8rSN9axLxTeBWVji8V5FcHSjXNb39O7/uYZ+S/8FFKl2xXMbZLSgsl9VVSXyX1dUHqyyb6Sh6s5MFKHkxX5m/2BwWmLySXPzZ4Qz82cIy+oYiUgj9FuDQbXLLAl2WBS/b3vtlfI0HgvQhDIE7+slzBOdqZyQKNxq/MsghVVWg2zyFc1JNtvrJZUG81zlcH8ZZbtLw2zCl/4/fWf+N3N534WckquS62L5SkkpT05dfjP6N1F4s=
|
703,016
|
Form a palindrome
|
Given a string, find the minimum number of characters to be inserted to convert it to a palindrome.
Examples:
Input:
str = "abcd"
Output:
3
Explanation:
Inserted character marked with bold characters in
dcb
abcd, here we need minimum three characters to make it palindrome.
Input:
str = "aa"
Output:
0
Explanation:
"aa" is already a palindrome.
Constraints:
1 ≤ |str| ≤ 500
str contains only lowercase alphabets.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1618931138,
"func_sign": [
"static int countMin(String str)"
],
"initial_code": "import java.io.*;\nimport java.util.*; \n\nclass GFG{\n public static void main(String args[]) throws IOException { \n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n \n while(t-- > 0){\n String str = read.readLine();\n\n Solution ob = new Solution();\n \n System.out.println(ob.countMin(str));\n \nSystem.out.println(\"~\");\n}\n } \n} ",
"script_name": "GFG",
"solution": "//Backend complete function Template for Java\n\nclass Solution{\n static int countMin(String S)\n {\n int n = S.length();\n char[] str = S.toCharArray();\n \n // Create a table of size n*n. table[i][j]\n // will store minumum number of insertions\n // needed to convert str[i..j] to a palindrome.\n int table[][] = new int[n][n];\n int l, h, gap;\n\n // Fill the table\n for (gap = 1; gap < n; ++gap)\n for (l = 0, h = gap; h < n; ++l, ++h)\n table[l][h] = (str[l] == str[h])?\n table[l+1][h-1] :\n (Integer.min(table[l][h-1],\n table[l+1][h]) + 1);\n\n // Return minimum number of insertions\n // for str[0..n-1]\n return table[0][n-1];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n static int countMin(String str)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618931138,
"func_sign": [
"countMin(self, str)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n Str = input()\n\n solObj = Solution()\n print(solObj.countMin(Str))\n print(\"~\")\n",
"solution": "# Back-end function Template for python3\nclass Solution:\n\n def countMin(self, Str):\n # Finding the length of the string\n n = len(Str)\n\n # Creating a table to store the minimum number of palindromic cuts\n table = []\n # Initializing the table with 0\n for i in range(n):\n ro = [0] * n\n table.append(ro)\n\n # Iterating over the string to fill the table\n for gap in range(1, n):\n # Setting the starting and ending indexes for each substring\n h = gap\n l = 0\n\n while h < n:\n # Checking if the current substring is a palindrome\n if Str[l] == Str[h]:\n table[l][h] = table[l + 1][h - 1]\n else:\n # If not palindrome, calculating the minimum cuts required\n table[l][h] = min(table[l][h - 1], table[l + 1][h]) + 1\n\n # Updating the indexes\n l += 1\n h += 1\n\n # Returning the minimum number of cuts required for the entire string\n return table[0][-1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def countMin(self, str):\n # code here"
}
|
eJytk1FOhDAQhn3Qe5A+b8yy7mrWk5jIxgxtgQItpbRQMBoPoffVkF0TjcMGYh+aJu3888/0m7fLj7uri3E9rL8Oj89EKO0suQ9IGCkgq4Bwrzm1nD1Vzh6v1pF6jRR5WQW/3sdIQIgEGKCcgpmZRgIDKcZ9tkEazy+KMp6kmciLUqpK16axru18PyBCm920UsLZAhdYNqy1AHFMKWOcJ0maZpkQeV4UZSmlUlWldV0b0zTWOte2Xed93w9Yih1mahh877EuzPXl5hvb7pEkY7MhxHDE6jmF/QMpVKoJRMLbs2izo2DyTQwG+820Fvspxs6obVEAF364XOYDHaI/+IFpsBeQDfHUzJ1KPbxffwIHec95
|
702,719
|
Minimum Energy
|
Given an array containing positive and negative numbers. The array represents checkpoints from one end to the other end of the street. Positive and negative values represent the amount of energy at that checkpoint. Positive numbers increase the energy and negative numbers decrease. Find the minimum initial energy required to cross the street so that the energy level never becomes 0 or less than 0.
Examples:
Input:
arr[] = [4, -10, 4, 4, 4]
Output:
7
Explanation:
By having an initial energy of 7 we can make sure that all the checkpoints are visited and the fuel never reaches 0 or less value.
Input:
arr[] = [3, 5, 2, 6, 1]
Output:
1
Explanation:
We need at least 1 initial energy to reach first checkpoint
Constraints:
1 ≤ arr.size() ≤ 10**6
-10**3≤ arr[i] ≤ 10**3
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617732763,
"func_sign": [
"public int minEnergy(int a[])"
],
"initial_code": "import java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int t = Integer.parseInt(scanner.nextLine());\n\n while (t-- > 0) {\n String line = scanner.nextLine();\n String[] elements = line.split(\" \");\n int arr[] = new int[elements.length];\n\n for (int i = 0; i < elements.length; i++) {\n arr[i] = Integer.parseInt(elements[i]);\n }\n\n Solution ob = new Solution();\n System.out.println(ob.minEnergy(arr));\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n public int minEnergy(int a[]) {\n int initMin = 0;\n int curr = 0;\n // Iterate through the array\n for (int i = 0; i < a.length; i++) {\n curr += a[i];\n // If current energy is less than or equal to 0\n if (curr <= 0) {\n // Increase initial minimum energy by the absolute value of current\n // energy + 1\n initMin += Math.abs(curr) + 1;\n // Reset current energy to 1\n curr = 1;\n }\n }\n // If no adjustment was made, at least 1 unit of energy is required\n return initMin == 0 ? 1 : initMin;\n }\n}\n",
"updated_at_timestamp": 1727947200,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int minEnergy(int a[]) {\n // Your code goes here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617732763,
"func_sign": [
"minEnergy(self, arr)"
],
"initial_code": "# Initial Template for Python 3\ndef main():\n T = int(input())\n\n while T > 0:\n # Convert input to list of integers\n a = list(map(int, input().strip().split()))\n print(Solution().minEnergy(a))\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n # Function to calculate minimum energy needed.\n def minEnergy(self, arr):\n initMin, curr = 0, 0\n\n # Iterating over the array.\n for i in range(len(arr)):\n curr += arr[i]\n\n # If current energy becomes negative or zero, adjust the initial minimum energy.\n if curr <= 0:\n initMin += abs(curr) + 1\n curr = 1 # Reset current energy to 1\n\n # If no adjustment was made, at least 1 unit of energy is required.\n return initMin if initMin > 0 else 1\n",
"updated_at_timestamp": 1727947200,
"user_code": "#User function Template for python3\n\nclass Solution:\n # Function to calculate minimum energy needed.\n def minEnergy(self, arr):\n# Your code goes here"
}
|
eJyVVLtOxDAQpID/GLm+RV4/EocvQeIQBaSgCVfkJCSExEdAT8dvss7dCQG2Y8fJZi1lx5uZsd/OP74uzpbr+lOSmxf1OO32s7qC4u3EIAMLYhiQhQM5eJBHB+rQg3oEUMAAGsBabaDG5914P48Pd0/7+QhktpN63eAPtNZaqoZYF7Ml5tMMNKegj1V1IwesdQYbhTtLAafBvPRp/OGpnBTI8OmWbRRMZGILI11akVA0DEK8czkknwJy0QohGoC1pD+DOMCYDFafgtILWyi8Gr0kRpVgY+IkRMaok9DHJEgYsrS5NG0n9/kT3Oqs5NOUnchmvm6hPpS4D/o/+6J89bJt2843OVNMU91HxWGxroE4IKPzQcVfYjaeOuR9w++kl+T1NW/fL78BBlN3Ug==
|
704,788
|
The Palindrome Pattern
|
Given a two-dimensional integer array arr of dimensions n x n, consisting solely of zeros and ones, identify the row or column (using 0-based indexing) where all elements form a palindrome. If multiple palindromes are identified, prioritize the palindromes found in rows over those in columns. Within rows or columns, the palindrome with the smaller index takes precedence. The result should be represented by the index followed by either 'R' or 'C', indicating whether the palindrome was located in a row or column. The output should be space-separated. If no palindrome is found, return the string -1.
Examples:
Input:
arr[][] = [[1, 0, 0],
[0, 1, 0],
[1, 1, 0]]
Output:
1 R
Explanation:
In the first test case, 0-1-0 is a palindrome
occuring in a row having index 1.
Input:
arr[][] = [[1, 0],
[1, 0]]
Output:
0 C
Explanation:
1-1 occurs before 0-0 in the 0th column. And there is no palindrome in the two rows.
Constraints:
1<= arr.size <= 50
0 <= arr[i][j] <= 1
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public String pattern(int[][] arr)"
],
"initial_code": "// Initial Template for Java\n\n// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n\n Scanner sc = new Scanner(System.in);\n\n Solution ob = new Solution();\n int t = sc.nextInt();\n while (t-- > 0) {\n int n = sc.nextInt();\n int[][] a = new int[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n a[i][j] = sc.nextInt();\n }\n }\n String ans = ob.pattern(a);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public String pattern(int[][] arr) {\n // Code here\n int n = arr.length;\n int[] temp = new int[n];\n int flag = 0;\n String ans = \"\";\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n temp[j] =\n arr[i][j]; // Copying each row of the 2D array to a temporary array.\n }\n\n if (isPalindrome(temp)) { // Checking if the row is a palindrome.\n flag = 1;\n ans = i + \" \"\n + \"R\"; // Setting the answer as the row index and \"R\" to indicate\n // the pattern is in a row.\n break;\n }\n }\n\n if (flag == 0) {\n for (int j = 0; j < n; j++) {\n for (int i = 0; i < n; i++) {\n temp[i] = arr[i][j]; // Copying each column of the 2D array to a\n // temporary array.\n }\n\n if (isPalindrome(temp)) { // Checking if the column is a palindrome.\n flag = 1;\n ans = j + \" \"\n + \"C\"; // Setting the answer as the column index and \"C\" to\n // indicate the pattern is in a column.\n break;\n }\n }\n }\n\n if (flag == 0)\n ans = \"-1\"; // If no palindrome pattern is found, set answer as -1.\n\n return ans; // Return the answer.\n }\n\n // Function to check if the given array is a palindrome.\n private boolean isPalindrome(int[] arr) {\n int n = arr.length;\n int mid = n / 2;\n\n for (int i = 0; i < mid; i++) {\n if (arr[i] != arr[n - 1 - i]) {\n return false;\n }\n }\n\n return true;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public String pattern(int[][] arr) {\n // Code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"pattern(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n ob = Solution()\n t = int(input())\n for _ in range(t):\n n = int(input())\n L = list(map(int, input().split()))\n a = list()\n c = 0\n for i in range(0, n):\n X = list()\n for j in range(0, n):\n X.append(L[c])\n c += 1\n a.append(X)\n ans = ob.pattern(a)\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n def pattern(self, arr):\n n = len(arr)\n temp = [0] * n\n flag = 0\n ans = \"\"\n\n for i in range(n):\n for j in range(n):\n # Copying each row of the 2D array to a temporary array.\n temp[j] = arr[i][j]\n # Checking if the row is a palindrome.\n if self.is_palindrome(temp):\n flag = 1\n # Setting the answer as the row index and \"R\" to indicate the pattern is in a row.\n ans = str(i) + \" \" + \"R\"\n break\n\n if flag == 0:\n for j in range(n):\n for i in range(n):\n # Copying each column of the 2D array to a temporary array.\n temp[i] = arr[i][j]\n # Checking if the column is a palindrome.\n if self.is_palindrome(temp):\n flag = 1\n # Setting the answer as the column index and \"C\" to indicate the pattern is in a column.\n ans = str(j) + \" \" + \"C\"\n break\n\n if flag == 0:\n ans = \"-1\" # If no palindrome pattern is found, set answer as -1.\n\n return ans # Return the answer.\n\n # Function to check if the given array is a palindrome.\n def is_palindrome(self, arr):\n n = len(arr)\n mid = n // 2\n\n for i in range(mid):\n if arr[i] != arr[n - 1 - i]:\n return False\n\n return True\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def pattern (self, arr):\n # code here\n"
}
|
eJxrYJn6jY0BDCLeAxnR1UqZeQWlJUpWCkqGMXmmMXmGCgZAaAjGCBIG0cWAtJKOglJqRUFqcklqSnx+aQnMNIWgmLy6mDylWh0FVEtMYvIQBsEMNUQ2GoeRBjiNNIMYiepuAzSXI6xDtRJZ1hCH1UYKzjisNke12gDNcuwy2ByGLTygKkkODwtYPCLHm6ECeiwiO8FAAdnJaHGMphbdNCzpg2QngxDJmoxA/iQvyRjBUyEOrbqG+Cw1wJNYcOo0huhEiWlyAgqUgwi6gigTSNOLK6iIzuMUZXKYs1F9AErqZKQcJBMQyQiecygO2RhoiqYkjqharlEhhMgywRBrIMPzHz3KboQDY6foAQBdPdSX
|
701,428
|
Longest Increasing Subsequence
|
Given an array a[ ] of n integers, find the Length of the Longest Strictly Increasing Subsequence.
Examples:
Input:
n = 6, a[ ] = {5,8,3,7,9,1}
Output:
3
Explanation:
There are more than one
LIS
in this array.
One such Longest increasing subsequence is {5,7,9}.
Input:
n = 16, a[ ] = {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}
Output:
6
Explanation:
There are more than one LIS in this array.
One such Longest increasing subsequence is {0,2,6,9,13,15}.
Constraints:
1 ≤ n ≤ 10**4
0 ≤ a[i] ≤ 10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1730923336,
"func_sign": [
"static int longestSubsequence(int arr[])"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass Geeks {\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine()); // Number of test cases\n for (int g = 0; g < t; g++) {\n String[] str = (br.readLine())\n .trim()\n .split(\" \"); // Read the input for the current test case\n int arr[] = new int[str.length];\n // Convert input string into an integer array\n for (int i = 0; i < str.length; i++) {\n arr[i] = Integer.parseInt(str[i]);\n }\n // Call the solution method and print the result\n System.out.println(new Solution().longestSubsequence(arr));\n }\n }\n}",
"script_name": "Geeks",
"solution": "None",
"updated_at_timestamp": 1730923336,
"user_code": "\n\nclass Solution {\n // Function to find length of longest increasing subsequence.\n static int longestSubsequence(int arr[]) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1730923336,
"func_sign": [
"longestSubsequence(self, arr)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n for _ in range(int(input())):\n a = [int(x) for x in input().split()]\n ob = Solution()\n print(ob.longestSubsequence(a))\n",
"solution": "class Solution:\n\n def longestSubsequence(self, arr):\n # To store the increasing subsequence\n res = []\n\n # Iterate through each number in the input array\n for n in arr:\n # If res is empty or n is greater than the last element in res, add it\n if not res or res[-1] < n:\n res.append(n) # Add n to the subsequence\n else:\n # Find the position in res where n can replace an element\n idx = self.binarySearch(res, n)\n # Replace the element at the found index with n\n res[idx] = n\n\n # Return the length of the longest subsequence\n return len(res)\n\n # Binary search to find the appropriate position for the element in res\n def binarySearch(self, arr, target):\n left, right = 0, len(arr) - 1\n\n # Perform binary search\n while left <= right:\n mid = (left + right) // 2\n if arr[mid] == target:\n return mid\n elif arr[mid] > target:\n right = mid - 1 # Search left half\n else:\n left = mid + 1 # Search right half\n\n # Return the insertion index where n should go\n return left\n",
"updated_at_timestamp": 1730923336,
"user_code": "#User function Template for python3\n\nclass Solution:\n #Function to find length of longest increasing subsequence.\n def longestSubsequence(self, arr):\n # code here\n \n"
}
|
eJylVD0PgjAUdNAf4OZ46UxMW/ko/hITMQ7K4IIMkJgYE3+E/l8fVAahBYqvwzFwj7t3fTzn79ViVtduSQ/7O7tkeVmwLZhIMgGJDXwECBFBIYbgzANLb3l6KtLz8VoWzds8ydjDQ6sBJ44ibkg9fOolIWwNTPwAneNCd/qW4HVNoCCuS4PSEGkINbipNkwdA+p65Q2gizaO5thmK000SXZCslIZIW8B+Yot/KDDtwk0qHPzMi2U/j1Q4xKVf0b6vW4TrpwxHxJTL+uEaO1/hBEb8zvYlhVUXhB35blvlGlqY+Z0eK0/fERlKw==
|
703,648
|
Another Matrix Game
|
Given a string S which contains only small letters. The task is to make a square matrix from string S. Then perform the following operations.1. In each column delete the characters which occur more than one.2. Let the characters in order be abcd....wxyz then print them in order azbycxdw.... For example, after operation 1 if the remaining characters in a column are cedjki then after sorting they become cdeijk , now when printed in the given order the output will be ckdjei. If there's no character remaining Print 0.
Examples:
Input:
S =
"adgkbdhlceilcfjm
"
Output:
abefgjhikm
Explanation:
Matrix will be
a d g k
b d h l
c e i l
c f j m
In 1st column 'c', in 2nd column 'd' and in
4th column 'l' has occurred more than once.
So after deleting them and sorting the
remaining characters the matrix become
a - g k
b - h -
- e i -
- f j m
So after operation 2 we get 'ab' from 1st
column, 'ef' from 2nd column, 'gjhi' from
3rd column and 'km' from 4th column. Appending
all of them we get the output as "abefgjhikm".
Input:
S =
"
abcabcabc
"
Output:
0
Explanation:
Matrix will be
a b c
a b c
a b c
So, There will be no letters remaining
and the output will be 0.
Constraints
1 <= |S| <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static String matrixGame(String S)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n \n String S = read.readLine();\n\n Solution ob = new Solution();\n\n System.out.println(ob.matrixGame(S));\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "//User function Template for Java\n\nclass Solution {\n static String matrixGame(String S){\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"matrixGame(self, S)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n S = input()\n\n ob = Solution()\n print(ob.matrixGame(S))\n print(\"~\")\n",
"solution": "class Solution:\n def matrixGame(self, S):\n ans = \"\"\n n = int(math.sqrt(len(S)))\n mat = [['0' for i in range(n)] for j in range(n)]\n k = 0\n\n for i in range(n):\n for j in range(n):\n mat[i][j] = S[k]\n k += 1\n\n for i in range(n):\n freq = [0]*26\n s = \"\"\n for j in range(n):\n freq[97-ord(mat[j][i])] += 1\n for j in range(n):\n if freq[97-ord(mat[j][i])] == 1:\n s += mat[j][i]\n\n if(len(s) % 2):\n for j in range(len(s)//2):\n ans += s[j]\n ans += s[len(s)-j-1]\n ans += s[len(s)//2]\n else:\n for j in range(len(s)//2):\n ans += s[j]\n ans += s[len(s)-j-1]\n\n if len(ans) == 0:\n ans = '0'\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def matrixGame(self, S):\n # code here"
}
|
eJzVVtuK1EAQ9UF80n9Y5nkRffVLBEek7/f7PaL4Efq/9u4Ku8pmnGQHwYakk1Qndaqrzql8e/7j1ctnt+P9i3nx4fNBWF/y4d3V4e3RAogwoYwLqbSx7vTt0R6urw6ke4IywZ9cyb8+xKTBXFkitKPSAKYs5NohcbRf5ztfrq9OOvUhplxq62MZvdWSUwzeWaOVFJxRghEEq66B4N61CrlwvjbEpA2lY6pMzGOh2KgcB0NWltBX0Cw7xiqcN2shAwgRwpgQShnjXAgpldLaGGud8z6EGFPKuZRaW+t9jBNOQMWROwUqSdxp2EgSfk40C29Qp1mGObEig8WDFRXtCqjf9/5hVvSqaRWUgbkAyy0qFTrh8EyGl560joMKtA8SdWQzJUknvgCWzdbieGD44/n6RiWuJhKYhZlIUJnFQTuuyk0kpGmfOKDdhCwgGzYWiVazt3VsL5BVTtxbThpvLOsbAUUOejCIZIlm4QirmiwQmOiWHZSEml484pTZUQMWjLulRTI9etATVSugQyOTZmVSDyQ8UUwQS0cVWrP0m/Nk8CQwTuB+4SrE0CbZK2rEMQ4riZ5KC2MGeGY7DzMKBqoIGuSJDdxyPI3Ce4M/S2UfYPyLEGAIpjqSs+p2Zx3vLuiLJQTfLdhAnJ2h7pYZQwS0VCLHFPZc75TbvTV1+8l4tk6zCJvlCXUnMh5eFrIEVSnY3rn+fUw7eqWaqgYUFhTqqWtQE8mQmcp2ofajLtR/1On+s8KZyzWOzayEU3gwQgBPDQIIbq35c368HltxtP8PWx6BSO4wyo1tgl+2T3z8/vonEWewvg==
|
705,117
|
Grouping Of Numbers
|
One day Jim came across array arr[] of N numbers. He decided to divide these N numbers into different groups. Each group contains numbers in which sum of any two numbers should not be divisible by an integer K. Print the size of the group containing maximum numbers.There will be atleast one number which is not divisible by K.
Examples:
Input:
N =
4,
K =
8
arr[] =
{1, 7, 2, 6}
Output:
2
Explanation:
The group of numbers which can be formed
are: (1),(2),(7),(6),(1,2),(1,6),(7,2),(7,6).
So,the maximum possible size of the group is 2.
Input:
N =
2,
K =
3
arr[] =
{1, 2}
Output:
1
Explanation:
The group of numbers which can be formed
are: (1),(2). So,the maximum possible size
of the group is 1.
Constraints:
1 ≤ N,K,arr[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int maxGroupSize(int[] arr, int N, int K)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n \n int N = Integer.parseInt(S[0]);\n int K = Integer.parseInt(S[1]);\n \n String S1[] = read.readLine().split(\" \");\n \n int arr[] = new int[N];\n \n for(int i=0; i<N; i++)\n arr[i] = Integer.parseInt(S1[i]);\n\n Solution ob = new Solution();\n System.out.println(ob.maxGroupSize(arr,N,K));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static int maxGroupSize(int[] arr, int N, int K) {\n int a[] = new int[K]; // Create an array to store the frequencies of remainders\n // Count the frequencies of remainders in the original array\n for (int i = 0; i < N; i++) a[arr[i] % K]++;\n int ans = 0; // Initialize a variable to store the maximum group size\n // Iterate through the remainders up to K/2\n for (int i = 1; i <= K / 2; i++) {\n if (i != K - i) // If the remainders are not equal\n ans += Math.max(a[i], a[K - i]); // Add the maximum frequency of the two remainders\n else {\n if (a[i] != 0) // If the remainder is equal to K/2 and not zero\n ans++; // Increment the maximum group size by 1\n }\n }\n if (a[0] != 0) // If the frequency of the remainder 0 is not zero\n ans++; // Increment the maximum group size by 1\n return ans; // Return the maximum group size\n }\n}\n",
"updated_at_timestamp": 1730477474,
"user_code": "class Solution {\n static int maxGroupSize(int[] arr, int N, int K) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxGroupSize(self, arr, N, K)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, K = map(int, input().split())\n arr = list(map(int, input().split()))\n\n ob = Solution()\n print(ob.maxGroupSize(arr, N, K))\n print(\"~\")\n",
"solution": "class Solution:\n def maxGroupSize(self, arr, N, K):\n # create a list to store the count of remainder values\n a = [0] * (K)\n # iterate through each element in the array\n for i in range(N):\n # increment the count of the remainder value in the list\n a[arr[i] % K] += 1\n ans = 0\n # iterate through the possible pairs of remainder values\n for i in range(1, K // 2 + 1):\n # if the remainder values are not equal\n if i != K - i:\n # add the maximum count between the two remainder values to the answer\n ans += max(a[i], a[K - i])\n else:\n # if the remainder values are equal\n if a[i] != 0:\n # add 1 to the answer\n ans += 1\n # if there are elements with remainder 0, add 1 to the answer\n if a[0] != 0:\n ans += 1\n # return the final answer\n return ans\n",
"updated_at_timestamp": 1730477474,
"user_code": "#User function Template for python3\n\nclass Solution:\n def maxGroupSize(self, arr, N, K):\n # code here "
}
|
eJydk8FKxTAQRV2I7vyGS9cPySSdJvVLBCsutAs38S364IEofoT+rze1oEXS17SFkrbMnZtzJx/nX1cXZ+N1e8nF3Wv1HPeHobpBJV0UWD6qHar+uO8fh/7p4eUw/P5/72L1tsO8SKFdNJjuwmKHuos1AsQWVoqBmNEyKAJFA0+dll8zSk1GiYVd9JAalmoBTlGXumkmMy3tUAE+U+8y9R4uwWiSfwtRSKCbQhNhjI/dlSgoJBBHrUKVVNhFS6zkSrAkS0JkS7iJbg6vzQWlsCaNiSVXiimCph0SM7W9ouWrgTNQA2/QluZX1kA3dPiPRNYxycX9V1DCTNK5E5paeCBs0JA/FP70QAsWR7peBW3c4spJ2kBN3HZupePDTuUzOgvnx3xqlRJiRFjMaGksnW4n0k6695/X35RFpjU=
|
703,831
|
Reverse Bits
|
Given a number x, reverse its binary form and return the answer in decimal.
Examples:
Input:
x =
1
Output:
2147483648
Explanation:
Binary of 1 in 32 bits representation-
00000000000000000000000000000001
Reversing the binary form we get,
10000000000000000000000000000000,
whose decimal value is 2147483648.
Input:
x =
5
Output:
2684354560
Explanation:
Binary of 5 in 32 bits representation-
00000000000000000000000000000101
Reversing the binary form we get,
10100000000000000000000000000000,
whose decimal value is 2684354560.
Constraints:
0 <= x < 2**32
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static Long reversedBits(Long x)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n Long X = Long.parseLong(read.readLine());\n\n Solution ob = new Solution();\n System.out.println(ob.reversedBits(X));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function to reverse the bits of a Long integer\n static Long reversedBits(Long X) {\n if (X == 0) return 0L;\n\n // Convert Long to binary string\n String s = Long.toBinaryString(X);\n while (s.length() < 32) // to ensure we have 32 bits representation\n s = \"0\" + s;\n\n // Reverse the binary string\n s = new StringBuilder(s).reverse().toString();\n\n // Parse binary string to Long integer\n Long ans = Long.parseLong(s, 2); // Parsing from binary to decimal\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n static Long reversedBits(Long x) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"reversedBits(self, x)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n X = int(input())\n\n ob = Solution()\n print(ob.reversedBits(X))\n print(\"~\")\n",
"solution": "class Solution:\n def reversedBits(self, x):\n # Change the Integer to its Binary Form\n s = bin(x)\n s = s[2:]\n\n y = 32 - len(s)\n\n s = '0' * y + s # Adding leading zeroes to fill 32 bits\n\n # Reverse the binary\n s = s[::-1]\n\n ans = int(s, 2) # Change binary to its Integer Form.\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def reversedBits(self, x):\n # code here "
}
|
eJyllMFOwzAMhjkgnmPqeUKO7cQOT4JEEQfYgUvZYZOQ0CYeAt6JG6+E244CXR0Yq6oobePf9p8vfT59fT876a7LN5tcPVX3zXK9qi5mFdSN3aFuqvmsWjwuF7erxd3Nw3q1+15t5rNvy7FuMMZ2SG4Io2jIAGrC27pRUk2g3XykRnVDKMm+pRjJFAMFEHSVd6u2Q5jNQiLlKXF7GQBtRGBbypAt1Arz5RGyhIi9rAVF6ZNFZNQ+GyYMPJkudEY6yuBE+L5bGmGlxJPGtaEgJBy07dDTcEIHbSnsYeacxEYvPVOw7ZAU/fSaiEKI5HWPSZkiF1Bym7fsPbi/1EA55CgC6vJ3EICBIBrNgsdBqEdjqIwFEDs2hpNdhiSwOaiUdwdrJNaKFDndd7Rf/gczR4iPHhNQliwyWZZra4tG4eB/MXvsBpi/wJTB3YLu/iTcB81nv/wH6JrMB5KlmVMWln+zNVj78/TuSiiWdOD/d9S97lVcba5fzj8A4SwFlQ==
|
712,068
|
Largest odd number in string
|
Given a string S, representing a large integer. Return thelargest-valued oddinteger (as a string) that is substring of the given string S.
Examples:
Input:
s = "504"
Output:
"5"
Explanation:
The only subtring "5" is odd number.
Input:
s = "2042"
Output:
""
Explanation:
All the possible non-empty substring have even value.
S
only consists of digits and does not contain any leading zeros.
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1662723966,
"func_sign": [
"String maxOdd(String s)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass Main {\n // Driver code\n public static void main(String[] args) throws Exception {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim());\n while (t-- > 0) {\n String s = br.readLine();\n Solution obj = new Solution();\n System.out.println(obj.maxOdd(s));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n\n String maxOdd(String s) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1663738757,
"func_sign": [
"maxOdd(self, s)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n s = input()\n ob = Solution()\n print(ob.maxOdd(s))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find the rightmost odd digit in the string.\n def maxOdd(self, s):\n p = -1\n # iterating over the string from the rightmost digit.\n for i in range(len(s)-1, -1, -1):\n # if the current digit is odd, store its index and break the loop.\n if int(s[i]) & 1:\n p = i\n break\n # if no odd digit is found, return an empty string.\n if p == -1:\n return ''\n # return the string from start till the rightmost odd digit index.\n return s[:p+1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def maxOdd(self, s):"
}
|
eJxrYJn6n4sBDCJ+ABnR1UqZeQWlJUpWCkqGMXkGaEBJR0EptaIgNbkkNSU+v7QEqjImry4mT6lWRwG/bvwAqAGH8SSbQ7FrcDoFh9mGxqbmljg1QWWpEEbIwJhK4YVmJpVdCQSmNHAoxFjsbiU58oyMTUzNzC0sceuEK6Fu+FA9ZHCFiZGJmQXJ4QI2EZG4cViJ3wtEZ0aEI7FbQ3IGJiFs6eFIYt1PG4eT5ARiNJCacgddEMPsGQxhPRDhTLorEarp4WusgjQMCtLdT4wGsgp4chowVKijMcTIqpyo0frC6jxaNCHg9WXsFD0AP6yoMg==
|
702,680
|
Palindrome Array
|
Given an array arr, the task is to find whether the arr ispalindrome or not.If thearris palindrome then returntrueelse return false.
Examples:
Input:
arr = [1, 2, 3, 2, 1]
Output:
true
Explanation:
Here we can see we have [1, 2, 3, 2, 1] if we reverse it we can find [1, 2, 3, 2, 1] which is the same as before. So, the answer is
true
.
Input:
arr = [1, 2, 3, 4, 5]
Output:
false
Explanation:
Here we can see we have [1, 2, 3, 4, 5] if we reverse it we find [5, 4, 3, 2, 1] which is the not same as before. So, the answer
false
.
Constraints:
1 ≤ arr.size ≤ 10**6
1 ≤ arr[i] ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617362265,
"func_sign": [
"public static boolean isPerfect(int[] arr)"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass Main {\n public static void main(String args[]) throws IOException {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine().trim());\n\n while (t-- > 0) {\n String line = read.readLine().trim();\n String[] numsStr = line.split(\" \");\n int[] nums = new int[numsStr.length];\n for (int i = 0; i < numsStr.length; i++) {\n nums[i] = Integer.parseInt(numsStr[i]);\n }\n Solution obj = new Solution();\n boolean res = obj.isPerfect(nums);\n if (res)\n System.out.println(\"true\");\n\n else\n System.out.println(\"false\");\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n public static boolean isPerfect(int[] arr) {\n int n = arr.length;\n // Checking elements from both ends of the array\n for (int i = 0; i < n / 2; i++) {\n // If any two elements are not equal, array is not perfect\n if (arr[n - i - 1] != arr[i]) return false;\n }\n // If all elements checked and they are equal, array is perfect\n return true;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "\nclass Solution {\n public static boolean isPerfect(int[] arr) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617362265,
"func_sign": [
"isPerfect(self, arr : List[int]) -> bool"
],
"initial_code": "if __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n arr = list(map(int, input().strip().split()))\n obj = Solution()\n res = obj.isPerfect(arr)\n if res:\n print(\"true\")\n else:\n print('false')\n",
"solution": "from typing import List\n\n\nclass Solution:\n def isPerfect(self, arr: List[int]) -> bool:\n n = len(arr)\n # loop through half of the array\n for i in range(0, n // 2):\n # check if the element at the current index is equal to the element at the opposite index\n if (arr[n - i - 1] != arr[i]):\n # return False if the elements are not equal\n return False\n # return True if all elements are equal\n return True\n",
"updated_at_timestamp": 1727947200,
"user_code": "\nfrom typing import List\nclass Solution:\n def isPerfect(self, arr : List[int]) -> bool:\n # code here\n \n"
}
|
eJylU9sKgkAQ7aH+47DPEa7rqttLvxFkRJRBECalEETQR9T/Nt4qK6nJWXcdVs+Z3Zkz5+511OvkNvbJmRzFOorTRAwhZBBJ2DSk6EOEhzhcJOFytk2T8odkl4ZBJE591FEGPjyaplgb0Kv5Zv8RruFAZWFpKvI1M7y0YFtQ+UOOtJh4BU0Hzw6vodixK4OpDI9NLhtqg4u2laNdzzcwvudqR9nEUe2xT1LWAvfqMBk0XMqoRyu7nvntixTUxfVJLPTlr2S9iuZHITSq+IXQyIqyfLcgtkwuJvLdP3qjXXOYLP/8npbPMdEUtBmOt4u36Qy2+r9laXoZ3AAHQ4E1
|
703,337
|
Maximize the sum of selected numbers from a sorted array to make it empty
|
Given a array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence ofAi-1 (if exists), and Aieach from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of the selected numbers.
Examples:
Input:
arr[ ] = {1, 2, 2, 2, 3, 4}
Output:
10
Explanation:
We select 4, so 4 and 3 are deleted leaving us with {1,2,2,2}.
Then we select 2, so 2 & 1 are deleted. We are left with{2,2}.
We select 2 in next two steps, thus the sum is 4+2+2+2=10.
Input:
arr[ ] = {1, 2, 3}
Output:
4
Explanation:
We select 3, so 3 and 2 are deleted leaving us with {1}. Then we select 1, 0 doesn't exist so we delete 1. thus the sum is 3+1=4.
Constraints:
1 ≤ N ≤ 10**5
1 ≤ A[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Complete",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int maximizeSum(int arr[], int n)"
],
"initial_code": "//Initial Template for Java\n\n//Initial Template for Java\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\nclass Array {\n \n // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t String line = br.readLine();\n\t\t String[] element = line.trim().split(\"\\\\s+\");\n\t\t int sizeOfArray = Integer.parseInt(element[0]);\n\t\t \n\t\t int arr [] = new int[sizeOfArray];\n\t\t \n\t\t line = br.readLine();\n\t\t String[] elements = line.trim().split(\"\\\\s+\");\n\t\t for(int i = 0;i<sizeOfArray;i++){\n\t\t arr[i] = Integer.parseInt(elements[i]);\n\t\t }\n\t\t Arrays.sort(arr);\n\t\t Complete obj = new Complete();\n\t\t int ans = obj.maximizeSum(arr, sizeOfArray);\n\t\t System.out.println(ans);\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}\n\n",
"script_name": "Array",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Complete{\n \n \n // Function for finding maximum and value pair\n public static int maximizeSum (int arr[], int n) {\n //Complete the function\n }\n \n \n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maximizeSum(self,arr, n)"
],
"initial_code": "# Initial Template for Python 3\nfor _ in range(0, int(input())):\n n = int(input())\n arr = list(map(int, input().strip().split()))\n arr.sort()\n ob = Solution()\n ans = ob.maximizeSum(arr, n)\n print(ans)\n print(\"~\")\n",
"solution": "from collections import defaultdict\n\n\nclass Solution:\n\n # Function to maximize the sum according to given conditions.\n def maximizeSum(self, arr, n):\n # Creating a dictionary to store the frequency of each element.\n ans = defaultdict(int)\n a = [False] * n\n sum = 0\n\n # updating the frequency of each element in the dictionary.\n for el in arr:\n ans[el] += 1\n\n # iterating the elements of the array in reverse order.\n for i in range(n - 1, -1, -1):\n # if the element is not used yet.\n if a[i] == False:\n # mark it as used and add it to the sum.\n a[i] = True\n sum += arr[i]\n\n # if there are more elements with value arr[i]-1,\n # mark them as used and reduce their frequency by 1.\n if (ans[arr[i] - 1] > 0):\n a[i - ans[arr[i]]] = True\n ans[arr[i] - 1] -= 1\n\n return sum\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n def maximizeSum (self,arr, n) : \n #Complete the function\n"
}
|
eJzt1s1uEzEQB3AOHHkIay9cKuSxPeMxT4JEEAfIgUvoIZWQEFUfAt4X+7/2lnzMKkQ5IepfpEptxjPjtddPL3+9fvUCP+9c/eX99+nL7v5hP711E2125NvHVQVD+8jTnZu23+63n/bbzx+/Puz7Vzhudo+b3fTjzh0F4s2OnWBkhJgDtuA0BCOqeiNq8O3jqIBCHsQRO0oQIWAWjzqsCkjMyWoJ9et1hDoiRuqDHffSRnFz11De31YVW9PZdemkhjAqoV7PWCHF/Lnmwcgq1jzrP1iVprLS1uMquY/nBZyrNIKLGLH5IHY6if0cXZcHxP/xmCz1x9GXpVMyVl77E1EfjYagTln7kVxgI+WYaDXnsfLnujJyl74CRv5nk5dhZN5z7gkb2YZibjW/tPi0yYcPaTnX23jSWznsrdXeOeG5ya3PIJBBoTTRA0GACAkYBDIolCZ5IAgQIQGDQAaF0rCvrA0RmFd76luz6kYroJBBgCFBhAAEvtECChkEGBJECEDgm1xAIYMAQ4IIAQh8IwUUMggwJIgQgMA3XEAhgwBDgggBqLI2mXrr2DPfNeaCqbf2wO1PmXirYyaJdcxYDWDzXUV2L1fOgPrH/8fA2jGg4YIV0kvuQ3T+nWJNfd29KVvvCDKvY9dcMbJeccnIhfPalbAdTcfFtUwuuRYS3+S8/rcO7LqeNz6yyedlQ3z4+eY3z1m1/g==
|
703,483
|
Average Count Array
|
Given an array arr[] and an integer x. You have to calculate the average for each element arr[i] and x and find out whether that number exists in the array. Do it for all the elements of the array and store the count result in another array for each index how many occurrences of average are present in the array.
Examples:
Input:
arr[] = [2, 4, 8, 6, 2] and x = 2
Output:
[2, 0, 0, 1, 2]
Explanation:
We take x = 2 and take average with arr[0] whch is equal to 2. We found 2 resides in array at two positions (1st and 5th element) thus storing 2 in another array at 0th index. Similarly do for all elements and store the count in second array.
Input:
arr[] = [9, 5, 2, 4, 0, 3] and x = 3
Output:
[0, 1, 1, 1, 0, 1]
Explanation:
The average of 9 and 3 is 6 and no occurence of 6 is present in array so 0. And so on.
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ x ≤ 10**5
1 ≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617554266,
"func_sign": [
"public ArrayList<Integer> countArray(int[] arr, int x)"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int k = Integer.parseInt(br.readLine());\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n ArrayList<Integer> v = new ArrayList<Integer>();\n v = new Solution().countArray(arr, k);\n\n for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + \" \");\n System.out.println();\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n // Function to count the occurrences of numbers in the array\n public ArrayList<Integer> countArray(int[] arr, int x) {\n int n = arr.length;\n ArrayList<Integer> b = new ArrayList<>();\n // Creating an ArrayList to store the counts\n // Counting frequency\n HashMap<Integer, Integer> m = new HashMap<>();\n for (int i = 0; i < n; i++) {\n m.put(arr[i], m.getOrDefault(arr[i], 0) + 1);\n }\n // Filling b ArrayList\n for (int i = 0; i < n; i++) {\n int avg = (arr[i] + x) / 2;\n b.add(m.getOrDefault(avg, 0));\n }\n return b;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n // Function for finding maximum and value pair\n public ArrayList<Integer> countArray(int[] arr, int x) {\n // Complete the function\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617554266,
"func_sign": [
"countArray(self, arr, x)"
],
"initial_code": "if __name__ == \"__main__\":\n t = int(input())\n while t > 0:\n arr = list(map(int, input().split()))\n k = int(input())\n ob = Solution()\n res = ob.countArray(arr, k)\n print(*res)\n print(\"~\")\n t -= 1\n",
"solution": "# User function Template for python3\n\nfrom collections import defaultdict\n\n\nclass Solution:\n # Function to count the occurrences of numbers in the array\n def countArray(self, arr, x):\n n = len(arr)\n b = [] # List to store the counts\n\n # Counting frequency\n freq_map = defaultdict(int)\n for num in arr:\n freq_map[num] += 1\n\n # Filling b list\n for num in arr:\n avg = (num + x) // 2\n b.append(freq_map[avg])\n\n return b\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def countArray (self, arr, x) : \n #Complete the function\n"
}
|
eJy9VTsOwjAMZUDiGlZmhNw/5SRIFDFAB5bCUCQkBOIQcBo2ToYTKEWA66Z8Ysttk/oldp6Tfft47rRMG57oZbRR82y5ytUAlJNkWlUXVLpeptM8nU0Wq7wc3SWZ2nbhyQXuwjuHcBcOBnXjEZDzK1xt/YwTxLoZ2zc2MjYUQB8iZnLiggc+BBRwBIQMjg5NhAMRmFZMeBHhBoTv0TzUG3yM60ItoR+ZqVyEpirzqlokAkBNqUOUBh+0PXara5oPM+cfsxJf67WsF8sKLFj1QjNTjc/9PPUcyrek+LabL7LQqsrQssoe45KCIzRG8fr8Fl3i3/KlPBFrHol4Sys2SGoljXz/sxiZdQjnox6s2ijhAg1AC2p7wxkfehf2GuwC
|
704,158
|
Modify array to maximize sum of adjacent differences
|
Given an array arr of size N, the task is to modify values of this array in such a way that the sum of absolute differences between two consecutive elements is maximized. If the value of an array element is X, then we can change it to either 1 or X. Find the maximum possible value of the sum of absolute differences between two consecutive elements.
Examples:
Input:
N = 4, arr[] = [3, 2, 1, 4, 5]
Output:
8
Explanation:
We can modify above array as
arr[] = [3, 1, 1, 4, 1]
Sum of differences =
|1-3| + |1-1| + |4-1| + |1-4| = 8
Which is the maximum obtainable value
among all choices of modification.
Input:
N = 2, arr[] = {1, 5}
Output:
4
Explanation:
No modification required
Your Task:
You don't need to read input or print anything. Complete the function
maximumDifferenceSum
()
which takes
N
and array
arr
as input parameters and returns the integer value
Expected Time Complexity:
O(
N
)
Expected Auxiliary Space:
O(
N
)
Constraints:
1 ≤
N≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int maximumDifferenceSum(int arr[], int N)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nclass GfG\n{\n public static void main(String args[])\n {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while(t-->0)\n {\n int n = sc.nextInt();\n int A[] = new int[n];\n for(int i = 0;i<n;i++)\n A[i] = sc.nextInt();\n Solution ob = new Solution();\n System.out.println(ob.maximumDifferenceSum(A,n));\n }\n }\n} ",
"script_name": "GfG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "class Solution{\n\n\tpublic int maximumDifferenceSum(int arr[], int N) \n\t{ \n\t //code here.\n\t} \n\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maximumDifferenceSum(self,arr, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n N = int(input())\n arr = [int(x) for x in input().split()]\n ob = Solution()\n ans = ob.maximumDifferenceSum(arr, N)\n print(ans)\n",
"solution": "import sys\nsys.setrecursionlimit(10**6)\n\ndp = [[0]*2 for i in range(10**5+1)]\n\n\nclass Solution:\n # Function to find the maximum difference sum.\n def maximumDifferenceSum(self, arr, N):\n global dp\n # Initialize dp array with -1.\n for i in range(N+1):\n for j in range(2):\n dp[i][j] = -1\n\n # Calculate the maximum difference sum for both start options (0 and 1).\n x = self.solve(arr, 1, N, 0)\n y = self.solve(arr, 1, N, 1)\n # Return the maximum of the two maximum difference sums.\n return max(x, y)\n\n # Recursive function to find the maximum difference sum.\n def solve(self, arr, i, n, x):\n global dp\n # Base case: reached the end of the array.\n if i == n:\n return 0\n\n # If the value is already calculated in dp array, return it.\n if dp[i][x] != -1:\n return dp[i][x]\n\n # If the start option is 0, calculate the maximum difference sum\n # considering two possibilities: choosing the current element or choosing 1.\n if x == 0:\n op1 = abs(arr[i] - arr[i-1]) + self.solve(arr, i+1, n, 0)\n op2 = abs(1 - arr[i-1]) + self.solve(arr, i+1, n, 1)\n dp[i][x] = max(op1, op2)\n return dp[i][x]\n\n # If the start option is 1, calculate the maximum difference sum\n # considering two possibilities: choosing the current element or not choosing it.\n else:\n op1 = abs(arr[i] - 1) + self.solve(arr, i+1, n, 0)\n op2 = self.solve(arr, i+1, n, 1)\n dp[i][x] = max(op1, op2)\n return dp[i][x]\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef maximumDifferenceSum(self,arr, N):\n\t\t# code here"
}
|
eJzVVb1OwzAYZGDiKU6ZK+Tvx7HNysYTIFHEAB1YSodWQkJIPAS8L19CgFaymwZCAUuuklZ3vrtevjwdvpwdHbTr/NQuLh6q2/litaxOUNF0Tq7ZICTb0XawXYOqCarZ/WJ2vZzdXN2tlh2iNkj1OMEmCTckINcu/NhVQRPFZCtmlZFv7HUcu3yWzpBY5/h965whUHjLLViGlqSRGRuDBKQgD7JILVkLOIEd2DAMFrCCPbgGB3AEJ4iDEMQoBaIQD6khARIhCeqgBGWonahQD62hARqhCb4on10+Hmf6jcP0m9gPH//yvmCdG4sZ5635La3Konit5wVcalcJ/F7pb4G/eL5sPKSlprTwWOo6hpfdqrnvunv2oS/Enpnids2x+2J4nI0Y82pEHcVWOfkW/9r4ER32j8SCgZEH0AgThcP4Myho7zT5/bfo268DhE6ngw7+fBvvSTTGUt0je/3uj4SMrFyJBfiwoC+fj18BlOtcDw==
|
706,386
|
Division without using multiplication, division and mod operator
|
Given two integers dividendand divisor. Find the quotient after dividing the dividendby divisorwithout using multiplication, division and mod operator.
Examples:
Input:
dividend = 10, divisor= 3
Output:
3
Exaplanation:
10/3 gives quotient as 3 and remainder as 1.
Input:
dividend = 43, divisor = -8
Output:
-5
Explanation:
43/-8 gives quotient as -5 and remainder as 3.
Examples:
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static long divide(long dividend, long divisor)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GfG {\n\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n int t = Integer.parseInt(br.readLine());\n\n while (t > 0) {\n String S[] = br.readLine().split(\" \");\n\n long a = Long.parseLong(S[0]);\n\n long b = Long.parseLong(S[1]);\n\n Solution ob = new Solution();\n\n System.out.println(ob.divide(a, b));\n t--;\n\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "GfG",
"solution": "// Back-end function Template for Java\nclass Solution {\n public static long divide(long dividend, long divisor) {\n // Calculate sign of divisor\n // i.e., sign will be negative\n // only iff either one of them\n // is negative otherwise it\n // will be positive\n long sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;\n // remove sign of operands\n dividend = Math.abs(dividend);\n divisor = Math.abs(divisor);\n // Initialize the quotient\n long quotient = 0, temp = 0;\n // test down from the highest\n // bit and accumulate the\n // tentative value for\n // valid bit\n // 1<<31 behaves incorrectly and gives Integer\n // Min Value which should not be the case, instead\n // 1L<<31 works correctly.\n for (int i = 31; i >= 0; --i) {\n if (temp + (divisor << i) <= dividend) {\n temp += divisor << i;\n quotient |= 1L << i;\n }\n }\n return (sign * quotient);\n }\n}\n",
"updated_at_timestamp": 1730268216,
"user_code": "// User function Template for Java\n\nclass Solution {\n public static long divide(long dividend, long divisor) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"divide(self, dividend, divisor)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(0, t):\n inp = list(map(int, input().split()))\n\n a = inp[0]\n b = inp[1]\n\n ob = Solution()\n print(ob.divide(a, b))\n print(\"~\")\n",
"solution": "# Back-end function Template for python3\nclass Solution:\n\n def divide(self, dividend, divisor):\n # Calculate sign of divisor\n # i.e., sign will be negative\n # either one of them is negative\n # only iff otherwise it will be\n # positive\n sign = (-1 if ((dividend < 0) ^ (divisor < 0)) else 1)\n\n # remove sign of operands\n dividend = abs(dividend)\n divisor = abs(divisor)\n\n # Initialize\n # the quotient\n quotient = 0\n temp = 0\n\n # test down from the highest\n # bit and accumulate the\n # tentative value for valid bit\n for i in range(31, -1, -1):\n if (temp + (divisor << i) <= dividend):\n temp += divisor << i\n quotient |= 1 << i\n\n return sign * quotient\n",
"updated_at_timestamp": 1730268216,
"user_code": "#User function Template for python3\n\nclass Solution:\n def divide(self, dividend, divisor):\n #code here"
}
|
eJxrYJm6g4UBDCI2AhnR1UqZeQWlJUpWCkqGMXkGCoZKOgpKqRUFqcklqSnx+aUlUEmDmLy6mDylWh0FVB2GOHUY4tChi1uLLi49hgq6JOvRxaMJlx4jQxNzEwtjMxNznG5EKMFlL1yFBW4HINQQYQpOrxM0Bck/SIpJjGJkpyAMJCk6CFuOrgGXn3HEM/50RYzPgGYQG3mGlsYmZmaWlngSOCTJkpFo0cIaf2Bj9RfUI0QGIMRCnEkFSFgQHWeYRhEb2WhBj9vC2Cl6AEfdYAU=
|
704,867
|
Choose and Swap
|
You are given a string str of lower case english alphabets. You can choose any two characters in the string and replace all the occurences of the first character with the second character and replace all the occurences of the second character with the first character. Your aim is to find the lexicographically smallest string that can be obtained by doing this operation at most once.
Examples:
Input:
str = "ccad"
Output:
"aacd"
Explanation:
In ccad, we choose a and c and after doing the replacement operation once we get, aacd and this is the lexicographically smallest string possible.
Input:
str = "abba"
Output:
"abba"
Explanation:
In abba, we can get baab after doing the replacement operation once for a and b but that is not lexicographically smaller than abba. So, the answer is abba.
Note :
Here |str| refers to the length of the string str.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1616271268,
"func_sign": [
"String chooseandswap(String str)"
],
"initial_code": "// Initial Template for Java\n\n// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n\n Solution obj = new Solution();\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String A = read.readLine().trim();\n\n String ans = obj.chooseandswap(A);\n System.out.println(ans);\n }\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1727746861,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n String chooseandswap(String str) {\n // Code Here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616271268,
"func_sign": [
"chooseandswap(self, str)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n ob = Solution()\n t = int(input())\n for _ in range(t):\n A = input()\n ans = ob.chooseandswap(A)\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n\n # Function to perform choose and swap operation.\n def chooseandswap(self, str):\n # Converting the string into a set to remove duplicate characters.\n ss = set(list(str))\n\n # Iterating over the string\n for i in range(len(str)):\n # If the current character is present in the set,\n # we remove it from the set.\n if str[i] in ss:\n ss.remove(str[i])\n\n # If the set is empty, which means we have removed\n # all the characters, we break the loop.\n if len(ss) == 0:\n break\n\n # If the minimum character in the set is less than the\n # current character, we perform choose and swap operation.\n if min(ss) < str[i]:\n temp = str[i]\n # Replacing the current character with '$' for temporary storage.\n str = str.replace(str[i], \"$\")\n # Replacing the minimum character with the current character.\n str = str.replace(min(ss), temp)\n # Replacing '$' with the minimum character.\n str = str.replace(\"$\", min(ss))\n break\n\n # Returning the modified string after choose and swap operation.\n return str\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n\n def chooseandswap(self, str):\n # code here\n pass\n"
}
|
eJyNk91OwyAYhj3Q+2g4Xkw49TY8MYoxFNjW/dBuowwwGi9C71eg1ewnL1uTlibf+/D95P2+bn+e727y8/QYf17eSaO73pCHilCmOZlURLlOCaPkW9ubMcSZ/mSafEyqE31AQEBELaRCUIoBLni3t4CzMYbzcRFfOZ4w85GqVPt0Nm8Wy9Vat91muzO93TsPpwAB1GVusze77aZr9Xq1XDTz2VRJgSvniIAT4XUthJTwwiEMaOddcMEHD/D/OORji6GAD2FAl+2jL/mn5FiaBGhmOW+RTgKNJn7B9xQZLlO62C9HDQ/LxHxxcxhLKj6KrrrpfKeQNekRB5cq++0vDXIlpUmFFzMWEj+H/uSihnVREe+DUw/ejn36cJ1z7IF1Xr/vfwFeYeMz
|
703,246
|
Even and odd elements at even and odd positions
|
Given an array arr[], the task is to arrange the array such that odd elements occupy the odd positions and even elements occupy the even positions. The order of elements must remain the same. Consider zero-based indexing. After printing according to conditions, if remaining, print the remaining elements as it is.
Examples:
Input:
arr[] = [1, 2, 3, 4, 5, 6]
Output:
[2, 1, 4, 3, 6, 5]
Explanation:
Even elements are at even position and odd elements are at odd position keeping the order maintained.
Input:
arr[] = [3, 7, 4, 1]
Output:
[4, 3, 7, 1]
Constraints:
2 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤arr.size()
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static ArrayList<Integer> arrangeOddAndEven(int arr[])"
],
"initial_code": "// Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\n// Driver class\nclass Array {\n\n // Driver code\n public static void main(String[] args) throws IOException {\n // Taking input using buffered reader\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n ArrayList<Integer> ans;\n ans = obj.arrangeOddAndEven(arr);\n for (int i : ans) System.out.print(i + \" \");\n System.out.println();\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Array",
"solution": "import java.util.*;\n\nclass Solution {\n // Function to arrange odd and even numbers in the array.\n public static ArrayList<Integer> arrangeOddAndEven(int[] arr) {\n int n = arr.length;\n ArrayList<Integer> ans = new ArrayList<>();\n int i = 0;\n int j = 0;\n int flag = 0;\n // Iterating over the array.\n while (i < n || j < n) {\n // Checking if flag is 0.\n if (flag == 0) {\n // Finding the next even number.\n while (i < n && arr[i] % 2 != 0) i++;\n // Pushing the even number to the answer list.\n if (i < n) {\n ans.add(arr[i]);\n i++;\n }\n flag = 1;\n }\n // Checking if flag is 1.\n else if (flag == 1) {\n // Finding the next odd number.\n while (j < n && arr[j] % 2 == 0) j++;\n // Pushing the odd number to the answer list.\n if (j < n) {\n ans.add(arr[j]);\n j++;\n }\n flag = 0;\n }\n }\n // Returning the answer list with arranged odd and even numbers.\n return ans;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public static ArrayList<Integer> arrangeOddAndEven(int arr[]) {\n // write code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"arrangeOddAndEven(self, arr)"
],
"initial_code": "if __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n ans = ob.arrangeOddAndEven(arr)\n print(*ans)\n tc -= 1\n print(\"~\")\n # No change needed, the indentation is already correct\n",
"solution": "class Solution:\n\n def arrangeOddAndEven(self, arr):\n n = len(arr)\n ans = []\n i = 0\n j = 0\n flag = 0\n\n # Iterating over the array\n while i < n or j < n:\n # Checking if flag is 0\n if flag == 0:\n # Finding the next even number\n while i < n and arr[i] % 2 != 0:\n i += 1\n # Appending the even number to the answer list\n if i < n:\n ans.append(arr[i])\n i += 1\n flag = 1\n # Checking if flag is 1\n else:\n # Finding the next odd number\n while j < n and arr[j] % 2 == 0:\n j += 1\n # Appending the odd number to the answer list\n if j < n:\n ans.append(arr[j])\n j += 1\n flag = 0\n\n # Returning the answer list with arranged odd and even numbers\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def arrangeOddAndEven(self, arr):\n # Your code goes here"
}
|
eJydVMtKxEAQ9KD/0cx5kfS8MvFLBCMeNAcvcQ9ZWBCX/Qj9O2/+iJ2eRFRSk9U0AyFTVVPTjxzP3z4uzvS5fpeXm2fz2G93g7kiw21vyZkNmW6/7e6H7uHuaTdMm7LT9oe2Ny8b+slh8oDjiQHHkqdIibiCx80AeKqjQDU1QOBrHzoQ34KJgkqC44oaYvnK0BEiQIdz2DkK0r8W1Bx1nISXCBJRopZIEg3MRlZ1egGvrKC8pKspZGkqw5zN0/PTFDJTCSIK2tJqGSuBpEnWC9BCr2EsiVOzUWC1wAuqYVLlGbqoStpoq51WbrUlY2Nu/2AOzhEqBu7J1dvw2nUAMwC8H2fAhWJBvDZPRqFzVUe75wQx2HvjKY5za+cfjGK/qUYsm5nLuoi1Msnx/6Mcy7N8+3r5CXm7lE8=
|
705,291
|
Word Break - Part 2
|
Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences.
Examples:
Input:
s = "catsanddog", n = 5
dict = {"cats", "cat", "and", "sand", "dog"}
Output:
(cats and dog)(cat sand dog)
Explanation:
All the words in the given
sentences are present in the dictionary.
Input:
s = "catsandog", n = 5
dict = {"cats", "cat", "and", "sand", "dog"}
Output:
Empty
Explanation:
There is no possible breaking
of the string s where all the words are present
in dict.
Constraints:
1 ≤ n ≤ 20
1 ≤ dict[i] ≤ 15
1 ≤ |s| ≤ 500
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static List<String> wordBreak(int n, List<String> dict, String s)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.stream.*;\n\nclass GFG{\n public static void main(String args[])throws IOException\n {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while(t-- > 0){\n int n = Integer.parseInt(in.readLine());\n String arr[] = in.readLine().trim().split(\"\\\\s+\");\n List<String> dict = new ArrayList<String>();\n for(int i = 0;i < n;i++)\n dict.add(arr[i]);\n String s = in.readLine();\n \n Solution ob = new Solution();\n List<String> ans = new ArrayList<String>();\n ans = ob.wordBreak(n, dict, s);\n if(ans.size() == 0)\n System.out.println(\"Empty\");\n else{\n List<String> sol = ans.stream().sorted().collect(Collectors.toList());\n for(int i = 0;i < sol.size();i++)\n System.out.print(\"(\"+sol.get(i)+\")\");\n System.out.println();\n }\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n static List<String> wordBreak(int n, List<String> dict, String s)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"wordBreak(self, n, dict, s)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n = int(input())\n dicti = input().split()\n s = input()\n\n ob = Solution()\n ans = ob.wordBreak(n, dicti, s)\n if len(ans) == 0:\n print(\"Empty\")\n else:\n ans.sort()\n for it in ans:\n print(\"(\"+it, end=\")\")\n print()\n print(\"~\")\n",
"solution": "class Solution:\n def wordBreak(self, n, dict, s):\n # Function to find all possible word break combinations\n def solve(arr, st, l, res):\n # If the entire string has been processed, append the current combination to the result\n if st == len(s):\n res.append(l[:])\n\n # Try all possible words from the dictionary and check if they match the substring\n for word in arr:\n if s[st:st+len(word)] == word:\n l.append(word) # Add the word to the current combination\n # Recursively check for the remaining substring\n solve(arr, st+len(word), l, res)\n l.pop() # Remove the last word from the current combination to backtrack\n\n # Initialize an empty list to store the result\n res = []\n\n # Call the recursive function to find all possible word break combinations\n solve(dict, 0, [], res)\n\n # Convert the combinations to string format\n res = [\" \".join(x) for x in res]\n\n # Return the final result\n return res\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def wordBreak(self, n, dict, s):\n # code here"
}
|
eJzVnNFuG0UUhrngQUa5aiSEKBVccI/EIyBhhMaJSaum65I4ahEC8RDwvtjr3fGc75u1d0uFRAOJz/GZ//z/N75c+c9P/+6++6T/9/3d/sUPv1296t4+7a6+SVfPV91Xq+4m7x7T/lfK3W16PPy63d4d2/ti//rqs3S1ef92c7Pb3P60fdoNp58dzozz1896mbFadX+suqvfP0sLt00u+/bN292vE5I553T4r3+Vp9zuBw4/18cXx79j3Zfj28O7/ZsTOb5ede+2D7dp/bDJr9Ph5fHV24ft+n7zJj1u7592r7bdcax/b3hryl0lN0xeP5PuGaw5rdfpJt2mzf71+uZ2s5Tji1X3cnN/vz2kud/L5Ifdy6HVd/rGlHudnHL65cFpXh885vXkTa33I1MK+//ut93d5nFXXkzpDG9PKe0T715u0i9Pr25e79Fv33Xp5+37Vdc3+npfTmnj1KTbL/rA/Ufs8P/x1/B7/FP+nl5Ur4aP9fHfhQ93/XPtpnutOY215BpqDTFqtaw1nDWM2VfDll3ZFDy1cDVoNWCZVQOVSRmUODUwmZIhiZERiZAART4VN/fUakxxqCFlJQtBp2HJjmxIfmxHbmQmemngMR3DERujERmBIRdjERVBIRMhIRECqXkUGJVE1VGrMcWhhpSVLASdhiU7siH5sR25kZnopYHHdAxHbIxGZASGXIxFVASFTISERAgk8Cg0klvseAYjlpGKRKKGrciJjNCHbNAFTQQPxiEagkEWQkESBAEOwkAKhAAGRAACAHDKX7JX60NHrcYUhxpSVrIQdBqW7MiG5Md25EZmopcGHtMxHLExGpERGHIxFlERFDIREhIhkMCj0EhuseMZjFhGKhKJGrYiJzJCH7JBFzQRPBiHaAgGWQgFSRAEOAgDKRACGBABCABAlT+n6kctdjyDEctIRSJRw1bkREboQzbogiaCB+MQDcEgC6EgCYIAB2EgBUIAAyIAAQCo85f0SR00NBEHJEEFCoTzskAHNID9XI/tWF7vVnymZ3hkZ3QkR/CYm7GRGqFjZkSOiWPgMW9112UvOmo1pjjUkLKShaDTsGRHNiQ/tiM3MhO9NPCYjuGIjdGIjMCQi7GIiqCQiZCQCIEEHoVGcosdz2DEMlKRSNSwFTmREfqQDbqgieDBOERDMMhCKEiCIMBBGEiBEMCACEAAAKr8JfzpeNVgxzMYsYxUJBI1bEVOZIQ+ZIMuaCJ4MA7REAyyEAqSIAhwEAZSIAQwIAIQAIA6f0mf1EFDE3FAElSgQDgvC3RAA9jP9diO5fVuxWd6hkd2RkdyBI+5GRupETpmRuSYOAYueavLHs+GBjuewYhlpCKRqGErciIj9CEbdEETwYNxiIZgkIVQkARBgIMwkAIhgAERgAAA1Pmru2UHDU3EAUlQgQLhvCzQAQ1gP9djO5bXuxWf6Rke2RkdyRE85mZspEbomBmRY+IY+JS3uu2kDhqaiAOSoAIFwnlZoAMawH6ux3Ysr3crPtMzPLIzOpIjeMzN2EiN0DEzIsfEMXCVV9fN2+Zl46551bhpXHS8Z14zbhmXHO8YVxxvOF5wuF9eL24XlxvvFlcbbzZebLjXjJgxZQwZMsaIIWEIeMw3/YRHfDLlRXyoZXis5uyzLecePBqeZRpkhkeaumVPUF18ZkqPkITf45/yN757+Pe/fX6kZaTho2HDLhom7CH71PlGC1aDVQOVSTVAmZMxNSgZkhkJUbbwnMaprii5p1ZjikMNKStRqOHABrxf671dy5n+fN2AYzZGIzIGIy7CojQzG8tqni9vl+jViqqjVmOKQw0pK1Go4cAGvF/rvV3Lmf583YBjNkYjMgYjLsJiKoIiJkSSpXm5LmUJn9xixzMYsYxUIOLV2qzF3Ku13Jo5P13K0NzGsprnL9bzS5rDbkiPZ3MKP+6p1ZjiUEPKShRqOLAB79d6b9dypj9fN+CYjdGIjMGIi7CYiqCICZFkaV6uS1nCJ7fY8QxGLCMViHi1Nmsx92ott2bOT5eGIRZCQRICQQ7EwASz6gUlzo5v5pR5+VWDHc9gxDJSgYhXa7MWc6/Wcmvm/HRpGGIhFCQhEORADKJACGQABJlyl8qxUtz5jWU1z1+s55c0N6NeUOLsmZKYQAEhYwqYjC7GNeUmqhtBR63GFIcaUlaiUMOBDXi/1nu7lmcdOVc34JiN0YiMwYiLsJiKoIgJkfC259SlLOGTW+x4BiOWkQpEvFqbtZh7tZZbM+enS8MQC6EgCYEgB2Jggln1ghJnxzdL1pN41WDHMxixjFQg4tXarMXcq7Xcmjk/XRqGWAgFSQgEORCDKBACGQBBptylcqxK2qQOGpqIA5KgQhTQTq7kRizkPqzLeV5FH/PqBSXOXihnVrAUd0bR4Vx1zePZ0GDHMxixjFQg4tXarMXcq7Xcmjk/XRqGWAgFSQgEORCDKBACGQBBptylcqyqm2QHDU3EAUlQIQpoJ1dyIxZyH9blPK9SeGZndCRncORGbLieUc6t4rnhLV3uksaymucv1vNLmptRLyhx9kxJTLPqBSXOXihnVrB0sZxb/ecFP6b4FOJDFj9F+JDET0G8ZtxivKZ4DwF1ZBlwHVMs+5KV4VGEmV/Ccfb7VuJ3jTw/7BufgWh8PcdH+C6S+rmNvvfxHt44MtoVSHcnSqtTrH8BbHaYg4UPDtTf6apbrfK6fwLlwy52/Mj3j4xs9EU35Vtspp4jKeI//vX5P7uzBUE=
|
703,022
|
Smallest subarray with all occurrences of a most frequent element
|
Given an array arr[]. Let x be an element in the array with the maximum frequency. The task is to find the smallest sub-segment of the array which also has x as the maximum frequency element.
Examples:
Input:
arr[] = [1, 2, 2, 3, 1]
Output:
[2, 2]
Explanation:
Note that there are two elements that appear two times, 1 and 2. The smallest window for 1 is whole array and smallest window for 2 is [2, 2]. Since window for 2 is smaller, this is our output.
Input:
arr[] = [1, 4, 3, 3, 5, 5]
Output:
[3, 3]
Explanation:
In this array, both 3 and 5 have the highest frequency of 2. However, the sub-segment [3, 3] occurs earlier in the array than [5, 5], so the correct output is [3, 3].
Expected Time Complexity:
O(n).
Expected Auxiliary Space:
O(n).
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1618075590,
"func_sign": [
"public int[] smallestSubsegment(int arr[])"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n // int k = Integer.parseInt(br.readLine());\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n int answer[] = obj.smallestSubsegment(arr);\n int sz = answer.length;\n\n StringBuilder output = new StringBuilder();\n for (int i = 0; i < sz; i++) output.append(answer[i] + \" \");\n System.out.println(output);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n public int[] smallestSubsegment(int[] arr) {\n int n = arr.length;\n // Maps to store the index and count of elements.\n HashMap<Integer, Integer> left = new HashMap<>();\n HashMap<Integer, Integer> count = new HashMap<>();\n int mx = 0;\n int mn = 0, strindex = 0;\n\n // Iterating over the array.\n for (int i = 0; i < n; i++) {\n int x = arr[i];\n\n // If the element is encountered for the first time,\n // initialize its left index and count as 1.\n if (!count.containsKey(x)) {\n left.put(x, i);\n count.put(x, 1);\n } else {\n // Else increment the count.\n count.put(x, count.get(x) + 1);\n }\n\n // If the count is greater than the maximum count,\n // update the maximum count, minimum subsegment size,\n // and starting index of the subsegment.\n if (count.get(x) > mx) {\n mx = count.get(x);\n mn = i - left.get(x) + 1;\n strindex = left.get(x);\n }\n // If the count is equal to the maximum count and the\n // subsegment size is smaller than the current subsegment,\n // update the minimum subsegment size and starting index.\n else if (count.get(x) == mx && i - left.get(x) + 1 < mn) {\n mn = i - left.get(x) + 1;\n strindex = left.get(x);\n }\n }\n\n // Creating an array to store the smallest subsegment.\n int[] result = new int[mn];\n\n // Adding the smallest subsegment elements to the array.\n for (int i = 0; i < mn; i++) {\n result[i] = arr[strindex + i];\n }\n\n // Returning the smallest subsegment array.\n return result;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int[] smallestSubsegment(int arr[]) {\n // Complete the function\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618075590,
"func_sign": [
"smallestSubsegment(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n while t > 0:\n arr = list(map(int, input().split()))\n ob = Solution()\n res = ob.smallestSubsegment(arr)\n print(*res)\n t -= 1\n print(\"~\")\n",
"solution": "class Solution:\n\n def smallestSubsegment(self, arr):\n # Dictionaries to store the index and count of elements.\n left = {}\n count = {}\n mx = 0\n mn = 0\n strindex = 0\n\n # Iterating over the array.\n for i, x in enumerate(arr):\n # If the element is encountered for the first time,\n # initialize its left index and count as 1.\n if x not in count:\n left[x] = i\n count[x] = 1\n else:\n # Else increment the count.\n count[x] += 1\n\n # If the count is greater than the maximum count,\n # update the maximum count, minimum subsegment size,\n # and starting index of the subsegment.\n if count[x] > mx:\n mx = count[x]\n mn = i - left[x] + 1\n strindex = left[x]\n # If the count is equal to the maximum count and the\n # subsegment size is smaller than the current subsegment,\n # update the minimum subsegment size and starting index.\n elif count[x] == mx and i - left[x] + 1 < mn:\n mn = i - left[x] + 1\n strindex = left[x]\n\n # Returning the smallest subsegment as a list.\n return arr[strindex:strindex + mn]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def smallestSubsegment (self, arr) : \n #Complete the function\n"
}
|
eJzNVUtOw0AMZcGGW1hZV6jzn3ASJIpYQBdsQhetBEKgHgLui+2ZCW2Jk2lZQOx8mvoX28/enn9uL874uH7Bh5vX5rFbbdbNFTRq0Skg0kyGyTI5okXXzKBZPq+W9+vlw93TZl0USWvRvaPA2wwOLM4BWRc2c7DMbo9F04digz58ig88U8gUmdpEooMsLUbPB7R8lFt5u/dvLLf8Vs7Wb2wORmkw/yZXzPa5CPnJyMndlxypINcQUi3JB94cXTznmd+PfG+l/qD3VL+kqdQOa2bDbHuWo/jWlb6TM2hzRmL2qoobtI4he1ABFIbcckOjDkIFc29BO9AedAAdQbfU6AargiaxKhYM1sGDCWAimJYxoMBqsOgRAebAerABbATbjuFBDr4Adxe2PXQLTbSCm2gEgjBhmBBMeMQC4hnwjNSyuX0xaXQhUUWyioSV+3GRP3JItqI7qvE6HwYXVkwB2jmpwfKYkTInD4OTBmesnJxxYnQKNf13cDilycYm8JFJr1pkkPKcflHm5QiKGSkMyzMzpk1MDanrtzHLVI8J1c+JowfF5L74k4WR0Ty+fMd1cWMesZ2p5tVb32TPtx+XXx/zQ5Q=
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.