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,825
|
Count digits in given number N which divide N
|
Given a number S(in the form of a string). Count all the digits in Swhich divide S. Divisibility by 0 is not allowed. If any digit in Swhich is repeated divides S, then all repetitions of that digit should be counted.
Examples:
Input:
S = "35"
Output:
1
Explanation:
Only 5 digits 35,thus the answer is 1.
Input:
S = "1122324"
Output:
7
Explanation:
All the digits divide 1122324, therefore,
the answer is 7.
Constraints:
1<=|S|<=10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int divisibleByDigits(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 read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S = read.readLine();\n Solution ob = new Solution();\n System.out.println(ob.divisibleByDigits(S));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n boolean divisible(String S, int digit) {\n int ans = 0;\n for (int i = 0; i < S.length(); i++) {\n ans = (ans * 10 + (int) (S.charAt(i) - '0'));\n ans %= digit;\n }\n return (ans == 0);\n }\n\n // Function to count digits which appears in S and\n // divide S\n // divide[10] --> array which tells that particular\n // digit divides S or not\n // count[10] --> counts frequency of digits which\n // divide S\n int divisibleByDigits(String S) {\n boolean divide[] = new boolean[10];\n divide[1] = true; // 1 divides all numbers\n // start checking divisibilty of S by digits 2 to 9\n for (int digit = 2; digit <= 9; digit++) {\n // if digit divides S then mark it as true\n if (divisible(S, digit)) divide[digit] = true;\n else divide[digit] = false;\n }\n // Now traverse the number string to find and increment\n // result whenever a digit divides S.\n int result = 0;\n for (int i = 0; i < S.length(); i++) {\n if (divide[(int) (S.charAt(i) - '0')] == true) result++;\n }\n return result;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n static int divisibleByDigits(String S) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"divisibleByDigits(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.divisibleByDigits(S))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to check if a number is divisible by the given digit.\n def divisible(self, S, digit):\n ans = 0\n # iterating over each digit in the number.\n for i in S:\n # converting the digit to integer and adding it to ans.\n ans = (ans*10) + int(i)\n # calculating the remainder when ans is divided by digit.\n ans %= digit\n # returning True if ans is 0 (divisible by digit), else False.\n return ans == 0\n\n # Function to find the count of digits in the number that are divisible by their own value.\n def divisibleByDigits(self, S):\n # creating a list to store whether each digit is divisible or not.\n divide = []\n # appending False for index 0 and True for index 1, as 0 and 1 are always divisible by themselves.\n divide.append(False)\n divide.append(True)\n # iterating from 2 to 9 (all possible single digits).\n for i in range(2, 10):\n # checking if the number is divisible by the digit i.\n if self.divisible(S, i):\n # appending True if divisible, else False.\n divide.append(True)\n else:\n divide.append(False)\n # initializing the result as 0.\n result = 0\n # iterating over each digit in the number.\n for i in S:\n # checking if the digit is divisible by itself using divide list.\n if divide[int(i)]:\n # if divisible, incrementing the result.\n result += 1\n # returning the final result.\n return result\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution: \n def divisibleByDigits(self,S):\n #code here"
}
|
eJylVMsKwjAQ9KD/EXIu0jyb+iVCK4Lag5faQwqCKH6E/q+pJNUWdkvoXFJIJpnZne5z+T6sFl9sC/dR3Oi5blpLN4Syss4DypomhFbXpjra6rS/tNYfcjsPt3lPyJDJAuKZKUhhEIULqXRmcpiqASoPiNapPECiAQ0GRBvNTaaVFByuqgCYQohojnQASRKWmOmRSzWUjhpArBvdi8KLwLE75l7C0lHiJruJyGG9GKxow5xOlhB675dY/DeDgjtbb5fDbo1WjuQQbJOfPn9C0HGEDwi879j4CHnevdYfTMuexA==
|
702,918
|
Sub-Array sum divisible by K
|
You are given an array of integers and a value k. The task is to find the count of all sub-arrays whose sum is divisible by k.
Examples:
Input:
arr[] = [4, 5, 0, -2, -3, 1], k = 5
Output:
7
Explanation:
There are 7 sub-arrays whose is divisible by k: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3] and [-2, -3]
Input:
arr[] = [2, 2, 2, 2, 2, 2], k = 2
Output:
21
Explanation:
All subarray sums are divisible by 2
Constraints:
1 ≤ arr.size() ≤ 10**6
-10**4≤ arr[i]≤ 10**4
1 ≤ k ≤ 10**3
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615310465,
"func_sign": [
"public int subCount(int[] arr, 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 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 int d = Integer.parseInt(read.readLine().trim());\n\n Solution ob = new Solution();\n long ans = ob.subCount(nums, d);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730810735,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Function to count the number of subarrays with a sum that is divisible by K\n public int subCount(int[] arr, int k) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615310465,
"func_sign": [
"subCount(self, arr, k)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input().strip())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n d = int(input().strip())\n ob = Solution()\n print(ob.subCount(arr, d))\n tc -= 1\n",
"solution": "# Initial Template for Python 3\nclass Solution:\n # Function to count the number of subarrays with a sum that is divisible by K\n def subCount(self, arr, k):\n # Dictionary to store the frequency of remainders\n mod = [0] * k\n\n # Initialize all elements of mod[] to 0\n cumSum = 0 # Variable to store the cumulative sum of elements in the array\n\n # Loop through the array to calculate the cumulative sum\n # and update the mod array\n for num in arr:\n cumSum += num\n # Update the frequency of the remainder in the mod array\n mod[((cumSum % k) + k) % k] += 1\n\n result = 0 # Variable to store the final result\n\n # Loop through the mod array to calculate the count of subarrays\n for count in mod:\n if count > 1:\n # Calculate the count of subarrays with the same remainder\n # and add it to the result\n result += (count * (count - 1)) // 2\n\n # Add the count of subarrays with a sum of 0 to the result\n result += mod[0]\n\n # Return the final result\n return result\n",
"updated_at_timestamp": 1727947200,
"user_code": "class Solution:\n # Function to count the number of subarrays with a sum that is divisible by K\n def subCount(self, arr, k):\n # Your code goes here"
}
|
eJyVUzFOAzEQpIB/jK7mkHfttX28BIkgCkhBEygSCQkh8Qj4ER2fYjYJQoANR6LzbZTxenZm/HT48nZ0sP2cvbI4fxhuVneb9XCKQRargjFCIAGjIYOvhIpRIYpRBGmxysMxhuX93fJqvby+vN2sP3bzv+HxGF8bSghQPjF4Ly7mReZS+FT/MXEhLDi409us1XuaJu7mMrPgAdY5IIYmeSNv0qYUfBXD5EyNSiiL6IWxyGRXOo1Lq2/Ev7/c1KNu0uTuViaYUO2K6lwDbRTKITFDLLIoZF8J1JB8R2+G2jpAkZiQ6llhOCRRBzaj2VCFJmiGVtcvKkiEZ8aKFJCUe6VzlObmLEyesmuMJJ0SpzJakjM9KQW11p3NsscxqkRSMuvlqanYViIK43JA+XLu5qkFEzDSaY9hL0G5zTy4EiH55BPVksnvUY6VgmihMWM2czuihKI7fM/n5gFf79Mf10h+pnwrWgf+HZrrTKCWX/PUgM+k8Dkwg7yfOf9/6KbZ2LsdZ9ndcINzMHVzR9miQ+9Sfwcz9F3kxfPJO9AghXI=
|
701,303
|
The Modified String
|
Ishaan is playing with strings these days. He has found a new string. He wants to modify it as per the following rules to make it valid:
Examples:
Input:
S = aabbbcc
Output:
1
Explanation:
Inaabbbcc 3 b's occur
consecutively, we add a 'd',and Hence,
output will be aabbdbcc.
Input:
S = aaaaa
Output:
2
Explanation:
In aaaaa 5 a's occur
consecutively,we need to add 2 'b', and
Hence, the output will be aababaa.
Constraints :
1 <= Length of S <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1619250093,
"func_sign": [
"public static long modified(String a)"
],
"initial_code": "import 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 long t = sc.nextLong();\n \n while(t-- > 0)\n {\n String a = \"\";\n a = sc.next();\n System.out.println(new Solution().modified(a));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "gfg",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "\n\nclass Solution\n{\n //Function to find minimum number of characters which Ishaan must insert \n //such that string doesn't have three consecutive same characters.\n public static long modified(String a)\n {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619250093,
"func_sign": [
"modified(self,s)"
],
"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 obj = Solution()\n print(obj.modified(s))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n\n # Function to find minimum number of characters which Ishaan must insert\n # such that string doesn't have three consecutive same characters.\n def modified(self, s):\n ans = 0\n same = 1\n\n # checking for any three consecutive same characters and if they are\n # found then we increment the count of characters to be added.\n for i in range(1, len(s)):\n if s[i] == s[i-1]:\n same += 1\n else:\n ans += (same - 1) // 2\n same = 1\n\n ans += (same - 1) // 2\n # returning the answer.\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "\n#User function Template for python3\n\nclass Solution:\n \n #Function to find minimum number of characters which Ishaan must insert \n #such that string doesn't have three consecutive same characters.\n def modified(self,s):\n #code here"
}
|
eJy9VduOgjAQ3QeT/Q3SZ2NEN8b4JSZiDJSu9wJaUDQaP2L9FN/246yNiBpmCmg8vEygPZ2Zc6YcKsf/7y+F7kkGvS0Zcz8UpGMQ0+LOFRYnVYOwtc+oYO7AC8V1TdPie/lxVzUeN9q241AJV4ExBjL8QAxqP7XV+fYFSUApSNYGyDYYQDYTzA3cUgerQZ7CbH4pgMc0WrAGLvsdjsaT6WzOPc+TLEEQLCSWSyFEKBFF0UpifUEcx1g7TcQsqcRpqAxwewG3yYRcmKS0QQKYtZHHTBnaPov7uFpjRdyRuFB6n+XSCXJdvrqzh//D3YDlKDFtt3LuqGlSq6aAjNO1N+JLY1LUzGlq2cK9rYO6zGnh1LXTXXowMNOht5j6Y33aJ/2/2hn6Od0p
|
713,588
|
Maximum Bipartite Matching
|
There are M job applicants and N jobs. Each applicant has a subset of jobs that he/she is interested in. Each job opening can only accept one applicant and a job applicant can be appointed for only one job. Given a matrix G with Mrows and N columnswhere G(i,j) denotes i**thapplicant is interested in the j**thjob. Find the maximum number of applicants who can get the job.
Examples:
Input:
M = 3, N = 5
G = {{1,1,0,1,1},{0,1,0,0,1},
{1,1,0,1,1}}
Output:
3
Explanation:
There is one of the possible
assignment-
First applicant gets the 1st job.
Second applicant gets the 2nd job.
Third applicant gets the 4th job.
Input:
M = 6, N = 2
G = {{1,1},{0,1},{0,1},{0,1},
{0,1},{1,0}}
Output:
2
Explanation:
There is one of the possible
assignment-
First applicant gets the 1st job.
Second applicant gets the 2nd job.
Constraints:
1 ≤ N, M ≤ 100
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1673953262,
"func_sign": [
"public int maximumMatch(int[][] G)"
],
"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 PrintWriter out=new PrintWriter(System.out);\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String[] S = br.readLine().trim().split(\" \");\n int m = Integer.parseInt(S[0]);\n int n = Integer.parseInt(S[1]);\n int[][] G = new int[m][n];\n for(int i = 0; i < m; i++){\n String[] s = br.readLine().trim().split(\" \");\n for(int j = 0; j < n; j++)\n G[i][j] = Integer.parseInt(s[j]);\n }\n Solution obj = new Solution();\n int ans = obj.maximumMatch(G);\n out.println(ans);\n \nout.println(\"~\");\n}\n out.close();\n }\n}",
"script_name": "GFG",
"solution": "//User function Template for Java\n\nclass Solution\n{\n boolean bpm(int bpGraph[][], int u, \n boolean seen[], int matchR[], int M, int N)\n {\n // Try every job one by one\n for (int v = 0; v < N; v++)\n {\n // If applicant u is interested \n // in job v and v is not visited\n if (bpGraph[u][v]==1 && !seen[v])\n {\n \n // Mark v as visited\n seen[v] = true; \n\n // If job 'v' is not assigned to\n // an applicant OR previously\n // assigned applicant for job v (which\n // is matchR[v]) has an alternate job available.\n // Since v is marked as visited in the \n // above line, matchR[v] in the following\n // recursive call will not get job 'v' again\n if (matchR[v] < 0 || bpm(bpGraph, matchR[v],\n seen, matchR, M, N))\n {\n matchR[v] = u;\n return true;\n }\n }\n }\n return false;\n }\n // Returns maximum number \n // of matching from M to N\n int maxBPM(int bpGraph[][], int M, int N)\n {\n // An array to keep track of the \n // applicants assigned to jobs. \n // The value of matchR[i] is the \n // applicant number assigned to job i, \n // the value -1 indicates nobody is assigned.\n int matchR[] = new int[N];\n\n // Initially all jobs are available\n for(int i = 0; i < N; ++i)\n matchR[i] = -1;\n\n // Count of jobs assigned to applicants\n int result = 0; \n for (int u = 0; u < M; u++)\n {\n // Mark all jobs as not seen \n // for next applicant.\n boolean seen[] =new boolean[N] ;\n for(int i = 0; i < N; ++i)\n seen[i] = false;\n\n // Find if the applicant 'u' can get a job\n if (bpm(bpGraph, u, seen, matchR, M, N))\n result++;\n }\n return result;\n }\n public int maximumMatch(int[][] G)\n {\n // Code here\n int M=G.length;\n int N=G[0].length;\n int ans = maxBPM(G,M,N);\n return ans;\n }\n}",
"updated_at_timestamp": 1730481932,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public int maximumMatch(int[][] G)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1673953262,
"func_sign": [
"maximumMatch(self, G)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n m, n = map(int, input().strip().split())\n G = []\n for i in range(m):\n G.append(list(map(int, input().strip().split())))\n obj = Solution()\n ans = obj.maximumMatch(G)\n print(ans)\n",
"solution": "class Solution:\n def try_kunh(self, u, G, used, mt):\n # Function to check if there is an augmenting path starting from vertex u\n for v in range(len(G[0])):\n # Check if there is an edge between u and v and v is not used yet\n if G[u][v] and used[v] == False:\n used[v] = True\n # If v is not matched with any other vertex or there is an augmenting path starting from mt[v]\n if mt[v] < 0 or self.try_kunh(mt[v], G, used, mt):\n mt[v] = u\n return True\n return False\n\n def maximumMatch(self, G):\n m = len(G)\n n = len(G[0])\n N = max(n, m)\n ans = 0\n mt = [-1 for i in range(N)]\n # Try to find an augmenting path starting from each vertex in G\n for i in range(m):\n used = [False for j in range(N)]\n # If an augmenting path is found, increment the count of matches\n if self.try_kunh(i, G, used, mt):\n ans += 1\n return ans\n",
"updated_at_timestamp": 1730481932,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef maximumMatch(self, G):\n\t\t#code here"
}
|
eJzVVMEKwjAM9eDBzwg9iySDXfwSQcWD7uBlepggiODZm6D/a5d1TrtktBMPbjS0W17ymqbvMnzcRgN+Zlc7mZ/MNt8fCjMFQ4ucoDRmDCY77rN1kW1Wu0PR/DfnMQgIVBAoIRJI6kSgpUo6gDYo9gBiBQynqnm246eQMjF+iekBLzlhtfAc3FclRSrtgrOgC4Ix05jTIcvMkfVGtS9v/Iun1tJyDVKg14kqts6i2IaZaN85isHfyQvBP3fXCu5vX2SuOIg1lZkLDjJaZe456GiV+cfBd6HVFmhftjKRk7YF5XaEKUENC9YN1qWy0ahb1NrCi7rmfidPVEqshThHZJbRUvVTEflJ0DDPKBUJKLtUd9dF/WqP2Kst+vUFxZLruhvL++QJu4UPOQ==
|
703,296
|
Rod Cutting
|
Given a rod of length N inches and an array of prices, price[]. price[i] denotes the value of a piece of length i. Determine the maximum value obtainable by cutting up the rod and selling the pieces.
Examples:
Input:
n = 8,
price[] = {1, 5, 8, 9, 10, 17, 17, 20}
Output:
22
Explanation:
The maximum obtainable value is 22 by
cutting in two pieces of lengths 2 and
6, i.e., 5+17=22.
Input:
n = 8,
price[] = {3, 5, 8, 9, 10, 17, 17, 20}
Output:
24
Explanation:
The maximum obtainable value is
24 by cutting the rod into 8 pieces
of length 1, i.e, 8*price[1]= 8*3 = 24.
Constraints:
1 ≤ n≤ 1000
1 ≤ price[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int cutRod(int price[], int n)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass RodCutting {\n\n public static void main(String args[])throws IOException {\n BufferedReader in=new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out=new PrintWriter(System.out);\n \n int t = Integer.parseInt(in.readLine().trim());\n while (t-- > 0) {\n int n = Integer.parseInt(in.readLine().trim());\n String s[]=in.readLine().trim().split(\" \");\n int[] arr = new int[n];\n for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(s[i]);\n\n Solution ob = new Solution();\n out.println(ob.cutRod(arr, n));\n \nout.println(\"~\");\n}\n out.close();\n }\n}\n",
"script_name": "RodCutting",
"solution": "class Solution {\n public int cutRod(int[] price) {\n int n = price.length;\n // create a new array to store the maximum value for each length of rod\n int dp[] = new int[n + 1];\n\n // base case: if the length of rod is 0, the maximum value is 0\n dp[0] = 0;\n\n // iterate through all possible lengths of rod\n for (int i = 1; i <= n; i++) {\n int max_val = Integer.MIN_VALUE;\n\n // for each length of rod, try all possible cuts and find the maximum value\n for (int j = 0; j < i; j++) {\n max_val = Math.max(max_val, price[j] + dp[i - j - 1]);\n }\n\n // store the maximum value for the current length of rod\n dp[i] = max_val;\n }\n\n // return the maximum value for the given length of rod\n return dp[n];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution{\n public int cutRod(int price[], int n) {\n //code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"cutRod(self, price, n)"
],
"initial_code": "# Initial Template for Python 3\n\ndef main():\n T = int(input())\n\n while(T > 0):\n n = int(input())\n a = [int(x) for x in input().strip().split()]\n ob = Solution()\n print(ob.cutRod(a, n))\n\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n\n # Function to find the maximum obtainable value by cutting the rod\n def cutRod(self, price, n):\n\n # Create a list to store the maximum obtainable value for each length of rod\n val = [0]*(n+1)\n\n # Iterate through each length of rod\n for i in range(1, n+1):\n # Initialize the maximum value to -1 for each length of rod\n max_val = -1\n\n # Iterate through each possible cut in the rod\n for j in range(i):\n # Calculate the maximum obtainable value by considering different cuts\n max_val = max(max_val, price[j] + val[i - j - 1])\n\n # Store the maximum obtainable value for the current length of rod\n val[i] = max_val\n\n # Return the maximum obtainable value for the given length of rod\n return val[n]\n",
"updated_at_timestamp": 1730272786,
"user_code": "#User function Template for python3\n\nclass Solution:\n def cutRod(self, price, n):\n #code here"
}
|
eJzNlL9KxEAQxi3Ews43+Nj6kJ3Z2c3GJxGMWOgVNvGKHAii+BD6vk72cmC4TI6cjZkUIcP89pt/+3n+fXVxVp7bS/24e3PP7WbbuRs4atr+9W4Ft37drB+79dPDy7bbu33TfjSte19hHMQahGhERSOopxEObOnZBeNRI6NCQoQggGc4Jij2elijRSlJaVmpiiZVpcAAEpCVJZlpqiNixgxgZQHZ73SK6qOEwEiqizM4avq9Us8C9pIhvk7IVOu/FLIWhquUkWIMSfMhXzE4MYkmzMI5Wx0sTkOOylTKzpb2rsQO9V4aq3o8RmYQzKEtdYz/ppCTg3zaJE/C9rNYtuOkNR9D8/FdC2lGoVbNXKbeNxVqSTZOsFOk+SR1Cg47MXTYypa5CsJyHCu/ufWfweNrKy69t0IYwPdf1z9RG6aG
|
714,217
|
Minimum Number
|
You are given an array arr of n elements. In one operation you can pick two indices i and j, such that arr[i] >= arr[j]and replace the value of arr[i] with (arr[i] - arr[j]). You have to minimize thevalues of the array after performing any number of such operations.
Examples:
Input:
n = 3
arr = {3,2,4}
Output:
1
Explanation:
1st Operation : We can pick 4 & 3, subtract 4-3 => {3,2,1}
2nd Opeartion : We can pick 3 & 2, subtarct 3-2 => {1,2,1}
3rd Operation : We can pick 1 & 2, subtract 2-1 => {1,1,1}
4th Opeartion : We can pick 1 & 1, subtract 1-1 => {1,0,1}
5th Operation : We can pick 1 & 1, subtract 1-1 => {0,0,1}
After this no operation can be performned, so maximum no is left in the array is 1, so the ans is 1.
Input:
n = 2
arr = {2,4}
Output:
2
Explanation:
1st Operation : We can pick 4 & 2, subtract 4-2 => {2,2}
2nd Operation : We can pick 2 & 2, subtract 2-2 => {0,2}
After this no operation can be performned, so maximum no is left in the array is 2, so the ans is 2.
Constraints:
1 ≤ n≤ 10**5
1 ≤ arr[i]≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1678707539,
"func_sign": [
"public static int minimumNumber(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 int res = obj.minimumNumber(n, arr);\n \n System.out.println(res);\n \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public static int minimumNumber(int n, int[] arr) {\n // code here\n int gcd=0;\n for(int i=0;i<n;i++){\n gcd=gcd(gcd,arr[i]);\n }\n return gcd;\n }\n public static int gcd(int a,int b)\n {\n if(b==0)return a;\n return gcd(b,a%b);\n }\n}",
"updated_at_timestamp": 1730482422,
"user_code": "class Solution {\n public static int minimumNumber(int n, int[] arr) {\n // code here\n }\n}\n \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1678707539,
"func_sign": [
"minimumNumber(self, n, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n n = int(input())\n arr = [int(i) for i in input().split()]\n obj = Solution()\n print(obj.minimumNumber(n, arr))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find the minimum number.\n def minimumNumber(self, n, arr):\n # function to calculate gcd of two numbers.\n def gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\n\n res = 0\n # iterating over the array.\n for i in range(n):\n # finding gcd of res and each element of array.\n res = gcd(res, arr[i])\n\n # returning the gcd.\n return res\n",
"updated_at_timestamp": 1730482422,
"user_code": "#User function Template for python3\n\nclass Solution:\n def minimumNumber(self, n, arr):\n #code here"
}
|
eJy1VD1PxDAMZUBiZmN86nxCifPNL0GiiAE6sIQbehISuhM/Av4vTiFFN1ypq+LKktPIznPec97PP68uzga7veTg7q15zttd39yg0W12bdaqGlI1xGoI1eCrtbnZoOlet91j3z09vOz634IH3txvcHwKZ2iMnzg9tJlg4BCgOd9AB3GN2OYUg3fWEJcgY50PMWFYK94Br9TwH76GcDWErSFMDcUQtDq6bIYhX4gPNdz3yGoN4hjJL9IWLgkWUZyaCpbSDntpi9iZTGXZHbtnlwNy34CYIzg5J8TaYhlExCIuRsAC0MGCGBkZAnkunhSMTkz96Z4pnTrhf7Q3c6TiAln8kLxIHRPvCVZ8UKZVvT7ssBLuOdDn9mImBtT+MaEkHAf5PEzcQBmHRaKdh05rCb77j+svJw3uDQ==
|
702,787
|
Find the element that appears once
|
Given a sorted array arr[] of n positive integers having all the numbers occurring exactly twice, exceptfor one number which will occur only once. Find the number occurring only once.
Examples:
Input:
n = 5, arr[] = {1, 1, 2, 5, 5}
Output:
2
Explanation:
Since 2 occurs once, while other numbers occur twice, 2 is the answer.
Input:
n = 7, arr[] = {2, 2, 5, 5, 20, 30, 30}
Output:
20
Explanation:
Since 20 occurs once, while other numbers occur twice, 20 is the answer.
Constraints
0 <
n
<= 10^6
0 <=
arr[i]
<= 10^9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Sol",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int search(int n, 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) {\n\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n\n while (t-- > 0) {\n int n = sc.nextInt();\n int[] arr = new int[n];\n\n for (int i = 0; i < n; ++i) arr[i] = sc.nextInt();\n\n System.out.println(new Sol().search(n, arr));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GfG",
"solution": "// Back-end complete function Template for Java\nclass Sol {\n public static int bs(int arr[], int low, int high) {\n if (low == high) {\n return arr[low];\n }\n // Find the middle point\n int mid = (low + high) / 2;\n // If mid is even and element next to mid is\n // same as mid, then output element lies on\n // right side, else on left side\n if (mid % 2 == 0) {\n if (arr[mid] == arr[mid + 1]) return bs(arr, mid + 2, high);\n else return bs(arr, low, mid);\n } else // If mid is odd\n {\n if (arr[mid] == arr[mid - 1]) return bs(arr, mid + 1, high);\n else return bs(arr, low, mid - 1);\n }\n }\n\n public static int search(int n, int arr[]) {\n return bs(arr, 0, n - 1);\n }\n}\n",
"updated_at_timestamp": 1730468539,
"user_code": "// User function Template for Java\n\nclass Sol {\n public static int search(int n, int arr[]) {\n // your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"search(self, n, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n for tc in range(t):\n n = int(input())\n arr = list(map(int, input().split()))\n ob = Solution()\n print(ob.search(n, arr))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n\n # Binary search function for finding the single non-repeating element\n def bs(self, arr, low, high):\n if low == high:\n return arr[low]\n\n mid = (low + high) // 2\n\n # Check if mid is even\n if mid % 2 == 0:\n # If mid and next element are the same, the non-repeating element is to the right of mid\n if arr[mid] == arr[mid + 1]:\n return self.bs(arr, mid + 2, high)\n else:\n return self.bs(arr, low, mid)\n else:\n # If mid and previous element are the same, the non-repeating element is to the right of mid\n if arr[mid] == arr[mid - 1]:\n return self.bs(arr, mid + 1, high)\n else:\n return self.bs(arr, low, mid - 1)\n\n # Function to search the non-repeating element\n def search(self, n, arr):\n # Call the binary search function with initial low and high values\n return self.bs(arr, 0, n - 1)\n",
"updated_at_timestamp": 1730468539,
"user_code": "#User function Template for python3\nclass Solution:\n def search(self, n, arr):\n # your code here"
}
|
eJzNVM1KxEAM9iD4GqHnRabz02l9EsGKB+3By7iHLgii+BD6oN48mmTablsmpesuYidsZ+nky5d8k7yff35fnPFz/YWbm5fsMWx3bXYFmamDq0MOOWhwgFtfBx33oBUYMvye92c0GFwWF50osg1kzfO2uW+bh7unXduh6jq8IY7iV8G/2esGRnERsEJMBWhaDaHAsjklADuVAsNwhsAIjbAUB80doGk24xBWIqsiqHEpbFuHsg4KEHsogKVgqYoUHNiDhxJXBXzKdu5irmSFAi8RNMwrsqtiSaUysFDIC4mxGTbL5tgKOmEEOYm4QIL8FsQkPfkR3ONHwTmKRw/079+DuVFuiwVN38hJWbAoAoQVILB91jSIVMbB3ZP/AoAUf9/M+WJvzjzTYyD+yY8eBG7x6owCS4IlOc8Ek7VKN/ZErKPzP1Cp00+V+VCx+7FSert6spDj2rvpCnNQe5w46b/JejybpsNlNKr6+/NfMuyodSndflz+AA9zIm4=
|
712,540
|
Partition Array for Maximum Sum
|
Given an integer arrayarr, partition the array into (contiguous) subarrays of lengthat mostk. After partitioning, each subarray has their values changed to become the maximum value of that subarray.Returnthe largest sum of the given array after partitioning.
Examples:
Input:
n = 7
k = 3
arr = [1,15,7,9,2,5,10]
Output:
84
Explanation:
arr becomes [15,15,15,9,10,10,10]
Input:
n = 1
k = 1
arr = [1]
Output:
1
Constraint:
1 <= n <= 500
0 <= arr[i] <= 10**9
1 <= k <= n
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1667049219,
"func_sign": [
"public int solve(int N, int k, int arr[])"
],
"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 k=sc.nextInt();\n int []arr=new int[N];\n for(int i=0;i<N;i++){\n arr[i]=sc.nextInt();\n }\n Solution obj=new Solution();\n int res=obj.solve(N, k, arr);\n System.out.println(res);\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\n\nclass Solution{\n // function to solve the problem\n public int solve(int N, int k, int arr[]){\n // create an array to store the maximum score at each position\n int []dp=new int[N+1];\n \n // iterate over each position\n for(int i=1;i<=N;i++){\n int curmax=0, best=0;\n \n // choose the maximum score from previous k positions\n for(int j=1;j<=k && i-j>=0; j++){\n curmax= Math.max(curmax, arr[i-j]);\n best= Math.max(best, dp[i-j]+curmax*j);\n }\n \n // store the maximum score at current position\n dp[i]=best;\n }\n \n // return the maximum score at last position\n return dp[N];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n public int solve(int N, int k, int arr[]){\n //Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1667050151,
"func_sign": [
"solve(self, n, k, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n n, k = input().split()\n n = int(n)\n k = int(k)\n arr = list(map(int, input().split()))\n ob = Solution()\n print(ob.solve(n, k, arr))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find the maximum sum of elements by considering k elements.\n def solve(self, n, k, arr):\n # Initializing dp array with 0.\n dp = [0] * (n + 1)\n\n # Iterating from 1 to n.\n for i in range(1, n + 1):\n curmax = 0\n best = 0\n j = 1\n\n # Calculating the maximum value in the range i-j to i.\n while j <= k and i - j >= 0:\n curmax = max(curmax, arr[i - j])\n best = max(best, dp[i - j] + curmax * j)\n j += 1\n\n # Storing the maximum sum in the dp array for i elements.\n dp[i] = best\n\n # Returning the maximum sum from the dp array for n elements.\n return dp[n]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def solve(self, n, k, arr):\n # Code here"
}
|
eJzdVs1OhDAQ9uDRh5hwXk3/pgWfxESMB+XgBffAJiZG40Po+zptqVmFQZZlf3SHpZNCv/mf4e30w5ydhN/VOTHXz9lDvVw12SVksqylAAx3GUm0t7iWdbaArHpaVndNdX/7uGrSSUHPXunxywJ+ACKYskaIlIBFe6V95JE1MshKgC1rTXCG/ggFKLC06pbPaXXEaeI1j+9yDp+Ok/7+NElAwnaEWXi1C2JcEGYCvAQB3rLw6oAozYjSAkgLRZiSkL3qaTXBGC/RBXPsmpF5kB52WJkKLRcYIUJEu7b8ix3WIwWbqhgdokJGeRCM0VYdab0pgN+3v3J8/RqvJg6pGUs0ge2enaClic500CXdQ7aHVJcG8pxrE5YUQd+BNNniQV3oFwXFwJeSaYtO72qH950ZjvAe4rpdiNnWPra3I9/bJ/begzmPtdFoNUOFqBlKBKX5E97e5KPh2CKjpoXGCa4QpkxpNealg8/pGOffxqAUlms/I7I23+wDzemhaWb3Oc7yLeeqm61tSOlS37h5v/gEGZO3wA==
|
702,957
|
Closing bracket index
|
Given a string with brackets ('[' and ']') and the index of an opening bracket. Find the index of the corresponding closing bracket.
Examples:
Input:
S = "[ABC[23]][89]"
pos = 0
Output:
8
Explanation:
[
ABC[23]
]
[89]
The closing bracket corresponding to the
opening bracket at index 0 is at index 8.
Input:
S = "ABC[58]"
pos = 3
Output:
6
Explanation:
ABC
[
58
]
The closing bracket corresponding to the
opening bracket at index 3 is at index 6.
|
geeksforgeeks
|
Easy
|
{
"class_name": "Sol",
"created_at_timestamp": 1619436863,
"func_sign": [
"int closing(String s, int pos)"
],
"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 int pos = sc.nextInt();\n \t\tSystem.out.println (new Sol().closing (s, pos));\n \nSystem.out.println(\"~\");\n}\n \n }\n}\n// Contributed By: Pranay Bansal\n",
"script_name": "GfG",
"solution": "// Back-end complete function Template for Java\nclass Sol {\n // Function to find the closing bracket in a string starting from the given position\n int closing(String s, int pos) {\n int n = s.length();\n int cnt = 0;\n for (int i = pos; i < n; ++i) {\n // Increment the count if the character is '['\n if (s.charAt(i) == '[') cnt++;\n // Decrement the count if the character is ']'\n else if (s.charAt(i) == ']') cnt--;\n // Check if the count is zero, indicating that the closing bracket is found\n if (cnt == 0)\n // Return the index of the closing bracket\n return i;\n }\n // If the closing bracket is not found, return -1\n return -1;\n }\n}\n// Contributed By: Pranay Bansal\n",
"updated_at_timestamp": 1730469533,
"user_code": "//User function Template for Java\n\nclass Sol\n{\n int closing (String s, int pos)\n {\n // your code here \n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619436863,
"func_sign": [
"closing(self,s, pos)"
],
"initial_code": "# Initial Template for Python 3\n\nt = int(input())\nfor tc in range(t):\n s = input()\n pos = int(input())\n ob = Solution()\n print(ob.closing(s, pos))\n print(\"~\")\n# Contributed By: Pranay Bansal\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def closing(self, s, pos):\n cnt = 0\n\n # iterating over the string starting from the given position\n for i in range(pos, len(s)):\n # incrementing counter if \"[\" is encountered\n if s[i] == '[':\n cnt += 1\n # decrementing counter if \"]\" is encountered\n elif s[i] == ']':\n cnt -= 1\n # if the counter becomes 0, it means the closing bracket for the given position has been found\n if cnt == 0:\n return i\n\n # if no closing bracket is found, return -1\n return -1\n\n# Contributed By: Pranay Bansal\n",
"updated_at_timestamp": 1730469533,
"user_code": "#User function Template for python3\n\nclass Solution:\n def closing (self,s, pos):\n # your code here"
}
|
eJytlLtOw0AQRSngPyLXAcV2IIHOedhx7LwfBO5eUUAKGpMikZAQiI+AL6TjK1gvBBBiEicw1TZzdu6dx+Pu8+vejonJi37gzrpOZou5dZKzbJXAq6CKWh1+wEbIZsS4hXany16fKnGtfM6a3s6ml/Pp1cXNYr5MLKnkQSXWfT73A2c7cIs4PEKpzOMCvQqrNdR9BA2GTUaxhpYEqMg0QRMqsaWSClK6ByMRWiO1SGqVjDTJEUiOSIJHjaJBQaMQIkXF1JaxQ22axhYErOuu1Pel8V2naP2RhGEKkA1yxDy5ZjuDpwhgjIAxgksj+hxwyBHHq3om4c9xhglOMcYIQwzQRw9ddNBGCzEi/VmoGxnQZ501Vlmht80366equNmcuz62G/G0hJT6rY3/Y/H+2hau2AQ5+UO+Un9SnXGzxcn9vF3eRserLPIy5Yt7bMrZ+JY6Yjm/3IUsh4FPB2/6/umM
|
713,153
|
Minimum X (xor) A
|
Given two integersAandB, the task is to find an integerXsuch that(X XOR A)is minimum possible and the count of set bit inXis equal to the count of set bits inB.
Examples:
Input:
A = 3, B = 5
Output:
3
Explanation:
Binary(A) = Binary(3) = 011
Binary(B) = Binary(5) = 101
The XOR will be minimum when x = 3
i.e. (3 XOR 3) = 0 and the number
of set bits in 3 is equal
to the number of set bits in 5.
Input:
A = 7, B = 12
Output:
6
Explanation:
(7)
2
= 111
(12)
2
= 1100
The XOR will be minimum when x = 6
i.e. (6 XOR 7) = 1 and the number
of set bits in 6 is equal to the
number of set bits in 12.
Example 2:
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1671445695,
"func_sign": [
"public static int minVal(int a, int b)"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out = new PrintWriter(System.out);\n int t =\n Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n while (t-- > 0) {\n\n int a = Integer.parseInt(br.readLine().trim());\n int b = Integer.parseInt(br.readLine().trim());\n\n Solution ob = new Solution();\n out.println(ob.minVal(a, b));\n \nout.println(\"~\");\n}\n out.flush();\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n public static int minVal(int a, int b) {\n // code here\n int setBits = Integer.bitCount(b);\n int setBits1 = Integer.bitCount(a);\n int ans = 0;\n\n for (int i = 0; i <= 31; i++) {\n int mask = 1 << i;\n int set = a & mask;\n\n // If i'th bit is set also set the\n // same bit in the required number\n if (set == 0 && setBits > setBits1) {\n ans |= (mask);\n setBits--;\n } else if (set != 0 && setBits1 > setBits) {\n setBits1--;\n } else {\n ans |= set;\n }\n }\n\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public static int minVal(int a, int b) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1671445695,
"func_sign": [
"minVal(self, a, b)"
],
"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 a = int(input())\n b = int(input())\n\n ob = Solution()\n print(ob.minVal(a, b))\n print(\"~\")\n",
"solution": "class Solution:\n\n # Function to calculate the minimum value between two numbers.\n def minVal(self, a, b):\n # Counting the number of set bits in b.\n setBits = str(bin(b)).count(\"1\")\n # Counting the number of set bits in a.\n setBits1 = str(bin(a)).count(\"1\")\n # Initializing the answer variable.\n ans = 0\n\n # Iterating through each bit position.\n for i in range(32):\n # Creating a mask to check the current bit position.\n mask = 1 << i\n # Checking if the current bit is set in a.\n set = a & mask\n # If the current bit is not set in a and there are more set bits in b than in a,\n # then set the current bit in the answer.\n if set == 0 and setBits > setBits1:\n ans |= mask\n setBits -= 1\n # If the current bit is set in a and there are more set bits in a than in b,\n # then unset the current bit in the answer.\n elif set != 0 and setBits1 > setBits:\n setBits1 -= 1\n # If the current bit is the same in both a and b, then set the current bit in the answer.\n else:\n ans |= set\n\n # Returning the minimum value.\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def minVal(self, a, b):\n #code here"
}
|
eJy9Vc2OEzEM5rAX3qKa8wrFsWM7+wJ744zErDhAD1yGPXQlJLSjfQh4X5yfGWCbDG1BW1VpqsT+7M+f46erH29fv8qfd7e2ef9t+DzdPxyGm90Qxgns6zyOUwCftzRO3pGMkxsnWzWvMlzvhv3X+/3Hw/7Thy8Ph+qgmM7Ves5GtlJeJa/D4/XuN0i7TsjR7nlQsgBUUFMQQsLmw7MHSoGQBuEObPUwr9a2A0alFmJKyyMFFo3jFFU4EHozWn7raS/FchoLitl48S0YSocBufxY7uiFdY1LIZoZuciZXy1cdzCrh3l1Mi8O5sW6nScLQERjlYE1cRzSPnh1veySRb4619vNkmUKKlPm0Jh0hUqrfCURg8QOSLLmQl+xnFezZhrGooqLkN2SBxGvyRacKmPSiBIGCqGDt5wXzPV2Bw0xBLJoMn0GBWGVX6llD4YgEjqMRX5OLVbs8AepTXJAWYTgAHK7IVCGYxDQrgCr1GPJABCtyJ1kTCWwyCzHXiXUSyFf/ENn2z4vUvkZcfQ6eClSOLtKiNHeCK7v1EaZjjPd7qh/T0p9s1qXB9KLpJYsNSCSduvcCucI8Cy4IEjd7Puy4me6GvHFlJV5OCJjo7NO4envGl1jSI3ue/rc6IKNCOvfE1+hkxuJlNqDqI54+TXj46VD3heAZC+8PeaThP7P8H3+IrYm7933Nz8Bm02tNw==
|
700,434
|
Multiply Matrices
|
Given two square Matrices A[][] and B[][]. Your task is to complete the function multiply which stores the multiplied matricesin a new matrix C[][].
Examples:
Input:
N = 2
A[][] = {{7, 8}, {2 , 9}}
B[][] = {{14, 5}, {5, 18}}
Output:
C[][] = {{138, 179}, {73, 172}}
Input:
N = 2
A[][] = {{17, 4}, {17 , 16}}
B[][] = {{9, 2}, {7, 1}}
Output:
C[][] = {{181, 38}, {265, 50}}
Constraints:
1 <=T<= 100
1 <= N <= 20
|
geeksforgeeks
|
Easy
|
{
"class_name": "GfG",
"created_at_timestamp": 1617795742,
"func_sign": [
"public static void multiply(int A[][], int B[][], int C[][], int N)"
],
"initial_code": "import java.util.Scanner;\nclass Matrix{\n\tpublic static void main(String[] args){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();\n\t\twhile(t-- > 0){\n\t\t\tint n = sc.nextInt();\n\t\t\tint[][] a = new int[n][n];\n\t\t\tint[][] b = new int[n][n];\n\t\t\tint[][] c = new int[n][n];\n\t\t\tfor(int i = 0; i < n; i++)\n\t\t\t\tfor(int j = 0; j < n; j++)\n\t\t\t\t\ta[i][j]=sc.nextInt();\n\t\t\tfor(int i = 0 ;i < n; i++)\n\t\t\t\tfor(int j = 0; j < n; j++)\n\t\t\t\t\tb[i][j]=sc.nextInt();\n\t\t\tGfG g = new GfG();\n\t\t\tg.multiply(a,b,c,n);\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t{for (int j = 0; j < n; j++)\n\t\t\t\tSystem.out.print(c[i][j]+\" \");\n\t\t\t}\n\t\t\tSystem.out.println();\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "Matrix",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "/*Complete the function below*/\nclass GfG\n{\n public static void multiply(int A[][], int B[][], int C[][], int N)\n {\n //add code here.\n }\n}"
}
|
{
"class_name": null,
"created_at_timestamp": 1617795742,
"func_sign": [
"multiply(A, B, C, n)"
],
"initial_code": "if __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 matrix1 = [[0 for i in range(n)] for j in range(n)]\n c = 0\n for i in range(n):\n for j in range(n):\n matrix1[i][j] = arr[c]\n c += 1\n arr = list(map(int, input().strip().split()))\n matrix2 = [[0 for i in range(n)] for j in range(n)]\n c = 0\n for i in range(n):\n for j in range(n):\n matrix2[i][j] = arr[c]\n c += 1\n matrix3 = [[0 for i in range(n)] for j in range(n)]\n multiply(matrix1, matrix2, matrix3, n)\n for i in range(n):\n for j in range(n):\n print(matrix3[i][j], end=\" \")\n print('')\n print(\"~\")\n",
"solution": "def multiply(A, B, C, n):\n # Matrix multiplication\n for i in range(n): # iterate over rows of A\n for j in range(n): # iterate over columns of B\n for k in range(n): # iterate over columns of A and rows of B\n # multiply corresponding elements of A and B and add the result to C[i][j]\n C[i][j] += (A[i][k]*B[k][j])\n",
"updated_at_timestamp": 1729753320,
"user_code": "# Your task is to complete this function\n# function should store the multiplication in C\ndef multiply(A, B, C, n):\n # Code here"
}
|
eJy9ls1uXEUQhVmw5R1KXkeoq6t/qnkSJIxYgBdshiwcKRIC8QwIFrwt3+kbEyfy3ESRie/Yvneq6++cUzXzx5d///PVF/vn2z+5+e7Xm58vL1/d33xjN3578XJ7ad1mWq3my6Jbm5bLvLj1YbNbDYthrdl0G8OSo26xrC9bhXNWi0WxVqwXG8VmsSyHiV9X4Aj59y7/ORVikQFXrzt8M2og25iqZGeXq+9M1VpYbzYok/TTVmLnDHk9rLZd9LA+baTNN1U5/kdHlEYr1UbYbJbd1sA+sROnWe27vWk9baxdOr4FX4I77Q+LaS3Vr1pzW9gKtg86U5oPq9Mira2NjVtWW9gKNqL7tJobTbBzm9UybGEr2HzcXsauoW0Iq3VXFDIJpnl00nclDo4OVk6zTjCnXAcPB29Pzi3CkLQKsirYQRfOKoVVqq9gX8G3AlClgKDDAMEQBWAY1BigEMAcQ5jQenKOZhoNN9hqMNLqgi/6BZQGpW1IURBMXw3kunQF8x1qOq13wO1ir0sBiGRCNhj1pVYlKICDqQGMA6wHShlSA3QO4BoQMpYwET3wD6ITziaimBJth/ZRkR3ows9EXRMFJQpI2EkoTASYiCxRScJCimeElCkxAnMZ8Ipw4GGF+IFDqFhwsSBjwcYSHZsPEVLESBElRZwUkVLEShEtRbwUEVPETFmicAtCqvG65SMBN01B06jAEHKQaOEI5cpDMqkSYpXSK0QhAs1UaDjgyitkeYUtr9DlNeUh9YUkGlCGZDRFkOYBax7Q5gFvHhDnAXMeKQ+pvmmsmua2QZ+3qgmCQG8w6A0KvcGhN0j0lvJYW45smZsXdnP3+uXdj/d3P/3wy6v7NzuI6orkOOm7S4GVoDWpBn3maFBTwZ4kdY3RtGp8wlUAIklDMKBgktFS7ciWKH3mkKTrpGCU3RVl1tganxVZVc7DJBkSeMgg/UQpvPjXK1wFBOrJu+YJnLSUAoueOKenaGs/raWn1vKwHQPTp2akwYxsYwBo9Kq1h0l6jxE7Cp2g6piRCDkmEusK3doRekfpffshE0UZPeVXtULoaijtDMkiZk7ly1aVYcKPbHMe86qlGatoKmMxO9rbdMiMosKiVdmTDA01LQ1z9l1L9r77813LSlXde9vrbwublTBkA+Sy8y3ZMrZfru032CU6ufbuAAH1lz6LTk4NXawm/lrZyLcyJEJq7nuJ51jKLsVoFe0oxBBmnZKUoXf1NxkBZRibnKwb+czII8OOMqbyQfSOcthG2wgihc1DnzrJklBHOZsyrKMHDoD87eV3dP3bC3vvM/X2UvbriuTLiePxuuLoJ47UvB7+XnHHBnHlLIp/Ut0VRytc/ujmag/bfhKq7BPl0c3Veo7rrKp9Pbq5toXsuK6Eioe+VHl5t9V33jpt+tHJk0QPXf13PfnWByB5ez2VqFzxPq+n/Y8VnbT+/JmeEAZ79EQbmPmMOP49GdM+Z/kfqRF7FqDej69vIp86kBSe2s+fpfazZLrb36ueM+Hewf4RS9j5lM+3W/j7v77+FxHPEoU=
|
702,720
|
Count Increasing Subsequences
|
Given an array arr[] consisting of digits (where each digit ranges from 0 to 9), the task is to count all possible subsequences within the array where each digit in the subsequence is strictly greater than the previous digit. The final count should be returned modulo 10**9+7.
Examples:
Input:
arr[] = [1, 2, 3, 4]
Output:
15
Explanation:
There are total increasing subsequences {1}, {2}, {3}, {4}, {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, {3,4}, {1,2,3}, {1,2,4}, {1,3,4}, {2,3,4}, {1,2,3,4}.
Input:
arr[] = [4, 3, 6, 5]
Output:
8
Explanation:
Sub-sequences are {4}, {3}, {6}, {5}, {4,6}, {4,5}, {3,6}, {3,5}.
Input:
arr[] = [3, 2, 4, 5, 4]
Output:
14
Explanation:
Sub-sequences are {3}, {2}, {4}, {3,4}, {2,4}, {5}, {3,5}, {2,5}, {4,5}, {3,2,5}, {3,4,5}, {4}, {3,4}, {2,4}.
Expected Time Complexity:
O(n)
Expected Auxiliary Space:
O(1)
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1617733136,
"func_sign": [
"public static int countSub(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.countSub(arr);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function to count all the sub-sequences\n // possible in which digit is greater than\n // all previous digits\n public static int countSub(int[] arr) {\n int n = arr.length;\n final int MOD = 1000000007;\n // count[] array is used to store all sub-\n // sequences possible using that digit\n // count[] array covers all the digits\n // from 0 to 9\n int[] count = new int[10];\n // Scan each digit in arr[]\n for (int i = 0; i < n; i++) {\n // Count all possible sub-sequences by\n // the digits less than arr[i] digit\n for (int j = arr[i] - 1; j >= 0; j--) {\n count[arr[i]] = (count[arr[i]] + count[j]) % MOD;\n }\n // Store sum of all sub-sequences plus\n // 1 in count[] array\n count[arr[i]] = (count[arr[i]] + 1) % MOD;\n }\n // Now sum up all sequences possible in\n // the count[] array\n int result = 0;\n for (int i = 0; i < 10; i++) {\n result = (result + count[i]) % MOD;\n }\n return result;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n public static int countSub(int arr[]) {\n // Your code goes here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617733136,
"func_sign": [
"countSub(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.countSub(arr)\n print(res)\n t -= 1\n print(\"~\")\n",
"solution": "class Solution:\n\n def countSub(self, arr):\n MOD = 10**9 + 7\n\n # Initialize count array to store sub-sequences counts\n count = [0] * 10\n\n # Scan each digit in arr[]\n for i in range(len(arr)):\n # Count all possible sub-sequences by the digits less than arr[i]\n for j in range(arr[i] - 1, -1, -1):\n count[arr[i]] = (count[arr[i]] + count[j]) % MOD\n\n # Store sum of all sub-sequences plus 1 in count[] array\n count[arr[i]] = (count[arr[i]] + 1) % MOD\n\n # Sum up all sequences possible in the count[] array\n result = sum(count) % MOD\n\n return result\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def countSub(self, arr):\n # Your code goes here"
}
|
eJzlVUsKwjAQdeHCYwxZF+mkST+eRFBxoV24qS4qCKJ4CD2aOw/jWPGLr40KCtrX0ELzJjMvb5pVfbNr1IqrvZWXzlyNssk0Vy1S3M1YeaTS2SQd5OmwP57ml0/LbqYWHt3OT+gngKr2fVA3U0CWIuFqMhRSDCIkFgoXCz2UIEZCaULCJ4BvielvB9BKswngfmlBIDACKwgFkSAWlDggYI28z8JzGCByhJzBRaKmSPGQHgpg2bkpn/QW0x2e5F+v/ahXynKKKnOSG3BDh15DtaB1oTFc8nxFvIIj67psQJnbjxYq8Q9rWPNZr7f/8K5u+PoJIDg+sEWQvSr7DJ8Bn8PvnNVY5pPOvXVzD7nBF7k=
|
703,670
|
Difference between highest and lowest occurrence
|
Given an array, the task is to find the difference between the highest occurrence and lowest occurrence of any number in an array.Note: If only one type of element is present in the array return 0
Examples:
Input:
arr[] = [1, 2, 2]
Output:
1
Explanation:
Lowest occurring element (1) occurs once. Highest occurring element (2) occurs 2 times
Input:
arr[] = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
Output:
2
Explanation :
Lowest occurring element (2) occurs once. Highest occurring element (7) occurs 3 times
Constraints:
1<= arr.size() <=10**6
1<= arr[i] <=10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617637881,
"func_sign": [
"public int findDiff(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 =\n new Solution(); // Instantiate the Solution object once, not in the loop\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.findDiff(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\nclass Solution {\n // Function to find the difference between the maximum and minimum frequency of\n // elements.\n public int findDiff(int[] arr) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617637881,
"func_sign": [
"findDiff(self, arr)"
],
"initial_code": "def main():\n T = int(input())\n\n while T > 0:\n a = list(map(\n int,\n input().strip().split())) # Convert input to list of integers\n print(Solution().findDiff(a))\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n def findDiff(self, arr):\n from collections import Counter\n\n # Count the frequency of each element using Counter\n freq = Counter(arr)\n\n # Extract the frequencies and compute max and min frequency\n counts = list(freq.values())\n max_count = max(counts)\n min_count = min(counts)\n\n # Return the difference between maximum and minimum frequency\n return max_count - min_count\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findDiff(self, arr):\n # code here\n \n \n \n "
}
|
eJztV01v1DAQ5cCdv/CUc4Xiz9j8EiQWcYA9cAk9bBESqsSPgP/L89gJSWN3d1sopSLemdl2E8/HezPe/fb8x/WLZ3K9/sw3b752H8fLq0P3Cp3bjaqXC1EuuPxXMdOHs81rN8rNAUsz1IyfHsmPcR9oiqHY7AaeMlBCCqL4Kg4ilibUTNXrQE/QMLBw8BjAm7lvd4Fu/+Vy//6w//Du09WhFMHsRtaBPrXo7voCixKlT1c1cctS6LR2o8n/s6s7fDZDNqGUeVXQX+W/aSv5T6aRRi/Rq00Ctl4MKMavoQyUhXJQhGqAClCREGWosqgiuogpYou4Ij7Jmhpxy6BKfoElRlqWy3ClqhbOHEtWb/LVKd8FOrLjtOy8ssdtAxwl17HU2izbxprJhaXYG2KK6BmPhqx75oRm8TUjBaEz+qR7RkQak8KkL6mbHDXS8432SezTxjoP0QNEB4jmuEmaPpJWEK0h2kB0IphscDcWp3LwTmbM/ByiReTGGlGldBhACAjczCM4BItgEBiAYr7VGbRF/ZZq38rdvsGHNYh1cjaYl0o0EV2XVQavm8ZT4pKQKT+1UGX/SRrBZ5BNreuc0CW/rBBIp62nTiv9bVchzucCweVwMRwslkPFcaB4DpShJzY969mnwgvcArhALqAL7AK8QC/gC/xCAN2iq61xNQXSxqxyM57EOjnlR3CS/MFz4969x7wfoPtMrft+99yIDxf6XY5r87fO6/mb7zljQp44q8kewYEZ/5ET86mVa/4xcUI1TvyuH9X/GX3WjJZdpl8G9x550uJvv7/8CQ2lb2c=
|
701,344
|
Maximum of minimum for every window size
|
Given an integer arrayarr[]of sizeN. The task is to find the maximum of the minimum of every window size in the array.Note:Window size varies from1to theN.
Examples:
Input:
N = 7
arr[] = {10, 20, 30, 50, 10, 70, 30}
Output:
{70, 30, 20, 10, 10, 10, 10}
Explanation:
1. First element in output indicates maximum of minimums of all
windows of size 1.
2. Minimums of windows of size 1 are {10}, {20}, {30}, {50},{10},
{70} and {30}. Maximum of these minimums is 70.
3. Second element in output indicates maximum of minimums of all
windows of size 2.
4. Minimums of windows of size 2 are {10}, {20}, {30}, {10}, {10},
and {30}.
5. Maximum of these minimums is 30
Third element in output indicates maximum of minimums of all
windows of size 3.
6.
Minimums of windows of size 3 are {10}, {20}, {10}, {10} and {10}.
7. Maximum of these minimums is 20.
Similarly other elements of output are computed.
Input:
N = 3
arr[] = {10, 20, 30}
Output:
{30, 20, 10}
Explanation:
First element in output indicates maximum of minimums of all
windows of size 1. Minimums of windows of size 1 are {10} , {20} , {30}. Maximum of these minimums are 30 and similarly other outputs can be computed
Constraints:
1 <= N <= 10**5
1 <= arr[i] <= 10**6
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int[] maxOfMin(int[] arr, int n)"
],
"initial_code": "import java.util.*;\nimport java.io.*;\n\nclass Main {\n\n public static void main(String[] args) throws IOException {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim());\n while (t-- > 0) {\n String[] inputline = br.readLine().trim().split(\" \");\n int n = Integer.parseInt(inputline[0]);\n inputline = br.readLine().trim().split(\" \");\n int[] arr = new int[n];\n for (int i = 0; i < n; i++) {\n arr[i] = Integer.parseInt(inputline[i]);\n }\n Solution ob =new Solution();\n int[] res = ob.maxOfMin(arr, n);\n \n for (int i = 0; i < n; i++) \n System.out.print (res[i] + \" \");\n System.out.println ();\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730270838,
"user_code": "\nclass Solution \n{\n //Function to find maximum of minimums of every window size.\n static int[] maxOfMin(int[] arr, int n) \n {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxOfMin(self,arr,n)"
],
"initial_code": "# Initial Template for Python 3\n\nimport atexit\nimport io\nimport sys\n\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 n = int(input())\n a = list(map(int, input().strip().split()))\n ob = Solution()\n res = ob.maxOfMin(a, n)\n for i in range(len(res)):\n print(res[i], end=\" \")\n print()\n\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find maximum of minimums of every window size.\n def maxOfMin(self, a, n):\n # stack used to find previous and next smaller numbers.\n stack = []\n # using arrays to store previous and next smaller numbers.\n left = [-1 for i in range(n)]\n right = [n for i in range(n)]\n\n # filling elements of left[] using logic discussed in\n # next greater element problem.\n for i in range(n):\n while len(stack) and a[stack[-1]] >= a[i]:\n stack.pop()\n if len(stack):\n left[i] = stack[-1]\n stack.append(i)\n\n # emptying the stack as stack is going to be used for right[].\n stack = []\n\n # filling elements of right[] using same logic.\n for i in range(n - 1, -1, -1):\n while len(stack) and a[stack[-1]] >= a[i]:\n stack.pop()\n if len(stack):\n right[i] = stack[-1]\n stack.append(i)\n\n # creating and initializing answer list.\n ans = [0 for i in range(n + 1)]\n\n # filling answer list by comparing minimums of all\n # lengths computed using left[] and right[].\n for i in range(n):\n # length of the interval.\n length = right[i] - left[i] - 1\n # a[i] is a possible answer for this length 'length' interval,\n # check if a[i] is more than max for 'length'.\n ans[length] = max(ans[length], a[i])\n\n # some entries in ans[] may not be filled yet. Filling\n # them by taking values from right side of ans[].\n for i in range(n - 1, -1, -1):\n ans[i] = max(ans[i], ans[i + 1])\n\n # returning the answer list.\n return ans[1:]\n",
"updated_at_timestamp": 1730270838,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to find maximum of minimums of every window size.\n def maxOfMin(self,arr,n):\n # code here"
}
|
eJy1VUtOxDAMZcGCY1hdj1CcT5tyEiSKWMAs2JRZzEhIaBCHgPOx4xzYTtJ0kNJ2YKhdtUr9e/GL+3b+8XVxJtf1J73cvFSP/Wa3ra6gwq5H1fUOEAxYqEFDAx4ctNUKqvXzZn2/XT/cPe220aGl745ER0GSrn/t+mq/gh+BNQdXoOl2olpBo8ArQHk3CiyvF1KxH459g+KhlpI7ugkTV6ip3lpwtZKZlghqISsZtGTZkIcbEGYppNO0iRacJAtJQzoOYmllFBXnE7NHFlxYAiMeF28H+Nzagy3AvLxkG1KkaSnUJWXJBa1c4eHDowmPcjdmPYsMUJl+RjHVmEcKasUsZBpS2ECxEgNRRRsffeoYw8aYiaKFEjxzMEHQCYRJMGwEMoPdRj4EMk4QMBDbSMu4ddJDpFUqwgISk4h9xFEP2MhJKh1y+cZGrE7UiCIrtYGChzGQ+DlxCo1UhTxTCEAtTk6I2ExMGR9TmAG6niPaXLITZwtj0x3MTVUenGSZtkwPsvDI/PrEDGdkFGYpWYnjx/E1e/yVsXg8ZcXpNJwdNbbOf8SJ1so3qX9Bb3N4HiILMyTbSKIjksA/QZiZrC6NVijN1sFoaq6WZmtxYlf72/fLb5Y+IwQ=
|
707,314
|
Max Min
|
Given an array A of size N of integers. Your task is to find the sum ofminimum and maximum elementin thearray.
Examples:
Input:
N = 5
A[] = {
-2, 1, -4, 5, 3}
Output:
1
Explanation:
min = -4, max = 5. Sum = -4 + 5 = 1
Input:
N = 4
A[] = {
1, 3, 4, 1}
Output:
5
Explanation:
min = 1, max = 4. Sum = 1 + 4 = 5
Constraints:
1 <= N <= 10**5
-10**9
<= A
i
<= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1620210852,
"func_sign": [
"public static int findSum(int A[],int N)"
],
"initial_code": "//Initial Template for Java\n\n//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\nclass Array {\n\tpublic 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 int a[] = new int[n];\n \n for(int i=0;i<n;i++){\n a[i] = sc.nextInt();\n }\n \n Solution ob = new Solution();\n \n System.out.println(ob.findSum(a,n));\n \nSystem.out.println(\"~\");\n}\n \n\t}\n}",
"script_name": "Array",
"solution": "//User function Template for Java\nclass Solution\n{ \n public static int findSum(int A[],int N) \n {\n //code here\n int max=Integer.MIN_VALUE;\n int min=Integer.MAX_VALUE;\n int sum=0;\n for(int i=0;i<A.length;i++)\n {\n if(A[i]>max)\n {\n max=A[i];\n }\n if(A[i]<min)\n {\n min=A[i];\n }\n }\n sum=max+min;\n return sum;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution\n{ \n public static int findSum(int A[],int N) \n {\n //code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1620212277,
"func_sign": [
"findSum(self,A,N)"
],
"initial_code": "# Initial Template for Python 3\n\nt = int(input())\nfor _ in range(0, t):\n n = int(input())\n a = list(map(int, input().split()))\n ob = Solution()\n print(ob.findSum(a, n))\n print(\"~\")\n",
"solution": "class Solution:\n # Function to find the sum of maximum and minimum elements in an array\n def findSum(self, arr, arr_size):\n max_val = 0\n min_val = 0\n i = 0\n\n # If the array size is odd, initialize max and min as the first element\n if arr_size % 2 == 1:\n max_val = arr[0]\n min_val = arr[0]\n i = 1\n else:\n # If the array size is even, compare the first two elements to determine max and min\n if arr[0] < arr[1]:\n max_val = arr[1]\n min_val = arr[0]\n else:\n max_val = arr[0]\n min_val = arr[1]\n i = 2\n\n # Iterate through the array in pairs, comparing and updating max and min values\n while i < arr_size:\n if arr[i] < arr[i + 1]:\n if arr[i] < min_val:\n min_val = arr[i]\n if arr[i + 1] > max_val:\n max_val = arr[i + 1]\n else:\n if arr[i] > max_val:\n max_val = arr[i]\n if arr[i + 1] < min_val:\n min_val = arr[i + 1]\n i = i + 2\n\n # Return the sum of the maximum and minimum elements\n return max_val + min_val\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def findSum(self,A,N): \n #code here\n"
}
|
eJzFVMtKBDEQ9CD4G82cjUwnmZnE7/Ag7IoH3YOX0cMKgih+hP6v1T2PrI+WWRHsJZnKJqmuVB4vh2+rowON8zOA1WN109/db6tTqnjdt+vecT0F1bTTcHkKKsg1dV0dU7V5uNtcbTfXl7f325GuXvfP6756OqaPORgdDX35GSxs0SRIbaDKowSR6kUtxZqCpciZZBmyyFOgCCktdZQo7yuoE++gB3LIRThDriXXWVrSD/YEykLEDZTIAiMxaBO1FlljkTW6oeRVDyfhA1VLnuEYVDJLFihO5K0Fe4Pc16IWNFLJWZCTkfCBeciDkmEASkYGlAwRKBn2oGSsCCXDssx7HiGPZTV6JoPUXirWdpS6U6j/an+rbZ2QhmOdpxmDevnoIB5YlICVwOkMVh6Owz1QrHQsswzx0mXoD+hwnmMXU2gjrJ9gR7vXb8nlG/sLUgsGWJD6NMCC1KEBFlTyl/QlO5XcaQyagevGoBm4dgyagWvGoBm4OAbNwIUxaALmnf7O41mKMevz8EndwuHe3vU/uya8xz3JYdFb+8vHtpyThfak5UPNJVkbWh61/9gAU67r8vSgX7yevANTa9si
|
707,939
|
Count the Substrings
|
Given a stringS. The task is to count the number of substrings which contains equal number of lowercase and uppercase letters.
Examples:
Input:
S = "gEEk"
Output:
3
Explanation:
There are 3 substrings of
the given string which satisfy the
condition. They are "gE", "gEEk" and "Ek".
Input:
S = "WomensDAY"
Output:
4
Explanation:
There are 4 substrings of
the given string which satisfy the
condition. They are "Wo", "ensDAY",
"nsDA" and "sD"
Constraints:
1 ≤ |S| ≤ 10**3
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1624364410,
"func_sign": [
"int countSubstring(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 \n while(t-- > 0){\n String S = read.readLine().trim();\n Solution ob = new Solution();\n int ans = ob.countSubstring(S);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n } \n} ",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution \n{ \n int countSubstring(String S) \n { \n // code here\n }\n} \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1624364410,
"func_sign": [
"countSubstring(self, S)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n S = input()\n ob = Solution()\n ans = ob.countSubstring(S)\n print(ans)\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n def countSubstring(self, S):\n ans = 0\n for i in range(len(S)):\n c = 0\n for j in range(i, len(S)):\n # if current character is a lowercase letter, increase the count\n if ord(S[j]) >= ord('a') and ord(S[j]) <= ord('z'):\n c += 1\n # if current character is not a lowercase letter, decrease the count\n else:\n c -= 1\n # if the count becomes 0, it means we have found a valid substring\n if c == 0:\n ans += 1\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def countSubstring(self, S): \n #code here"
}
|
eJyllUtvgkAUhbto0r9hWJtGMZq2O0BqrSj4QqU2DS+fM4AIiDRtuuyum/b/lmkX1cXVwV4SQkL4hjnnnjtv518fF2c/NXxPHx6embnjhQFzk2OKY0c3TMueTGfzxRJhx/VW/joIo0281cYOk88xduzZZmBbT24Y/H31mr58yef2URwvVMXb2l39viE1W7LS7nR7fXUwHGngIgm4CFuBVjEES5zUZvVFAzUd2Wv73aAfDeIRzCpWrgFYkiSapu3eQUgJYnA6uXiDNwRTMKtW1RJt0YZ/hoX0w02n5cqesmr7nXU36IX9SN0M4uF2lGg6ByvFlgGgpxAYwREgQRIowRLwCUCelE7KIMWlG+cMzuB1Lt2+zoPEcgEASmkh5LqyqqoRQkhVJQljrCgKxogUiLwCLd3GmygM1v7Kcx2Mlov5bDqxLdPQ4f48oQv3TOeOu16AJNgh0ShM02Klg3KfnNRfn1BGo1g6n44ke9dGiqhkdxocav+wJ7M/VL6I1CM0y8SiGBeH2ruYJeG0Eac8AqiES3vp8CFRpos6lVoUOj1+Xn4DF3STpQ==
|
705,802
|
Moving on grid
|
Given a grid on XY plane with dimensions rx c, the twoplayers (say JONand ARYA) can move the coin over the grid satisfying the following rules:
Examples:
Input:
r = 1, c = 2
Output:
JON
Explanation:
ARYA lost the game because
he won't able to move after JON's move.
Input:
r = 2, c = 2
Output:
ARYA
Explanation:
After first move by JON(1,2 or 2,1)
and second move by ARYA(2,2) JON won't able to
move so ARYA wins.
Your Task:
You dont need to read input or print anything. Complete the function
movOnGrid()
which takes rand cas input parameter and returns the name of the winner ( either JONor ARYA)
.
Expected Time Complexity:
O(1)
Expected Auxiliary Space:
O(1)
Constraints:
1 <= r, c<=10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public String movOnGrid(int r, int c)"
],
"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 r = Integer.parseInt(input[0]); \n int c = Integer.parseInt(input[1]); \n Solution ob = new Solution();\n System.out.println(ob.movOnGrid(r,c));\n }\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730479562,
"user_code": "//User function Template for Java\nclass Solution\n{\n public String movOnGrid(int r, int c)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"movOnGrid(self, r, c)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n r, c = map(int, input().strip().split())\n ob = Solution()\n print(ob.movOnGrid(r, c))\n print(\"~\")\n",
"solution": "class Solution:\n def movOnGrid(self, r, c):\n # check if the row index modulo 7 is equal to the column index modulo 4\n if (r-1) % 7 == (c-1) % 4:\n # if the condition is true, return 'ARYA'\n return 'ARYA'\n else:\n # if the condition is false, return 'JON'\n return 'JON'\n",
"updated_at_timestamp": 1731598639,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef movOnGrid(self, r, c):\n\t\t# code here\n"
}
|
eJxrYJnqzs4ABhEOQEZ0tVJmXkFpiZKVgpKhQUyeoQEIKFiCQEwemFKAiMXkmYKlzE3BHDClYAqRMVYwjckzUbAA6VcwBLINFQzBZoH0xuQZKRjH5CnpKCilVhSkJpekpsTnl5ZALfXy94vJq4vJcwyKdAQzYALoNFwBJgNdqVKtjgKSvxDuUQB50VzBJCbPAuRiQxOwAA6X4TQeQwLNPiOE/w0gQQAOJGKtwWoa1AyYkQSDE4dhhrBYNMXrJty6DRWMSNVlDEtHWBMVaoIjNZFgcSDCPAuy/GdIKJ6w2Qn0DmlWQVMfyYmSYO4gnIqokYwIlxSmsKICGP2klBSDuKigVVkBjhiQRfhihFSDCCYwwjbhSvF4Cg78qY7SZIeeiA2paxyxrkMKl9gpegB5yTjh
|
707,041
|
IPL 2021 - Match Day 1
|
Due to the rise of covid-19 cases in India, this year BCCI decided to organize knock-out matches in IPL rather than a league.
Examples:
Input:
A = (3, 2)
B = (3, 4)
c = (2, 2)
Output:
2.000000 0.000000
Explanation:
There are two options for
point D : (2, 4) and (2, 0) such that ABCD
forms a parallelogram. Since (2, 0) is
lexicographically smaller than (2, 4). Hence,
(2, 0) is the answer.
Constraints:
1 ≤ x, y ≤ 1000, where x and y denote coordinates of points A, B, and C.
The order of points in the parallelogram doesnt matter.
The given points are not collinear.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1618213656,
"func_sign": [
"public double[] findPoint(int A[], int B[], int C[])"
],
"initial_code": "//Initial Template for Java\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 int A[] = new int[2];\n \t\tint B[] = new int[2];\n \t\tint C[] = new int[2];\n A[0]=sc.nextInt();\n A[1]=sc.nextInt();\n B[0]=sc.nextInt();\n B[1]=sc.nextInt();\n C[0]=sc.nextInt();\n C[1]=sc.nextInt();\n\t\t \n\t\t Solution ob = new Solution();\n\t\t \n\t\t double[] ans = ob.findPoint(A, B, C);\n\t\t String a1 = String.format(\"%.6f\",ans[0]);\n\t\t String a2 = String.format(\"%.6f\",ans[1]);\n\t\t System.out.println(a1+\" \"+a2);\n\n \nSystem.out.println(\"~\");\n}\n \n }\n}",
"script_name": "GfG",
"solution": "class Solution {\n public class Point {\n double x, y;\n\n Point(double x, double y) {\n this.x = x;\n this.y = y;\n }\n }\n\n public class CustomSort implements Comparator<Point> {\n public int compare(Point a, Point b) {\n if (a.x < b.x) return -1;\n else if (a.x > b.x) return 1;\n else {\n if (a.y < b.y) return -1;\n else return 1;\n }\n }\n }\n\n // method to calculate the distance between two points\n public double dis(Point a, Point b) {\n double ans = Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);\n return Math.sqrt(ans);\n }\n\n // method to calculate the slope between two points\n public double slope(Point a, Point b) {\n if (a.x == b.x) return Double.MAX_VALUE;\n double ans = (a.y - b.y) / (a.x - b.x);\n return ans;\n }\n\n // method to find the missing point given two other points\n public Point findMissingPoint(Point A, Point B, Point C) {\n double dis = dis(B, C);\n double m = slope(B, C);\n Point a1 = new Point(0.0d, 0.0d);\n Point a2 = new Point(0.0d, 0.0d);\n if (m == Double.MAX_VALUE) {\n a1.x = A.x;\n a1.y = A.y + dis;\n a2.x = A.x;\n a2.y = A.y - dis;\n } else {\n a1.x = A.x + (dis / Math.sqrt(1 + (m * m)));\n a2.x = A.x - (dis / Math.sqrt(1 + (m * m)));\n a1.y = m * (a1.x - A.x) + A.y;\n a2.y = m * (a2.x - A.x) + A.y;\n }\n if (dis(C, a1) == dis(A, B)) return a1;\n else return a2;\n }\n\n // main method to find the missing point in a triangle\n public double[] findPoint(int[] A, int[] B, int[] C) {\n ArrayList<Point> l1 = new ArrayList<>();\n Point a = new Point((double) A[0], (double) A[1]);\n Point b = new Point((double) B[0], (double) B[1]);\n Point c = new Point((double) C[0], (double) C[1]);\n l1.add(findMissingPoint(a, b, c));\n l1.add(findMissingPoint(a, c, b));\n l1.add(findMissingPoint(b, a, c));\n l1.add(findMissingPoint(b, c, a));\n l1.add(findMissingPoint(c, a, b));\n l1.add(findMissingPoint(c, b, a));\n // sorting the points in ascending order\n Collections.sort(l1, new CustomSort());\n double[] ans = {l1.get(0).x, l1.get(0).y};\n return ans;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution\n{\n public double[] findPoint (int A[], int B[], int C[])\n {\n // your code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618213656,
"func_sign": [
"findPoint(self, A, B, C)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n A = []\n B = []\n C = []\n input1 = [int(x) for x in input().strip().split(\" \")]\n A.append(input1[0])\n A.append(input1[1])\n input2 = [int(x) for x in input().strip().split(\" \")]\n B.append(input2[0])\n B.append(input2[1])\n input3 = [int(x) for x in input().strip().split(\" \")]\n C.append(input3[0])\n C.append(input3[1])\n\n ob = Solution()\n ans = ob.findPoint(A, B, C)\n print(\"{:.6f}\".format(ans[0]), \"{:.6f}\".format(ans[1]))\n\n print(\"~\")\n",
"solution": "# Back-end complete function Template for python3\n\nimport math\n\n\nclass Solution:\n # Function to find the two points on the line segment.\n def findPoints(self, source, m, l):\n a = [0]*2\n b = [0]*2\n\n # If slope is 0, then move l units on the x-axis in both directions.\n if (m == 0):\n a[0] = source[0] + l\n a[1] = source[1]\n\n b[0] = source[0] - l\n b[1] = source[1]\n\n # If slope is infinity, then move l units on the y-axis in both directions.\n elif (m == float(\"inf\")):\n a[0] = source[0]\n a[1] = source[1] + l\n\n b[0] = source[0]\n b[1] = source[1] - l\n\n # For other slopes, calculate the change in x and y coordinates\n # using the slope and l.\n else:\n dx = (l / math.sqrt(1 + (m * m)))\n dy = m * dx\n a[0] = source[0] + dx\n a[1] = source[1] + dy\n b[0] = source[0] - dx\n b[1] = source[1] - dy\n\n return [a, b]\n\n # Function to find the slope of a line given two points on the line.\n def findSlope(self, p, q):\n # If y-coordinates are equal, the line is horizontal.\n if (p[1] == q[1]):\n return 0\n # If x-coordinates are equal, the line is vertical.\n if (p[0] == q[0]):\n return float(\"inf\")\n # Otherwise, calculate the slope using the formula.\n return (q[1] - p[1]) / (q[0] - p[0])\n\n # Function to find the distance between two points using the distance formula.\n def findDistance(self, p, q):\n return math.sqrt(math.pow((q[0] - p[0]), 2) + pow((q[1] - p[1]), 2))\n\n # Function to find the missing point on the line segment.\n def findMissingPoint(self, a, b, c):\n ans = [0]*2\n d = self.findPoints(a, self.findSlope(b, c), self.findDistance(b, c))\n # Check if the distance between d and c is equal to the distance between a and b.\n if (self.findDistance(d[0], c) == self.findDistance(a, b)):\n ans[0] = d[0][0]\n ans[1] = d[0][1]\n else:\n ans[0] = d[1][0]\n ans[1] = d[1][1]\n return ans\n\n # Function to find the point that is closest to the origin.\n def findPoint(self, A, B, C):\n ans = []\n # Find the missing point for each combination of points.\n ans.append(self.findMissingPoint(A, B, C))\n ans.append(self.findMissingPoint(A, C, B))\n ans.append(self.findMissingPoint(B, A, C))\n ans.append(self.findMissingPoint(B, C, A))\n ans.append(self.findMissingPoint(C, B, A))\n ans.append(self.findMissingPoint(C, A, B))\n # Sort the points and return the first (closest to the origin).\n ans.sort()\n return ans[0]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def findPoint(self, A, B, C):\n # code here"
}
|
eJy1lb1OxDAMxxlYmNiYrc7Xk53GbcOTIFHEADewlBvuJCQE4iHgfXFS+nGlaVLu6HCxnMj+xX/H93H+dXVx5r6bSzFuX5OnervfJdeQqKo2xgAhYlXb36EpO9YCJY4MQcvCCDkmK0g2L9vNw27zeP+83/3EkuNrdB/0ZlW/V3VK2O7g0J+8rWAAk0k2EKIMtGSC3GFIdpfe5ncAlkCMAkphF1w5RUDKA5XSZGYhmkbi1pvPgJLkVELJgliUFsJ6SAFlYvhImHUbXJdz4dWBFFafRgkgJwDbRQFLuVgDsyff9P102TGYGQQRQCFksqcloSw5QmHL3xS86QlidyJWsxAnHYBO4y+Vc0I4W8Vhp7vVp5kxXb0oJu74JZ0grjsTH5oi41pRuFWH0XnIejxxdf+65eBCZqCYQiCGtBs9uqYXQ88u755dalhlfyqLdo5waYwuFsSfnyMRolB3HTDMSxqfFnR+auaV6eaVwZMMrJTKUcLIqeWtrxtnx9c41YEaB9Q9WkZfAA+JX3XE303n64RBe0tXhAQYJBxNgv/4T+kneKCfqb/CIf/d5/obfctfkA==
|
701,399
|
Reach a given score
|
Consider a game where a player can score 3 or 5 or 10 points in a move. Given a total score n, find number of distinct combinations to reach the given score.
Examples:
Input:
n = 10
Output:
2
Explanation
There are two ways {5,5} and {10}.
Input:
n = 20
Output:
4
Explanation
There are four possible ways. {5,5,5,5}, {3,3,3,3,3,5}, {10,10}, {5,5,10}.
1 ≤
n≤ 5*10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Geeks",
"created_at_timestamp": 1619173522,
"func_sign": [
"public long count(int n)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\npublic class GFG {\n public static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n int t=in.nextInt();\n while(t > 0)\n {\n int n = in.nextInt();\n Geeks obj = new Geeks();\n System.out.println(obj.count(n));\n t--;\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Geeks \n{\n public long count(int n) \n {\n long[] dp = new long[(int)n+1];\n Arrays.fill(dp, 0);\n dp[0] = 1;\n for (int i = 3; i <= n; i++) dp[i] += dp[i - 3]; // For every points (3,5,10) you need to add the number of ways to reach that sum \n for (int i = 5; i <= n; i++) dp[i] += dp[i - 5]; // before adding these points.\n for (int i = 10; i <= n; i++) dp[i] += dp[i - 10];\n \n return dp[n];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// Complete this function!\n\nclass Geeks {\n public long count(int n) {\n // Add your code here.\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1627041237,
"func_sign": [
"count(self, n: int) -> int"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n n = int(input())\n ob = Solution()\n print(ob.count(n))\n print(\"~\")\n",
"solution": "class Solution:\n def count(self, n: int) -> int:\n table = [0] * (n + 1)\n table[0] = 1 # If 0 sum is required, the number of ways is 1.\n\n for i in range(3, n + 1):\n # For every point (3, 5, 10), add the number of ways to reach that sum before adding these points.\n table[i] += table[i - 3]\n for i in range(5, n + 1):\n table[i] += table[i - 5]\n for i in range(10, n + 1):\n table[i] += table[i - 10]\n\n return table[n]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def count(self, n: int) -> int:\n #your code here\n "
}
|
eJyl000KwjAQBWAXPUjJukgmk6mtJxGsuNAu3MQuKgj+IHgFva+2tgulL0HtKhC+zJtheonu12jUfrPj8zA/qI2rdrWaxooKx1olsSr3Vbmqy/Vyu6u7u0nhzoVTpyR+B4IAWSBII2IRMZCQIMPQMBOOBpFlmE6gMqQzxAQXyziD1ZqMuDPLOKYHErNgKUjhiKFhaj1k9T/9ib8mmYALFR9+QLcL0FO4B0aCs/p+XC18bZK/d4t5Lz+j/JDFUBPE86fqLM0pTfPOL27jB1d1X1Y=
|
702,105
|
Word Boggle
|
Given a dictionary of distinct words and an M x N board where every cell has one character. Find all possible words from the dictionary that can be formed by a sequence of adjacent characters on the board. We can move to any of 8 adjacent characters
Examples:
Input:
N = 1
dictionary = {"CAT"}
R = 3, C = 3
board = {{C,A,P},{A,N,D},{T,I,E}}
Output:
CAT
Explanation:
C
A P
A
N D
T
I E
Words we got is denoted using same color.
Input:
N = 4
dictionary = {"GEEKS","FOR","QUIZ","GO"}
R = 3, C = 3
board = {{G,I,Z},{U,E,K},{Q,S,E}}
Output:
GEEKS QUIZ
Explanation:
G
I
Z
U
E
K
Q
S
E
Words we got is denoted using same color.
Constraints:
1 ≤ N≤ 15
1 ≤ R, C≤ 50
1 ≤ length of Word≤ 60
Each word can consist of both lowercase and uppercase letters.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public String[] wordBoggle(char board[][], String[] dictionary)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\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 while(t>0)\n {\n int N = sc.nextInt();\n String[] dictionary = new String[N];\n for(int i=0;i<N;i++)\n {\n dictionary[i] = sc.next();\n }\n \n int R = Integer.parseInt(sc.next());\n int C = Integer.parseInt(sc.next());\n \n char board[][] = new char[R][C];\n for(int i=0;i<R;i++)\n {\n for(int j=0;j<C;j++)\n {\n board[i][j] = sc.next().charAt(0);\n }\n }\n \n Solution obj = new Solution();\n String[] ans = obj.wordBoggle(board, dictionary);\n \n if(ans.length == 0) System.out.println(\"-1\");\n else\n {\n Arrays.sort(ans);\n for(int i=0;i<ans.length;i++)\n {\n System.out.print(ans[i] + \" \");\n }\n System.out.println();\n }\n \n t--;\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n private boolean search(char board[][], String word, int index, int i, int j) {\n int n = board.length;\n int m = board[0].length;\n // If position of the cell is inside the board or not\n if (i < 0 || i > n - 1 || j < 0 || j > m - 1) return false;\n // If the current cell does not match the letter at index\n if (word.charAt(index) != board[i][j]) return false;\n // If each character is matched\n if (index == word.length() - 1) return true;\n char ch = board[i][j];\n board[i][j] = '#';\n // Search for adjacent indices\n int dx[] = {-1, 0, +1, -1, +1, -1, 0, +1};\n int dy[] = {+1, +1, +1, 0, 0, -1, -1, -1};\n for (int x = 0; x < dx.length; x++) {\n if (search(board, word, index + 1, i + dx[x], j + dy[x])) {\n board[i][j] = ch;\n return true;\n }\n }\n\n board[i][j] = ch;\n return false;\n }\n\n private boolean exist(char board[][], String word) {\n for (int i = 0; i < board.length; i++)\n for (int j = 0; j < board[0].length; j++) if (search(board, word, 0, i, j)) return true;\n return false;\n }\n\n public String[] wordBoggle(char board[][], String[] dictionary) {\n List<String> wordslist = new ArrayList<String>();\n for (int i = 0; i < dictionary.length; i++)\n if (exist(board, dictionary[i])) wordslist.add(dictionary[i]);\n String[] ans = wordslist.toArray(new String[0]);\n // Arrays.sort(ans);\n return ans;\n }\n}\n",
"updated_at_timestamp": 1730274210,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public String[] wordBoggle(char board[][], String[] dictionary)\n {\n // Write your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"wordBoggle(self,board,dictionary)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n N = int(input())\n dictionary = [x for x in input().strip().split()]\n line = input().strip().split()\n R = int(line[0])\n C = int(line[1])\n board = []\n for _ in range(R):\n board.append([x for x in input().strip().split()])\n obj = Solution()\n found = obj.wordBoggle(board, dictionary)\n if len(found) == 0:\n print(-1)\n continue\n found.sort() # sorting output\n for i in found:\n print(i, end=' ')\n print()\n print(\"~\")\n",
"solution": "class Solution:\n def search(self, board, word, index, i, j):\n n = len(board)\n m = len(board[0])\n\n # If position of the cell is inside the board or not\n if i < 0 or i > n - 1 or j < 0 or j > m - 1:\n return False\n\n # If the current cell does not match the letter at index\n if word[index] != board[i][j]:\n return False\n\n # If each character is matched\n if index == len(word) - 1:\n return True\n\n ch = board[i][j]\n board[i][j] = '#'\n\n # Search for adjacent indices\n dx = [-1, 0, +1, -1, +1, -1, 0, +1]\n dy = [+1, +1, +1, 0, 0, -1, -1, -1]\n\n for x in range(len(dx)):\n if self.search(board, word, index + 1, i + dx[x], j + dy[x]):\n board[i][j] = ch\n return True\n\n board[i][j] = ch\n return False\n\n def exist(self, board, word):\n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.search(board, word, 0, i, j):\n return True\n\n return False\n\n def wordBoggle(self, board, dictionary):\n wordslist = []\n for i in range(len(dictionary)):\n if self.exist(board, dictionary[i]):\n wordslist.append(dictionary[i])\n\n return wordslist\n",
"updated_at_timestamp": 1730274210,
"user_code": "#User function Template for python3\n\nclass Solution:\n def wordBoggle(self,board,dictionary):\n # return list of words(str) found in the board"
}
|
eJy9VN1u0zAUrgQSPManXA+kwrjhzkncOMWJI9vZGjBCbCuwG7OLTkJCoD0EvC0XnJMGsUpEI6WiceTKP+f7Oefk5v73ew9n/W/148Fs9upzchmvrjfJcyTzEJ+GqKTWBqfG6hxSWK9CPMYxrUNCQ4d4CgPLf2gfAjZED94UyRGS9aer9flmffHm4/VmCPuI4iZfjrCL9CzEpvPK1FiKE4rSph0a1SBrdOtoG3wAHTi2CZGOEdYJvQ1ToXP0EocWjsi0SEPks4ZPj/DocUL8+ic2T0KshLflCt6K2jXGSTIDZEdFkD5EixIrVmohmI1jHoYmOUk1BRS6MLb0qnIorGgUIUo5CBbkcMH2hlj2yiuQFwWDkly1xZf00GoK1t6hHiHwO/iYaEqqowxnCrlsvEJqpchpXpTW+SHr7leOM2JDCeekMLGULeGtnJksyB0LN9UKLeqiFYXErUoYnNAUuiYvWjalICSqhW2hGVpf8ioXwwoZpyEnfDo9CZ8Ggc3B88jF0XKhoU1dSOepT/I+Ss/Z9JwpPeTRtk1yotjh5QjArSBjUFwxaZbLRaHK5QtdVUNdCqSsnXtwwSWiUE6STxXvKqGpo6X30sJLznkf+i3OcB7iBdZ4F+J7fMDlZGfvsna8PQaxZyNq1X5yp3xu/sP3hofez6O/6dpD9ulONiez/UffxaGN38+9aX14MK/DfKLbu/fvuPz62+OfORJVKw==
|
706,063
|
Valid Pair Sum
|
Given an array of size N, find the number of distinct pairs {i, j} (i != j)in the array such that the sum of a[i] and a[j] is greater than 0.
Examples:
Input:
N = 3, a[] = {3, -2, 1}
Output:
2
Explanation:
{3, -2}, {3, 1} are two
possible pairs.
Input:
N = 4, a[] = {-1, -1, -1, 0}
Output:
0
Explanation:
There are no possible pairs.
Constraints:
1 ≤ N ≤ 10**5
-10**4
≤ a[i] ≤ 10**4
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1618397389,
"func_sign": [
"static long ValidPair(int a[], 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 Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while(t > 0){\n \tint n = sc.nextInt();\n \tint array[] = new int[n];\n \tfor (int i=0; i<n ;i++ ) {\n \t\tarray[i] = sc.nextInt();\n \t}\n Solution ob = new Solution();\n System.out.println(ob.ValidPair(array,n));\n t--;\n \nSystem.out.println(\"~\");\n}\n } \n} \n",
"script_name": "GFG",
"solution": "class Solution {\n // Function to find the lower bound index of element x in array a\n static int lowerBound(int a[], int x) {\n int l = -1, r = a.length;\n // Binary search for the lower bound index\n while (l + 1 < r) {\n int m = (l + r) >>> 1;\n // Update the range based on the comparison\n if (a[m] >= x) r = m;\n else l = m;\n }\n return r;\n }\n\n // Function to find the count of valid pairs in array a\n static long ValidPair(int a[], int n) {\n // Sort the array\n Arrays.sort(a);\n long ans = 0;\n // Iterate through the array\n for (int i = 0; i < n; ++i) {\n if (a[i] <= 0) continue;\n // Find the lower bound index for (-a[i] + 1) and calculate the count of valid pairs\n int j = lowerBound(a, -a[i] + 1);\n ans += (i - j);\n }\n return ans;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution \n{ \n static long ValidPair(int a[], int n) \n\t{ \n\t // Your code goes here\n\t}\n} \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618397389,
"func_sign": [
"ValidPair(self, a, n)"
],
"initial_code": "# Initial Template for Python 3\n# Position this line where user code will be pasted.\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n n = int(input())\n array = list(map(int, input().strip().split()))\n\n obj = Solution()\n ans = obj.ValidPair(array, n)\n print(ans)\n\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nfrom bisect import bisect_left as lower_bound\n\n\nclass Solution:\n # Function to find the number of valid pairs.\n def ValidPair(self, a, n):\n # Sorting the array in ascending order.\n a = sorted(a)\n\n # Initializing the count of valid pairs.\n ans = 0\n\n # Iterating through the array.\n for i in range(n):\n # If the current element is less than or equal to 0,\n # then continue to the next iteration.\n if a[i] <= 0:\n continue\n\n # Finding the index of the first element in the sorted array\n # that is greater than or equal to (-a[i] + 1).\n j = lower_bound(a, -a[i] + 1)\n\n # Adding the count of valid pairs from the current element\n # to the element at index j.\n ans += i - j\n\n # Returning the count of valid pairs.\n return ans\n",
"updated_at_timestamp": 1731598350,
"user_code": "#User function Template for python3\n\nclass Solution:\n def ValidPair(self, a, n): \n \t# Your code goes here"
}
|
eJylk0EKwjAQRV14kE/WjjRNUxtPIhhxoV24qS5aEETxEHpMdx7AaRTRxVjbDiEEhv/4P5Och9f7cBBqduPD/KA2xa4q1RRK+4JX5As1gsr3u3xV5uvltipffe6cuHkc4VtkfUEWlIAMKAbpLgSNGAYJrCjWkrpukI5ADpSBJqAUPQ3VSCY6ZJgghWVjhg3KoMQKpPTlzSJiDJ+0nNAJjDgwuBD21mnMW99E0AIheRPIPjm2C4aNOC6eVL231JNrQZC0lFEHOYsp7TWFcG1/eo3/NhV+Xr+X/pGrjfJHfnnsDZduGl5N9tQLub03DdzFZfwAfH52kQ==
|
711,153
|
Number Of Islands
|
You are given a n,m which means the row and column of the 2D matrix and an array of size k denoting the number of operations. Matrix elements is 0 if there is water or 1 if there is land. Originally, the 2D matrix is all 0 which means there is no land in the matrix. The array has k operator(s) and each operator has two integer A[i][0], A[i][1] means that you can change the cellmatrix[A[i][0]][A[i][1]] from sea to island. Return how many island are there in the matrix after each operation.You need to return an array of size k.Note :An island means group of 1s such that they share a common side.
Examples:
Input:
n = 4
m = 5
k = 4
A = {{1,1},{0,1},{3,3},{3,4}}
Output:
1 1 2 2
Explanation:
0. 00000
00000
00000
00000
1. 00000
01000
00000
00000
2. 01000
01000
00000
00000
3. 01000
01000
00000
00010
4. 01000
01000
00000
00011
Input:
n = 4
m = 5
k = 4
A = {{0,0},{1,1},{2,2},{3,3}}
Output:
1 2 3 4
Explanation:
0. 00000
00000
00000
00000
1. 10000
00000
00000
00000
2. 10000
01000
00000
00000
3. 10000
01000
00100
00000
4. 10000
01000
00100
00010
1 <= n,m <= 100
1 <= k <= 1000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1656394331,
"func_sign": [
"public List<Integer> numOfIslands(int rows, int cols, int[][] operators)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\n//Position this line where user code will be pasted.\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 k= sc.nextInt();\n int[][] a = new int[k][2];\n for(int i=0;i<k;i++){\n \n a[i][0] = sc.nextInt();\n a[i][1] = sc.nextInt();\n }\n \n Solution obj = new Solution();\n List<Integer> ans = obj.numOfIslands(n,m,a);\n \n for(int i:ans){\n System.out.print(i+\" \");\n }\n System.out.println();\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\n\n// Solution class to compute the number of islands\n// based on given operators and dimensions of the grid\nclass Solution {\n static final int[][] DIRS = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; // Possible directions to check adjacent cells\n \n // Function to compute the number of islands\n public List<Integer> numOfIslands(int rows, int cols, int[][] operators) {\n if (isNullOrEmpty(operators)) return Collections.emptyList(); // If operators are empty, return empty list\n \n UF uf = new UF(rows * cols + 1); // Create an instance of the Union-Find data structure\n List<Integer> result = new ArrayList<>(operators.length); // List to store the results\n \n // Iterate over the given operators\n for (int[] op : operators) {\n int curr = op[0] * cols + op[1] + 1; // Compute the current cell index\n uf.addLand(curr); // Add the current cell to the land\n \n // Check adjacent cells and perform union operation if they are also lands\n for (int[] dir : DIRS) {\n int r = op[0] + dir[0]; // Compute the row index of adjacent cell\n int c = op[1] + dir[1]; // Compute the column index of adjacent cell\n int adj = r * cols + c + 1; // Compute the index of adjacent cell\n \n // Check if adjacent cell is safe and is a land\n if (isSafe(rows, cols, r, c) && uf.isLand(adj)) {\n uf.union(curr, adj); // Perform union operation\n }\n }\n \n result.add(uf.nmbOfIslands()); // Compute the number of islands and add it to the result list\n }\n return result; // Return the list of number of islands for each operator\n }\n \n // Function to check if a cell is safe\n private boolean isSafe(int rows, int cols, int r, int c) {\n return r >= 0 && r < rows && c >= 0 && c < cols; // Check if row and column indices are within the grid bounds\n }\n \n // Function to check if an array is null or empty\n private boolean isNullOrEmpty(int[][] arr) {\n return arr.length == 0; // Check if the length of the array is zero\n }\n}\n\n// Union Find class to perform union-find operations\nclass UF {\n private final int[] parent; // Array to store the parent of each element\n private final int[] rank; // Array to store the rank of each element\n private int count = 0; // Number of components\n \n // Constructor to initialize the Union-Find data structure\n UF(int n) {\n parent = new int[n]; // Create parent array with size n\n rank = new int[n]; // Create rank array with size n\n }\n \n // Function to add a cell to the land\n public void addLand(int p) {\n if (isLand(p)) return; // If the cell is already a land, return\n \n parent[p] = p; // Set the parent of the cell to itself\n rank[p] = 1; // Set the rank of the cell to 1\n count++; // Increment the count of components\n }\n \n // Function to check if a cell is a land\n public boolean isLand(int p) {\n return parent[p] > 0; // Check if the parent of the cell is greater than zero\n }\n \n // Function to find the parent of an element using path compression\n public int find(int p) {\n while (p != parent[p]) {\n parent[p] = parent[parent[p]]; // Path compression\n p = parent[p]; // Update the element to its parent\n }\n return p; // Return the parent of the element\n }\n \n // Function to perform union operation on two cells\n public void union(int p, int q) {\n int pr = find(p); // Find the parent of the first cell\n int qr = find(q); // Find the parent of the second cell\n if (pr == qr) return; // If both cells are already in the same component, return\n \n // Perform union by rank\n if (rank[pr] < rank[qr]) {\n parent[pr] = qr;\n } else {\n parent[qr] = pr;\n if (rank[pr] == rank[qr]) rank[pr]++;\n }\n count--; // Decrement the count of components\n }\n \n // Function to get the number of islands\n public int nmbOfIslands() {\n return count; // Return the count of components as the number of islands\n }\n}",
"updated_at_timestamp": 1730481301,
"user_code": "//User function Template for Java\n\nclass Solution {\n \n public List<Integer> numOfIslands(int rows, int cols, int[][] operators) {\n //Your code here\n }\n \n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1656441107,
"func_sign": [
"numOfIslands(self, rows: int, cols : int, operators : List[List[int]]) -> List[int]"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n T = int(input())\n for t in range(T):\n\n n = int(input())\n m = int(input())\n k = int(input())\n operators = []\n for i in range(k):\n u, v = map(int, input().strip().split())\n operators.append([u, v])\n obj = Solution()\n ans = obj.numOfIslands(n, m, operators)\n for i in ans:\n print(i, end=' ')\n print()\n\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nfrom heapq import *\nfrom typing import List\n\n\nclass Solution:\n # Function to count the number of islands\n def numOfIslands(self, rows: int, cols: int, operators: List[List[int]]) -> List[int]:\n # Initialize graph as adjacency list\n root = [i for i in range(rows * cols)]\n rank = [1] * (rows * cols)\n a = [[0] * cols for _ in range(rows)]\n\n # Function to find the root of a node\n def find(x):\n if root[x] == x:\n return x\n root[x] = find(root[x])\n return root[x]\n\n # Function to perform union of two nodes\n def union(x, y):\n x, y = find(x), find(y)\n if x == y:\n return False\n if rank[x] > rank[y]:\n root[y] = x\n elif rank[y] > rank[x]:\n root[x] = y\n else:\n root[y] = x\n rank[x] += 1\n return True\n\n res = [1]\n a[operators[0][0]][operators[0][1]] = 1\n\n for x, y in operators[1:]:\n if a[x][y]:\n res.append(res[-1])\n continue\n\n a[x][y] = cnt = 1\n for i, j in [(0, -1), (0, 1), (1, 0), (-1, 0)]:\n p, q = i + x, y + j\n if 0 <= p < rows and 0 <= q < cols and a[p][q]:\n cnt -= union(x * cols + y, p * cols + q)\n\n res.append(res[-1] + cnt)\n\n return res\n",
"updated_at_timestamp": 1730481301,
"user_code": "#User function Template for python3\n\nfrom typing import List\nclass Solution:\n def numOfIslands(self, rows: int, cols : int, operators : List[List[int]]) -> List[int]:\n # code here"
}
|
eJzVVktuGzEM7aKb3uJh1kFA6jOfnCRApuii8aKbiRc2UKBIkEO0N8kul+ujpBk3aRTbTYAmlkaixuIj+UjJvv346/7Th/Q5v6Nw8aP5Nq23m+YMjY6TiizDOAk4DAOGYZyiIKZXtuA7yi7CxXHqIrqYNqTvY9aJ0pygWX1fr75uVpdfrrab2QocPAIiWnToMUAF43QzTs31CR66Y1j2uNkZgTlpkprk4Gzw4+RN8iYFBBvMI5OiSbSgkifT17zSvHJQlydqq88rTr4aQG6uNF9aKC2WVonpD4pjiaq45wQWqBd4TkEQZOG9FbScOkHHqRf0RjOzIXOIEYZXcuIjPKdACuIxeTBOjAhoIFwthFwCZmwOYEnGLgXJqxYtnUZHl9FTCcMuGQ/p95l+mg1LMNpCqa8dlAjaQ4mhdHRYyHIMw2zTuJUCy4AoLsCFF4RtdmmT9gaYHeoQn9jErZIy16qXhZRdwSZ60tIVojRL+iYo21Ppudrz+E/c1Y7C3MlX1YX9x6gckmMRXOrhqZtlDx8VQJ96XABdSXrJdx11ZrWCG1Jvn7kCWUJ7Lyv/JHy6xiu6f2+tcfx452Hb3vWh+S9nRuTQDND/lyZB30EWDri6jP7XT8PheeAv5REnxwjL/6CqCp9/nv4GSEeRQg==
|
705,631
|
Queries on a Matrix
|
You are given a matrix of dimension n*n. All the cells are initially, zero.You are given Q queries, which contains 4 integersa b c d where (a,b) is theTOP LEFT cell and (c,d) is the Bottom Right cell of a submatrix. Now, all the cells of this submatrix haveto be incremented by one. After all the Q queries have been performed. Your task is to findthe final resulting Matrix.Note : Zero-Based Indexing is used for cells of the matrix.
Examples:
Input:
n = 6, q = 6,
Queries = {
{4,0,5,3},
{0,0,3,4},
{1,2,1,2},
{1,1,2,3},
{0,0,3,1},
{1,0,2,4}}.
Output:
2 2 1 1 1 0
3 4 4 3 2 0
3 4 3 3 2 0
2 2 1 1 1 0
1 1 1 1 0 0
1 1 1 1 0 0
Explanation:
After incrementing all the
sub-matrices of given queries we will
get the final output.
Input:
n = 4, q = 2,
Queries = {
{0,0,3,3},
{0,0,2,2}}.
Output:
2 2 2 1
2 2 2 1
2 2 2 1
1 1 1 1
Explanation:
After incrementing all the
sub-matrices of given queries we will
get the final output.
Constraints:
1 <= n <= 1000
0 <= a <= c <n
0 <= b <= d <n
1 <= No. of Queries <= 1000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int[][] solveQueries(int n, int[][] Queries)"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out=new PrintWriter(System.out);\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n String[] s = br.readLine().trim().split(\" \");\n int n = Integer.parseInt(s[0]);\n int q = Integer.parseInt(s[1]);\n int[][] Queries = new int[q][4];\n for (int i = 0; i < q; i++) {\n String[] s1 = br.readLine().trim().split(\" \");\n for (int j = 0; j < 4; j++)\n Queries[i][j] = Integer.parseInt(s1[j]);\n }\n Solution obj = new Solution();\n int[][] ans = obj.solveQueries(n, Queries);\n for (int i = 0; i < ans.length; i++) {\n for (int j = 0; j < ans[i].length; j++) {\n out.print(ans[i][j] + \" \");\n }\n out.println();\n }\n \nout.println(\"~\");\n}\n out.close();\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public int[][] solveQueries(int n, int[][] Queries) {\n \n // Create a 2D array of size n x n to store the result\n int a[][]=new int[n][n];\n \n // Loop through each query\n for(int i=0;i<Queries.length;i++){\n \n // Get the coordinates of the top-left and bottom-right points of the query rectangle\n int x1=Queries[i][0];\n int y1=Queries[i][1];\n int x2=Queries[i][2];\n int y2=Queries[i][3];\n \n // Increase the count of the top-left point by 1\n a[x1][y1]++;\n \n // Decrease the count of the point just below the bottom-right point by 1\n if(x2<n-1){\n a[x2+1][y1]--;\n }\n \n // Decrease the count of the point just to the right of the bottom-right point by 1\n if(y2<n-1){\n a[x1][y2+1]--;\n }\n \n // Increase the count of the point just below and to the right of the bottom-right point by 1\n if(x2<n-1 && y2<n-1){\n a[x2+1][y2+1]++;\n }\n }\n \n // Calculate the prefix sum of each row\n for(int i=0;i<n;i++){\n for(int j=1;j<n;j++){\n a[i][j]+=a[i][j-1];\n }\n }\n \n // Calculate the prefix sum of each column\n for(int i=0;i<n;i++){\n for(int j=1;j<n;j++){\n a[j][i]+=a[j-1][i];\n }\n }\n \n // Return the resulting 2D array\n return a;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int[][] solveQueries(int n, int[][] Queries) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"solveQueries(self, n, Queries)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n, q = input().split()\n n = int(n)\n q = int(q)\n Queries = []\n for _ in range(q):\n cur = list(map(int, input().split()))\n Queries.append(cur)\n obj = Solution()\n ans = obj.solveQueries(n, Queries)\n for _ in ans:\n for __ in _:\n print(__, end=\" \")\n print()\n",
"solution": "class Solution:\n def solveQueries(self, n, Queries):\n # Create matrix and arrays for row and column updates\n matrix = [[0] * (n + 2) for _ in range(n + 2)]\n row = [[0] * (n + 2) for _ in range(n + 2)]\n col = [[0] * (n + 2) for _ in range(n + 2)]\n\n # Iterate through the Queries\n for i in Queries:\n a = i[0]\n b = i[1]\n c = i[2]\n d = i[3]\n\n # Update row and column arrays based on Query values\n row[a][b] += 1\n row[c + 1][b] -= 1\n col[a][d + 1] -= 1\n col[c + 1][d + 1] += 1\n\n # Perform cumulative sum on row and column arrays\n for i in range(1, n):\n for j in range(n + 2):\n row[i][j] += row[i - 1][j]\n col[i][j] += col[i - 1][j]\n\n # Calculate matrix values based on cumulative sums of rows and columns\n for i in range(n):\n matrix[i][0] = row[i][0] + col[i][0]\n for i in range(1, n):\n for j in range(n):\n matrix[j][i] = matrix[j][i - 1] + row[j][i] + col[j][i]\n\n # Create a result matrix with the calculated matrix values\n res = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n res[i][j] = matrix[i][j]\n\n return res\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef solveQueries(self, n, Queries):\n\t\t# Code here"
}
|
eJzs2M1undeZpuEe9IFsaOwBKVGylXEdRAMtIINEg0wUD2wgQBCgTrDOqblJ/dmRV7ILq/qF73XhsmLV5o/Ij++j26j//N//5/1//cf/+r9/f/GXDz/+/NOLP1xe3L/7cH95/J+7y5MX311evP/bj+//9NP7P//xrz//9Om9Lu8+vPjHd5dffeDd3d2nj3379u31129+PADwe/f0Hw0AwO+cogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIGiA0CBogNAgaIDQIG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KFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoUHQAKFB0AChQdAAoOJ42vz+MX5vvp/vHh82nsbk8nrZjdzxdjMXlenQ5Lp7aP5bRcrz5MDZ3P+/vvj7cffvy4/HhfInt2C7/FLavrz5f5Y1Xvd7H5fQ2F+v778d+3td2XI/rdXI7bo+nabwezNu5GTfH09W4GodxmM+Zl/bTFqa75cnxNC2sp+/Gbj74z/5XV8++p/nZandefZruFvtl7fl03t1henw5PUyfYn+ezzt+mt1Ot8Oysn5768r1q+k8Pyz+Tdfd7s92z/6pbc/72y3Tl7/Hxft+jfeeNn3IN8/8/OfjX5wetSA=
|
703,441
|
Roll the characters of a String
|
Given a string s containing lowercase alphabets and an array roll where roll[i] represents rolling the first roll[i] characters in the string, the task is to apply every roll[i] on the string and return the final string. Rolling means increasing the ASCII value of the character; for example, rolling z would result in a, rolling b would result in c, etc.
Examples:
Input:
s = "bca", roll[] = [1, 2, 3]
Output:
eeb
Explanation:
arr[0] = 1 means roll first character of string -> cca
arr[1] = 2 means roll first two characters of string -> dda
arr[2] = 3 means roll first three characters of string -> eeb
So final ans is "eeb".
Input:
s = "zcza", roll[] = [1, 1, 3, 4]
Output:
debb
Constraints:
1 ≤ s.size() ≤ 10**6
1 ≤ roll.size() ≤ 10**6
1 ≤ roll[i] ≤ s.size()**
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public String findRollOut(String s, List<Integer> roll)"
],
"initial_code": "import java.util.*;\n\nclass Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int t = scanner.nextInt();\n scanner.nextLine();\n Solution ob = new Solution();\n while (t-- > 0) {\n String s = scanner.nextLine();\n String line = scanner.nextLine();\n String[] parts = line.split(\" \");\n List<Integer> roll = new ArrayList<>();\n for (String part : parts) {\n roll.add(Integer.parseInt(part));\n }\n String result = ob.findRollOut(s, roll);\n System.out.println(result);\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n public String findRollOut(String s, List<Integer> roll) {\n // Maximum number of characters in the alphabet\n int rollSize = roll.size();\n int strSize = s.length();\n int alphabetCount = 26;\n // Array to store preliminary roll-out values\n long[] rollOutPrefix = new long[strSize + 1];\n // Calculating preliminary roll-out values\n for (int i = 0; i < rollSize; i++) {\n rollOutPrefix[0]++;\n if (roll.get(i) < strSize) {\n rollOutPrefix[roll.get(i)]--;\n }\n }\n // Calculating cumulative roll-out values\n for (int i = 1; i < strSize; i++) {\n rollOutPrefix[i] += rollOutPrefix[i - 1];\n }\n // Convert the string to a character array for modification\n char[] chars = s.toCharArray();\n // Rolling out characters to get the new string\n for (int i = 0; i < strSize; i++) {\n // Find the roll-out value for the character\n int rollValue = (int) (rollOutPrefix[i] % alphabetCount);\n // Convert character to numeric value\n int currentCharPos = chars[i] - 'a';\n // Get the new character after roll-out\n chars[i] = (char) ('a' + (currentCharPos + rollValue) % alphabetCount);\n }\n // Return the new string\n return new String(chars);\n }\n}\n",
"updated_at_timestamp": 1727947200,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Function to find the new string obtained by rolling out characters.\n public String findRollOut(String s, List<Integer> roll) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"findRollOut(self, s: str, roll: list[int]) -> str"
],
"initial_code": "from typing import List\n\n\ndef main():\n t = int(input())\n for _ in range(t):\n s = str(input())\n roll = list(map(int, input().split()))\n solution = Solution()\n result = solution.findRollOut(s, roll)\n print(result)\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "from typing import List\n\n\nclass Solution:\n # Function to find the new string obtained by rolling out characters.\n def findRollOut(self, s: str, roll: List[int]) -> str:\n rollSize = len(roll)\n strSize = len(s)\n alphabetCount = 26\n\n # Maximum number of characters in the alphabet\n rollOutPrefix = [0] * (strSize + 1)\n\n # Array to store preliminary roll-out values\n for i in range(rollSize):\n rollOutPrefix[0] += 1\n if roll[i] < strSize:\n rollOutPrefix[roll[i]] -= 1\n\n # Calculating preliminary roll-out values\n for i in range(1, strSize):\n rollOutPrefix[i] += rollOutPrefix[i - 1]\n\n # Calculating cumulative roll-out values\n result = []\n for i in range(strSize):\n # Find the roll-out value for the character\n rollValue = rollOutPrefix[i] % alphabetCount\n\n # Convert character to numeric value\n currentCharPos = ord(s[i]) - ord('a')\n\n # Get the new character after roll-out\n result.append(\n chr(ord('a') + (currentCharPos + rollValue) % alphabetCount))\n\n # Return the new string\n return ''.join(result)\n",
"updated_at_timestamp": 1727947200,
"user_code": "from typing import List\n\nclass Solution:\n # Function to find the new string obtained by rolling out characters.\n def findRollOut(self, s: str, roll: list[int]) -> str:\n # Your code goes here"
}
|
eJytVtuOmzAQ3Ye+7F+MeF5VsYFc9ksq1VUVwOEaQxJISKpq9yPa/+0YkwAJZsk2Yx6I8Jk5M3PsyfuXv2/PT5V9K/Hl+y8jFFmRG69gmEycyuPScT2+YsIGE+ZAgcAMpmAxoT74ARNz6CyEnY0JghATLLARNMOvCyaMFzB4mXE3597PtMjrcAHnq8qYCKM4WYs0w7fAX3HPdZYI+/0CLXYUwxzLw77Id9tNlop1Eket3XQK1AZqATWBUqDIYwJkAWQOZAZkCsQGYgExgWBOBMgEFkhP5mYjXVNmyoQksdnu8mJ/KI9NTh/iNCmeyn2+zUQSBSvP6fzAcnbsHOoqadKUPYyQyAT0j5aFqq1Mq6+o7ZSZmMJlMRE0fbGhXtooysPZT+VVQa9CmjIltaSSrgrp1saEBZ0lC+Y4rut5Uja+H6AOx3ZVwzgMfZ9zGStGU1E3WZamQqzXSRLHURT2dgQja506fYjTEOJW6p2uN91TolRSf9ijpzXAoIfvRcRjtFIde63i1VmoPI5xxqWdtw9UkpL/P0EZj+7vlk4pOkx/Gu0C6zxKG3mRfEhK70I8Wpaf0GUfh4H2aykPliHtAfWWtnVraRx6aGrHLVo3dDSuuloZMzju7hWRg+CuW4Th+dR17FreFa9aiA8a8vDgKX/PGFnWcz30ubs8Hordphnylz9Gp+6Q//Hn6z9mogXK
|
705,133
|
Arithmetic Number
|
Given three integers 'A' denoting the first term of an arithmetic sequence , 'C' denoting the common differenceof an arithmetic sequence and an integer 'B'. you need to tell whether 'B' exists in the arithmetic sequence or not. Return 1 if B is present in the sequence. Otherwise, returns 0.
Examples:
Input:
A = 1, B = 3, C = 2
Output:
1
Explanation:
3 is the second term of the
sequence starting with 1 and having a common
difference 2.
Input:
A = 1, B = 2, C = 3
Output:
0
Explanation:
2 is not present in the sequence.
Constraints:
-10**9
≤ A, B, C ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1731402182,
"func_sign": [
"static int inSequence(int a, int b, int c)"
],
"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 in = new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out = new PrintWriter(System.out);\n int t = Integer.parseInt(in.readLine());\n while (t-- > 0) {\n String arr[] = in.readLine().trim().split(\"\\\\s+\");\n int a = Integer.parseInt(arr[0]);\n int b = Integer.parseInt(arr[1]);\n int c = Integer.parseInt(arr[2]);\n\n Solution ob = new Solution();\n int ans = (ob.inSequence(a, b, c));\n if (ans == 1)\n System.out.println(\"true\");\n else\n System.out.println(\"false\");\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static int inSequence(int a, int b, int c) {\n // calculate the difference between b and a\n int d = (b - a);\n // if the difference is 0, it means the sequence is in order\n if (d == 0) return 1;\n // if the difference is negative, check if c is also negative\n // if c is not negative and the difference is divisible by c, it means the\n // sequence is in order otherwise, the sequence is not in order\n if (d < 0) {\n if (c >= 0) return 0;\n if (d % c == 0) return 1;\n return 0;\n }\n // if the difference is positive, check if c is also positive\n // if c is not positive and the difference is divisible by c, it means the\n // sequence is in order otherwise, the sequence is not in order\n else {\n if (c <= 0) return 0;\n if (d % c == 0) return 1;\n return 0;\n }\n }\n}",
"updated_at_timestamp": 1731490773,
"user_code": "// User function Template for Java\n\nclass Solution {\n static int inSequence(int a, int b, int c) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731402182,
"func_sign": [
"inSequence(self, a, b, c)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n A, B, C = [int(x) for x in input().split()]\n\n ob = Solution()\n ans = ob.inSequence(A, B, C)\n if ans:\n print(\"true\")\n else:\n print(\"false\")\n print(\"~\")\n",
"solution": "class Solution():\n def inSequence(self, A, B, C):\n # Calculate the difference between B and A\n d = (B - A)\n\n # If the difference is zero, the sequence is valid\n if d == 0:\n return 1\n\n # If the difference is negative\n if d < 0:\n # If C is positive, the sequence is not valid\n if C >= 0:\n return 0\n # If C is divisible by the difference, the sequence is valid\n if d % C == 0:\n return 1\n return 0\n\n # If the difference is positive\n else:\n # If C is negative, the sequence is not valid\n if C <= 0:\n return 0\n # If C is divisible by the difference, the sequence is valid\n if d % C == 0:\n return 1\n return 0\n\n return 0\n",
"updated_at_timestamp": 1731490773,
"user_code": "#User function Template for python3\n\nclass Solution:\n def inSequence(self, a, b, c):\n # code here"
}
|
eJxrYJm6m4UBDCK2ABnR1UqZeQWlJUpWCkqGMXkGCkCopKOglFpRkJpckpoSn19aApUuKSpNjcmri8lTqtVRQNdmiFtfWmJOMS6NhgYwoKCLzDaCs0l3DA4zDQkZic+d2A1SoJIzkZmkG6SLKxDJMcsSBhQQLEM4k4yQQxiDZLYuRUYaIgcYIYNweVaXYHpA10DIJgwLgPmCNBsIhgqGBuLUEe8AWFYm2gUEcwC6U4gObJwKY6foAQD3JWGl
|
704,427
|
Sum of Digits Divisibility
|
Given a number N. Check whether it is divisible by the sum of its digits or not.
Examples:
Input:
N=18
Output:
1
Explanation:
The sum of digits of 18 is 1+8=9
which divides 18.so, answer is 1.
Input:
N=25
Output:
0
Explanation:
The sum of digits of 25 is 2+5=7 which does
not divide 25, so answer is 0.
Constraints:
1<=N<=10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int isDivisible(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 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 Solution ob = new Solution();\n System.out.println(ob.isDivisible(N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // Function to check if a number is divisible by the sum of its digits\n int isDivisible(int N) {\n int sum = 0, N1 = N; // As N will get destroyed,so storing it in N1\n // Calculating the sum of digits of the number\n while (N > 0) {\n sum += N % 10;\n N /= 10;\n }\n // Checking if the number is divisible by the sum of its digits\n return (N1 % sum == 0 ? 1 : 0);\n }\n}\n;\n",
"updated_at_timestamp": 1730474919,
"user_code": "// User function Template for Java\n\nclass Solution {\n int isDivisible(int N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isDivisible(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())\n ob = Solution()\n print(ob.isDivisible(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def isDivisible(self, N):\n # As N will get destroyed,so storing it in N1\n N1 = N\n sum = 0\n while N > 0:\n sum += N % 10\n N //= 10\n return 1 if N1 % sum == 0 else 0\n",
"updated_at_timestamp": 1730474919,
"user_code": "#User function Template for python3\n\nclass Solution:\n def isDivisible(self,N):\n #code here"
}
|
eJxrYJn6j4UBDCK+AxnR1UqZeQWlJUpWCkqGMXlApKSjoJRaUZCaXJKaEp9fWoKQrANK1uoooOkwIFmLJQyQYRkMkK4VBkh3roW5mamJsRFunQa47DQyNjE1M7fA7VGcOmH+JN1SCpxqAPQqufZRZIYhzK9Qw8jyOARhcQ5qkiM95aBEJOHUgC/xkpFsUWzHl37xRS0Wk/B4DGwLmQmXcD4jlObJLRUQkU/Q6tgpegBBTYbi
|
703,966
|
Divisor Product
|
Given a number N, find the product of all the divisors of N (including N).
Examples:
Input:
N =
6
Output:
36
Explanation:
Divisors of 6 : 1, 2, 3, 6
Product = 1*2*3*6 = 36
Input:
N =
5
Output:
5
Explanation:
Divisors of 5 : 1, 5
Product = 1*5 = 5
Constraints:
1 <= N <= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static Long divisorProduct(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.divisorProduct(N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static Long divisorProduct(Long N) {\n Long ans = 1L; // Initilaizing the answer as 1.\n for (int i = 1; i <= Math.sqrt(N); i++) {\n // We multiply with the divisors\n if (N % i == 0) {\n // If the divisor is sqrt of N, then we multiply with the divisor once\n if (N / i == i) {\n ans *= i;\n ans %= 1000000007; // Taking the mod value of ans.\n } else {\n ans *= i;\n ans %= 1000000007;\n ans *= (N / i);\n ans %= 1000000007;\n }\n }\n }\n return ans;\n }\n}\n;\n",
"updated_at_timestamp": 1730473917,
"user_code": "//User function Template for Java\n\nclass Solution {\n static Long divisorProduct(Long N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"divisorProduct(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.divisorProduct(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nimport math\n\n\nclass Solution:\n def divisorProduct(self, N):\n ans = 1\n\n # iterating over numbers from 1 to sqrt(N)\n for i in range(1, int(math.sqrt(N)) + 1):\n # checking if i is a divisor of N\n if N % i == 0:\n # if i is a divisor and is equal to N//i, i*i=N, then add only i to the answer\n if N // i == i:\n ans *= i\n ans %= 1000000007\n # if i is a proper divisor of N, add both i and N//i to the answer\n else:\n ans *= i\n ans %= 1000000007\n ans *= (N // i)\n ans %= 1000000007\n\n return ans\n",
"updated_at_timestamp": 1730473917,
"user_code": "#User function Template for python3\n\nclass Solution:\n def divisorProduct(self, N):\n # code here "
}
|
eJy9lE1OwzAQhVnAPSKvKxT/js1JKhHEArJgE7pIpUpVqx6CXpIdN2DiGJJUeQ4SAiuRInvmy8y8GZ+uzx83V3Gt3/njfi9ems22FXeFkFXDj1gVot5t6qe2fn583bbD4ZEPD6viwqP8WtDV60BlcJIAIvRLEySMLPJBQIKyHIAjFTIxeJ0NoDue9/XKWOlsxn2wyMYPAextNUnpAEBJQ8ZrZ3ANk4XGWZCzRivcAk4GLiBrCQg2ZYHrMLJY0nFZkyVJp7C40TMvuvYXv0i6akwwirz3ymXHZ9IB8ZWYKLtBQDjug+lANVRVU2lgrtH1p7L8U3172mh8OthfRpSs0YQk0FwEZezVYQteBTTLX75GwaWFE7H8fmv68Hb7Ccb5vf8=
|
700,411
|
Find perimeter of shapes
|
Given a matrix mat[][] of nrows and mcolumns, consisting of 0’s and 1’s. The task is to complete the function findPerimeter which returns an integer denoting theperimeter of sub-figures consisting of only 1’s in the matrix.For examplePerimeter of single 1 is 4 as it can be covered from all 4 side. Perimeter of double 11 is 6.
Examples:
| 1 | | 1 1 |
Input Format:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. The first line of each test case contains two space separated n and m denoting the size of the matrix mat[][] . Then in the next lineare n*mspace separated values of the matrix.
Output Format:
For each test case in a new line print the perimeter of sub-figure consisting only 1’s in the matrix.
Constraints:
1<=T<=100
1<=n, m<=20
Example(To be used for expected output):
Input:
2
1 2
1 1
3 3
1 0 0 1 0 0 1 0 0
Output:
6
8
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": 1615292571,
"func_sign": [
"public static int findPerimeter(int[][] mat, int n, int m)"
],
"initial_code": "import java.util.*;\nclass Perimeter{\n\tpublic static void main(String[] args){\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();\n\t\twhile(t-- > 0){\n\t\t\tint n = sc.nextInt();\n\t\t\tint m = sc.nextInt();\n\t\t\tint[][] a = new int[n][m];\n\t\t\tfor(int i = 0 ; i < n; i++ )\n\t\t\t\tfor(int j = 0 ; j < m; j++)\n\t\t\t\t\ta[i][j] = sc.nextInt();\n\t\t\tGfG g = new GfG();\n\t\t\tSystem.out.println(g.findPerimeter(a,n,m));\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "Perimeter",
"solution": "/*Complete the function given below*/\nclass GfG {\n public static int findPerimeter(int[][] mat, int n, int m) {\n int perimeter = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (mat[i][j] == 1) {\n perimeter += 4;\n if (i > 0 && mat[i-1][j] == 1) perimeter--; // up\n if (i < n-1 && mat[i+1][j] == 1) perimeter--; // down\n if (j > 0 && mat[i][j-1] == 1) perimeter--; // left\n if (j < m-1 && mat[i][j+1] == 1) perimeter--; // right\n }\n }\n }\n return perimeter;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "/*Complete the function given below*/\nclass GfG\n{\n public static int findPerimeter(int[][] mat, int n, int m)\n {//add code here.\n }\n}"
}
|
{
"class_name": null,
"created_at_timestamp": 1615292571,
"func_sign": [
"findPerimeter(arr, n, m)"
],
"initial_code": "# Driver Program\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n = list(map(int, input().strip().split()))\n arr = list(map(int, input().strip().split()))\n matrix = [[0 for i in range(n[1])] for j in range(n[0])]\n k = 0\n for i in range(n[0]):\n for j in range(n[1]):\n matrix[i][j] = arr[k]\n k += 1\n print(findPerimeter(matrix, n[0], n[1]))\n print(\"~\")\n# Contributed by: Harshit Sidhwa\n",
"solution": "def cntneighbour(arr, i, j, n, m):\n cnt = 0\n # Checking if there is a neighbor above\n if i > 0 and arr[i-1][j] == 1:\n cnt += 1\n # Checking if there is a neighbor to the left\n if j > 0 and arr[i][j-1] == 1:\n cnt += 1\n # Checking if there is a neighbor below\n if i < n-1 and arr[i+1][j] == 1:\n cnt += 1\n # Checking if there is a neighbor to the right\n if j < m-1 and arr[i][j+1] == 1:\n cnt += 1\n return cnt\n\n\ndef findPerimeter(arr, n, m):\n # Initializing perimeter variable\n per = 0\n for i in range(n):\n for j in range(m):\n # Checking if current cell is occupied\n if arr[i][j] == 1:\n # Calculating the number of neighbors and subtracting it from 4 (since 4 is the maximum number of neighbors)\n per += (4 - cntneighbour(arr, i, j, n, m))\n return per\n",
"updated_at_timestamp": 1729753320,
"user_code": "# Your task is to complete this function\n# Function should return an integer\ndef findPerimeter(arr, n, m):\n # code here\n"
}
|
eJy1VMtKxTAQLSL6G0PWF5lJ+sIvEYy40C7cxLvoBUHuxY/Qr3VjpyltEjNiFrdDA3mcM2ceycfl18V1NX9331dVdf+uXtz+MKpbUGQdAQ9qB2p42w9P4/D8+HoYl/3aupN16riDGKRBz0g2AdoLUANmhW4mkJAWWGqomQWBfz8SJHOB00icDTTWIRSa4AUFJwQaM/HnTaqKFIFGoPOQmyjl+XEyLm/jFeCyTmuqlhkn2mxMtHIEv6BN+34k31s622KT/BZaLmSsgiI1sedYIwY45Lg7rzZus20FBXa5OUw7KzdSk/TQb2XEwBEmoinYCeXEQYahpad+J+Rv6V32SeDCEyd90i4ARcT0zVeiEGmpzFvzv5PrLZqycIZ7FIXtA+cwTGHWHK1JS5iKqRJ86RNVrDyVrnnazY5L9ed6yFoj4h8+b34AtBDVAw==
|
703,088
|
Bitonic Generator Sort
|
Given an array arrthe task is to sort all even-placed numbers in increasing and odd-place numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers.Note: that the first element is considered as even because of its index 0.
Examples:
Input:
arr[] = [0, 1, 2, 3, 4, 5, 6, 7]
Output:
[0, 2, 4, 6, 7, 5, 3, 1]
Explanation:
Even-place elements : 0, 2, 4, 6 Odd-place elements : 1, 3, 5, 7 Even-place elements in increasing order : 0, 2, 4, 6 Odd-Place elements in decreasing order : 7, 5, 3, 1
Input:
arr[] = [3, 1, 2, 4, 5, 9, 13, 14, 12]
Output:
[2, 3, 5, 12, 13, 14, 9, 4, 1]
Explanation:
Even-place elements : 3, 2, 5, 13, 12 Odd-place elements : 1, 4, 9, 14 Even-place elements in increasing order : 2, 3, 5, 12, 13 Odd-Place elements in decreasing order : 14, 9, 4, 1
Constraints:
1 ≤ arr.size() ≤ 10**5
1 ≤ arr[i] ≤ 10**5**
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static ArrayList<Integer> bitonicGenerator(int arr[])"
],
"initial_code": "// Initial Template for Java\n\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());\n\n while (t-- > 0) {\n\n ArrayList<Integer> array1 = new ArrayList<Integer>();\n String line = read.readLine();\n String[] tokens = line.split(\" \");\n for (String token : tokens) {\n array1.add(Integer.parseInt(token));\n }\n ArrayList<Integer> v = new ArrayList<Integer>();\n int[] arr = new int[array1.size()];\n int idx = 0;\n for (int i : array1) arr[idx++] = i;\n\n v = new Solution().bitonicGenerator(arr);\n\n for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + \" \");\n\n System.out.println();\n\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // Function to generate bitonic sequence\n public static ArrayList<Integer> bitonicGenerator(int[] arr) {\n int n = arr.length; // Size of the input array\n // Create ArrayLists for even-indexed and odd-indexed elements\n ArrayList<Integer> evenList = new ArrayList<>();\n ArrayList<Integer> oddList = new ArrayList<>();\n // Fill the evenList and oddList from the original array\n for (int i = 0; i < n; i++) {\n if (i % 2 == 0) {\n evenList.add(arr[i]); // Even index\n } else {\n oddList.add(arr[i]); // Odd index\n }\n }\n // Sort evenList in ascending order\n Collections.sort(evenList);\n // Sort oddList in ascending order and then reverse it to make it descending\n Collections.sort(oddList);\n Collections.reverse(oddList);\n // Create the final ArrayList to hold the result\n ArrayList<Integer> ans = new ArrayList<>();\n // Add sorted evenList elements to ans\n ans.addAll(evenList);\n // Add sorted oddList elements to ans\n ans.addAll(oddList);\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> bitonicGenerator(int arr[]) {\n // Your code goes here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"bitonicGenerator(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n\n while t > 0:\n arr = list(map(int, input().split()))\n ob = Solution()\n ans = ob.bitonicGenerator(arr)\n print(*ans)\n print(\"~\")\n t -= 1\n",
"solution": "class Solution:\n\n def bitonicGenerator(self, arr):\n n = len(arr)\n evenArr = []\n oddArr = []\n\n # Distribute elements between evenArr and oddArr based on their index\n for i in range(n):\n if i % 2 == 0:\n evenArr.append(arr[i])\n else:\n oddArr.append(arr[i])\n\n # Sort evenArr in ascending order\n evenArr.sort()\n\n # Sort oddArr in descending order\n oddArr.sort(reverse=True)\n\n # Initialize the result list\n ans = evenArr + oddArr\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def bitonicGenerator(self, arr):\n # Your code goes here\n"
}
|
eJydVElOw0AQ5AD/aM05Qt1eBpuXIGUQB/CBy5CDLSGxKI8I/023JyaBuOI4M96k6areqr2+/vm8uerXQ6cfyw/3Gldd6+7JSYhZiMK2SNyCXPO+ap7b5uXprWt3RmrxHaL7WtBfZK5IyigHsBzACnNIwv2dHgwoCkBR6kUF5eodBV0CqLegfzcAewCue7AFffwEVDWgEg6R6WgDFrMep5FdE7QcJXm6o4pqsvqigAwxTmVK0IJaPspRKZenqTILEkfSlJ6ghNLxOLaHC+ubJ0SGktGy+/kt0TVMxNAiqM3B+lyNz5R46sbcqpuvKY9DTIIbkO2L8S8TTo2b+afYz83ByFQXT85Bm04FySHwSf2dMQkjaowXTMfj5nYLxrmSyA==
|
702,693
|
Perfect Array
|
Given an array arr[] of non-negative integers, determine whether the array is perfect. An array is considered perfect if it first strictly increases, then remains constant, and finally strictly decreases. Any of these three parts can be empty.
Examples:
Input:
arr[] = [1, 8, 8, 8, 3, 2]
Output:
true
Explanation:
The array [1, 8, 8, 8, 3, 2] first increases in the range [0, 1], stays constant in the range [1, 3], and then decreases in the range [3, 4]. Thus, the array is perfect.
Input:
arr[] = [1, 1, 2, 2, 1]
Output:
false
Explanation:
The array does not follow the required pattern of strictly increasing, constant, and then strictly decreasing.
Constraints
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 10**8
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617648096,
"func_sign": [
"public boolean isPerfect(int[] arr)"
],
"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 for (int i = 0; i < t; i++) {\n String input = scanner.nextLine();\n String[] inputArray = input.split(\" \");\n int[] arr = new int[inputArray.length];\n for (int j = 0; j < inputArray.length; j++) {\n arr[j] = Integer.parseInt(inputArray[j]);\n }\n\n Solution solution = new Solution();\n System.out.println(solution.isPerfect(arr));\n System.out.println(\"~\");\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n public boolean isPerfect(int[] arr) {\n int n = arr.length;\n if (n < 3) return false;\n int i = 1;\n // Check for strictly increasing part\n while (i < n && arr[i] > arr[i - 1]) i++;\n // Check for constant part\n while (i < n && arr[i] == arr[i - 1]) i++;\n // Check for strictly decreasing part\n while (i < n && arr[i] < arr[i - 1]) i++;\n // If we reached the end, the array is perfect\n return i == n;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n public boolean isPerfect(int[] arr) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617648096,
"func_sign": [
"isPerfect(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(\"true\" if solution.isPerfect(arr) else \"false\")\n print(\"~\")\n",
"solution": "class Solution:\n\n def isPerfect(self, arr):\n n = len(arr)\n if n < 3:\n return False\n\n i = 1\n # Check for strictly increasing part\n while i < n and arr[i] > arr[i - 1]:\n i += 1\n\n # Check for constant part\n while i < n and arr[i] == arr[i - 1]:\n i += 1\n\n # Check for strictly decreasing part\n while i < n and arr[i] < arr[i - 1]:\n i += 1\n\n # If we reached the end, the array is perfect\n return i == n\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def isPerfect(self, arr):\n # code here\n"
}
|
eJytVMEKwjAM9aD/EXoe0q6tW7168wsEJyI6QZA6dANBFD9C/9d062A7qCya5BDY8vJe2vTef04HvdJmE0zmF7azWZGzMTCRWAEhSFClS8wFC4Cl5yxd5+lmeShy/2t+LNLE3hLLrgG0Iapi1b2w6u38XfF2tT+9reZgIIaoe18NulYLnEJbcG+NzHij4EkkFKEa5xHmknIM1TlqGCFEjECCt6KcFX700v8tm8IYWYUcJAfFQdehHHMaluoE9vFutRT+NitjKHqIG+HugZtDOYSYIl0brSm9Map9Fv41oYAQapxcSiscVnPtvuxdE2rxGL4AzbOQSQ==
|
703,213
|
Find element at a given Index
|
Given an array arr of integers and an index key(0-based index). Your task is to return the element present at the index key in the array.
Examples:
Input:
key = 2 ,
arr = [
10, 20, 30, 40, 50]
Output:
30
Explanation:
The value of arr[2] is 30 .
Input:
key = 4
,
arr = [10, 20, 30, 40, 50, 60, 70]
Output:
50
Explanation:
The value of the arr[4] is 50 .
Constraints:
0 ≤ key ≤ arr.size - 1
1 ≤ arr.size ≤ 10**6
1 ≤ arr[i] ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1708335711,
"func_sign": [
"public static int findElementAtIndex(int key, 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 int key = Integer.parseInt(read.readLine().trim());\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 Solution obj = new Solution();\n int res = obj.findElementAtIndex(key, nums);\n System.out.println(res);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "Main",
"solution": "//Back-end complete function Template for Java\nclass Solution {\n public static int findElementAtIndex(int key, int[] arr) { return arr[key]; }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\nclass Solution {\n public static int findElementAtIndex(int key, int[] arr) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1708335514,
"func_sign": [
"findElementAtIndex(self, key : int, arr : List[int]) -> int"
],
"initial_code": "if __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n key = int(input())\n arr = list(map(int, input().strip().split()))\n\n obj = Solution()\n res = obj.findElementAtIndex(key, arr)\n\n print(res)\n print(\"~\")\n",
"solution": "from typing import List\n\n\nclass Solution:\n def findElementAtIndex(self, key: int, arr: List[int]) -> int:\n return arr[key]\n",
"updated_at_timestamp": 1729753320,
"user_code": "\nfrom typing import List\nclass Solution:\n def findElementAtIndex(self, key : int, arr : List[int]) -> int:\n # code here\n \n"
}
|
eJzNVclOwzAU5MCJrxjlXCE/29k48RlIBHGAHLiEHloJCVHxEfC/jJ2kjVK7LXShdl6WxjNvGef18/L79urCj7uSN/fvyUsznc+SGyRp1aiqSSEKkkIr6BSGvwgPaBhYcInmk0A0xECsWykZJK8awxeKIJqhWVpKy2g5raCVinS2akoUyJEhJaUhNT20zsXhCSea4GSCpH6b1k+z+vnxdT5bxbnwcfAsxl+sI154Fp6TjwkGeVnH63JYn7p1jH6SrSQbxpOLskDY6Kqj+oHVbST4NmwziNaEYpa2HBESCUGMJ1yXT7epay+hadPhzMCM8q2aVU3hSMczi0Rm1ECcolNlPTfppI4VKYZz20dHQFaHQLrbV0uFyn6MpVu+iBV9udT7GfBEvWKIGW2UnoHYTSIHpZZRUrtFHJZh+5bdTLO1axTHbxsHbhh/TUmdcU6naYJ9Vfbuf7s0s306mNqvhR24mvbY5fwV579+Dfo0n8PgP0h7nPOyS0/16wMFPstaHq+YD1/XP3HYucQ=
|
702,927
|
Alternative Sorting
|
Given an array arr ofdistinct integers. Rearrange the array in such a way that the first element is the largest and the second element is the smallest, the third element is the second largest and the fourth element is the second smallest, and so on.
Examples:
Input:
arr[] = [7, 1, 2, 3, 4, 5, 6]
Output:
[7, 1, 6, 2, 5, 3, 4]
Explanation:
The first element is first maximum and second element is first minimum and so on.
Input:
arr[] = [1, 6, 9, 4, 3, 7, 8, 2]
Output:
[9, 1, 8, 2, 7, 3, 6, 4]
Explanation:
The first element is first maximum and second element is first minimum and so on.
Constraints:
1 ≤ arr.size() ≤ 10**5
1 ≤ arr[i] ≤ 10**5**
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static ArrayList<Integer> alternateSort(int[] arr)"
],
"initial_code": "// Initial Template for Java\n\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());\n\n while (t-- > 0) {\n\n ArrayList<Integer> array1 = new ArrayList<Integer>();\n String line = read.readLine();\n String[] tokens = line.split(\" \");\n for (String token : tokens) {\n array1.add(Integer.parseInt(token));\n }\n ArrayList<Integer> v = new ArrayList<Integer>();\n int[] arr = new int[array1.size()];\n int idx = 0;\n for (int i : array1) arr[idx++] = i;\n\n v = new Solution().alternateSort(arr);\n\n for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + \" \");\n\n System.out.println();\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n public static ArrayList<Integer> alternateSort(int[] arr) {\n int n = arr.length;\n // Sorting the array\n Arrays.sort(arr);\n ArrayList<Integer> ans = new ArrayList<>();\n\n // Adding elements in alternate order\n int i = 0, j = n - 1;\n while (i < j) {\n ans.add(arr[j--]);\n ans.add(arr[i++]);\n }\n\n // If there is a middle element left\n if (n % 2 != 0) {\n ans.add(arr[i]);\n }\n\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public static ArrayList<Integer> alternateSort(int[] arr) {\n\n // Your code goes here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"alternateSort(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 ans = ob.alternateSort(arr)\n print(*ans)\n print(\"~\")\n t -= 1\n",
"solution": "class Solution:\n\n def alternateSort(self, arr):\n # Sorting the array\n arr.sort()\n ans = []\n\n # Adding elements in alternate order\n i, j = 0, len(arr) - 1\n while i < j:\n ans.append(arr[j])\n ans.append(arr[i])\n j -= 1\n i += 1\n\n # If there is a middle element left\n if len(arr) % 2 != 0:\n ans.append(arr[i])\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def alternateSort(self,arr):\n # Your code goes here"
}
|
eJy1VdtKxEAM9UHwNw59XqSZW1u/RLDigxbxpe5DFwRR/Aj9X5NMuxY03a7owIaFnHOSOZPsvp1+9Gcnei7v+cvVc/HQb3dDcYGC2p5KOcUGRfe07W6H7u7mcTdMeU22/WvbFy8b/MREI0djrbHSmDRGjUGj1+g00mK9DJkJu5m8nxUJ81JWl1hxQ5DBjjm7QiEuOQVnkJ1ZmTnwCIhIqMB35y5AfBumeFAARVACVaAa1MBZ/TmmKUCAXghBiFEEkghVIliLcKMFrFvk95j8xPQo/oCz4zvu4eY08RXgSwTxEqlEVaLmWVD7uTH+yFUYQQwhxhCDiFHEMGqEb3tQqn0KUrzP1JBVYhZMWbvKZepcsRmL/8UezB71SNdGyWni4yib5cOazui72C97MKp9TeLCtuSkzBx3VNtbZ9Dj0o6ptfstcUeuicBlOpzAvMCD0krlkwpxzvR6sttu3lx15ZmdTWmTbfLWj8VRw2CPwOpV+Ic/gyycDgwnxYVf8nh4NLUPg6+5kXf9fv4JRfnlqg==
|
705,284
|
Rotate Each Row of Matrix K Times
|
You are given an integer k and matrixmat.Rotate the elements of the given matrix to the left k times and return the resulting matrix.
Examples:
Input:
k=1, mat=[[1,2,3]
[4,5,6]
[7,8,9]]
Output:
[[2, 3, 1]
[5, 6, 4]
[8, 9, 7]]
Explanation:
Rotate the matrix by one
1 2 3 2 3 1
4 5 6 => 5 6 4
7 8 9 8 9 7
Input:
k=2, mat=[[1, 2, 3]
[4, 5, 6]
[7, 8, 9]]
Output:
[[3, 1, 2]
[6, 4, 5]
[9, 7, 8]]
Explanation:
After rotating the matrix looks like
1 2 3 2 3 1 3 1 2
4 5 6 => 5 6 4 => 6 4 5
7 8 9 8 9 7 9 7 8
Constraints:
1<=k<=10**4
1<= mat.size(), mat[0].size, mat[i][j] <=1000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int[][] rotateMatrix(int k, 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 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 int n = Integer.parseInt(S[0]);\n int m = Integer.parseInt(S[1]);\n int k = Integer.parseInt(S[2]);\n int mat[][] = new int[n][m];\n for (int i = 0; i < n; i++) {\n String S1[] = read.readLine().split(\" \");\n for (int j = 0; j < m; j++) {\n mat[i][j] = Integer.parseInt(S1[j]);\n }\n }\n Solution ob = new Solution();\n int ans[][] = ob.rotateMatrix(k, mat);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) System.out.print(ans[i][j] + \" \");\n System.out.println();\n }\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n\n void reverse(int[][] mat, int i, int start, int end)\n {\n while (start <= end) {\n int temp = mat[i][start];\n mat[i][start] = mat[i][end];\n mat[i][end] = temp;\n start++;\n end--;\n }\n }\n\n int[][] rotateMatrix(int k, int mat[][])\n {\n // code here\n int n = mat.length;\n int m = mat[0].length;\n // Taking modulo of k with m to handle cases where k\n // exceeds m\n k %= m;\n\n // Iterating over rows and columns of the matrix\n for (int i = 0; i < n; i++) {\n // Reverse first k elements\n reverse(mat, i, 0, k - 1);\n // Reverse last n-k elements\n reverse(mat, i, k, m - 1);\n // Reverse whole array\n reverse(mat, i, 0, m - 1);\n }\n\n // Returning the rotated matrix\n return mat;\n }\n}",
"updated_at_timestamp": 1730478110,
"user_code": "// User function template for java\n\nclass Solution {\n int[][] rotateMatrix(int k, int mat[][]) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"rotateMatrix(self, k, mat)"
],
"initial_code": "import math\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n, m, k = map(int, input().strip().split(\" \"))\n mat = []\n for i in range(n):\n mat.append(list(map(int, input().strip().split(\" \"))))\n ob = Solution()\n ans = ob.rotateMatrix(k, 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": "class Solution:\n # Function to rotate the given matrix by K columns\n def rotateMatrix(self, k, mat):\n # Calculate the number of rows (n) and columns (m) from the matrix\n n = len(mat)\n m = len(mat[0])\n\n # Create a new matrix to store the rotated matrix\n ans = [[0] * m for _ in range(n)]\n\n # Reduce k to a value within the range of m to avoid unnecessary rotations\n k %= m\n\n # Iterate through each element of the matrix\n for i in range(n):\n for j in range(m):\n # Calculate the new position for each element after rotation\n ans[i][(j - k + m) % m] = mat[i][j]\n\n # Return the rotated matrix\n return ans\n",
"updated_at_timestamp": 1730478110,
"user_code": "class Solution:\n def rotateMatrix(self, k, mat):\n # code here\n"
}
|
eJztlkuOEzEQhlmw5BCfsh6huPzmJEgEsYAs2DSzmJFGQiAOAUdjx2Eot51MItmdhwZWk47S7i77/11fuTv+8fLXn1cv5s/b39p493X1ebq9v1u9YWU2k8djN5NBsDj8ZgpEEhmz1tsGIxiLcRiNmYCJmITJiMZFxwliEYdofHXDavtwu/14t/304cv9XfNRXarDZirCVA/VK7LsXfRG0WVvow5FmL3PZvquLt9uOM5CJfUbD/JgnAbLWSABiUhCMlbD1mBV1WIdVmkFbMQmbMZp2Bmc4NTV4Twu4CIu4TJew97gBW/xOiulHfARn/CZoOFgCEKwBEfQWQdCJCRCJmo4GqIQLdERPVGzisREzCQNJ0MSkiU5kicFkmadSJms4WzIQrZkR/bkQI5kpVKwrIflqtg4ZqkUGzC6OBVjI0aXp3JsyOgCVZCNGV2iSrJBo4tUUTZqdJkqy4aNLlSF2bjRpao0d+Doch0tTeVYTkPaZjRSEeLmJa3sSmsoIMw9Tk1hvVDzElyaSBtPFTloLuk10cP2kkGueHf6erksX/o/jhqJ6zKrb7gK4eg0JFqO1uvg3NUvb1B99a1px2XNwQz2PTjofWZ7SMG092O5moHrT7kazKE8/SXruddMwc4r7VQJ5cwaygVF7CxBuWINyikLY/9xDnnvcLbFNR5P/s++MMFiVH1OFM/nuQjZ1sTtYwGHFcy1Ux25q6J9agD/h0BnbZmLF9fiv8Uy5PFzcjHl5/3Whfst/7zjunbH5U/vud7/fP0Xr4kOmg==
|
713,980
|
Cutting Rectangles
|
Given arectangle of dimensions LxBfind the minimum number (N) of identical squares of maximum side that can be cut outfrom that rectangle so that no residue remains in the rectangle. Also find the dimension Kof that square.
Examples:
Input:
L = 2, B = 4
Output:
N = 2, K = 2
Explanation:
2 squares of 2x2 dimension.
Input:
L = 6, B = 3
Output:
N = 2, K = 3
Explanation:
2 squares of 3x3 dimension.
Constraints:
1 ≤ L, B ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1675773134,
"func_sign": [
"static List<Long> minimumSquares(long L, long B)"
],
"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 {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0){\n String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n long L = Long.parseLong(input_line[0]);\n long B = Long.parseLong(input_line[1]);\n\n Solution ob = new Solution();\n List<Long> ans = new ArrayList<Long>();\n ans = ob.minimumSquares(L, B);\n System.out.print(ans.get(0)+\" \");\n System.out.println(ans.get(1));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution{\n // Function to calculate the greatest common divisor of two numbers\n long gcd(long n, long m){\n if(m == 0)\n return n;\n return gcd(m, n%m);\n }\n\n // Function to find the minimum number of squares that can be formed with two given dimensions\n List<Long> minimumSquares(long L, long B)\n {\n // Calculating the greatest common divisor of L and B\n long x = gcd(L, B);\n List<Long> ans = new ArrayList<>();\n \n // Calculating the minimum number of squares\n ans.add((L*B)/(x*x));\n \n // Adding the greatest common divisor to the list\n ans.add(x);\n \n return ans;\n }\n}",
"updated_at_timestamp": 1730482168,
"user_code": "//User function Template for Java\n\nclass Solution{\n static List<Long> minimumSquares(long L, long B)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1675773134,
"func_sign": [
"minimumSquares(self, L, B)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n L, B = [int(x) for x in input().split()]\n ob = Solution()\n N, K = ob.minimumSquares(L, B)\n print(N, end=\" \")\n print(K)\n print(\"~\")\n",
"solution": "import math\n\n\nclass Solution:\n def minimumSquares(self, L, B):\n # Finding the greatest common divisor of L and B\n x = math.gcd(L, B)\n # Calculating the minimum number of squares required by dividing L*B by the square of the gcd\n return (L * B // (x * x), x)\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def minimumSquares(self, L, B):\n # code here"
}
|
eJyNVEtKA0EQdSGeo5mliHT9uzyJYMSFZuFmzCIBQRQPofe1JxonCameqc00dPF4/T7zef4NF2fbub2sh7u37rlfbdbdTepg0UPeTRqP3VXqlq+r5eN6+fTwslnv1vdWFv3Hou/er1IMF6HsrUQoM7hMo3gxFSasaEgsasUjMMlCDIBc2Ig9eQDJ6Oxq6AmBjQspB5COSGTgxRUykGiDJrKACiWxUuopEk60qJMh5KIIQBRC/pOzJKTFsgNGTwdBxyoAZ3U3zcox0zqF0vCxSMrhUrHaQmItf+OITSfLf4eswWF7PyNpx/E/achkDmekkeaoNywV9wn5vOzz81ZihvwxoLAytRIzNm5880TzxsUANVXYhtOx1QcG6EQlhDI4ukNud8LnpteMJvQf/wJh/bH2z8yztop/SKlN6q9U3KzVUZh3UuZBy7afJwJ8/3X9A02FsFU=
|
710,023
|
Compute Before Matrix
|
For a given 2D Matrixbefore,the corresponding cell (x, y) of the after matrix is calculated as follows:
Examples:
res = 0;
for(i = 0; i <= x; i++){
for( j = 0; j <= y; j++){
res += before(i,j);
}
}
after(x,y) = res;
Input:
N = 2, M = 3
after[][] = {{1, 3, 6},
{3, 7, 11}}
Output:
1 2 3
2 2 1
Explanation:
The before matrix for the given after matrix
matrix is {{1, 2, 3}, {2, 2, 1}}.
Reason:
According to the code given in problem,
after(0,0) = before(0,0) = 1
after(0,1) = before(0,0) + before(0,1)
= 1 + 2 = 3.
after(0, 2) = before(0,0) + before(0, 1)
+ before(0, 2) = 1 + 2 + 3 = 6.
Similarly we can calculate values for every
cell of the after matrix.
Input:
N = 1, M = 3
after[][] = {{1, 3, 5}}
Output:
1 2 2
Explanation:
The before matrix for the given after matrix
is {{1, 2, 2}}.
Constraints:
1 ≤ N, M, after[i][j] ≤ 10**9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1646061352,
"func_sign": [
"public int[][] computeBeforeMatrix(int N, int M,int[][] after )"
],
"initial_code": "//Initial Template for Java\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 PrintWriter out = new PrintWriter(System.out);\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 \n int[][] mat = new int[N][M];\n for(int i=0; i<N; i++)\n {\n String St[] = read.readLine().split(\" \"); \n for(int j=0; j<M; j++)\n {\n mat[i][j] = Integer.parseInt(St[j]);\n }\n }\n \n Solution ob = new Solution();\n int[][] before = ob.computeBeforeMatrix(N,M,mat);\n for(int i=0; i<N;i++){\n for(int j = 0; j<M;j++){\n out.print(before[i][j]);\n out.print(' ');\n \n }\n out.println();\n }\n \nout.println(\"~\");\n}\n out.flush();\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // Function to compute the \"before\" matrix based on the \"after\" matrix.\n public int[][] computeBeforeMatrix(int N, int M, int[][] after) {\n // Looping through each element of the \"after\" matrix in reverse order.\n for (int i = N - 1; i >= 0; i--) {\n for (int j = M - 1; j >= 0; j--) {\n // Subtracting the value of element above from the current element if i > 0.\n if (i > 0) {\n after[i][j] -= after[i - 1][j];\n }\n // Subtracting the value of element left from the current element if j > 0.\n if (j > 0) {\n after[i][j] -= after[i][j - 1];\n }\n // Adding the value of element top-left from the current element if i > 0 and j > 0.\n if (i > 0 && j > 0) {\n after[i][j] += after[i - 1][j - 1];\n }\n }\n }\n // Returning the modified \"after\" matrix.\n return after;\n }\n}\n",
"updated_at_timestamp": 1730480904,
"user_code": "//User function Template for Java\n\nclass Solution{\n public int[][] computeBeforeMatrix(int N, int M,int[][] after ){\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1646061352,
"func_sign": [
"computeBeforeMatrix(self, N, M, after)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n while T > 0:\n N, M = [int(i) for i in input().split()]\n after = []\n for j in range(N):\n after.append([int(i) for i in input().split()])\n ob = Solution()\n before = ob.computeBeforeMatrix(N, M, after)\n for i in range(len(before)):\n for j in range(len(before[i])):\n print(before[i][j], end=' ')\n print()\n T -= 1\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def computeBeforeMatrix(self, N, M, after):\n\n for i in range(N-1, -1, -1):\n for j in range(M-1, -1, -1):\n\n if i:\n after[i][j] -= after[i-1][j]\n if j:\n after[i][j] -= after[i][j-1]\n\n if i and j:\n after[i][j] += after[i-1][j-1]\n\n return after\n",
"updated_at_timestamp": 1730480904,
"user_code": "#User function Template for python3\n\nclass Solution:\n def computeBeforeMatrix(self, N, M, after):\n # Code here\n"
}
|
eJzNVbuOFEEMJCDiK6yJb1C/3A++BIlFBLAByXDBnoSEQERkZPC/lN09tz0cvbusELob6daeV5XLLs/Xpz+/P3uify+/IXj1aXq/3N4dphc02d3CxLvFkqdI1pBF4injl1wgjyxqnCg4igZ3GrkgSaAiOeMuXEFC1vF0Q9P+4+3+7WH/7s2Hu8OKQw4IgZh2yxpFEqgaJcRrlElI1agg/rJbps83tGXtyQtrBqZSzORxwlkKTCkPWQRFYrxZUKw8Ls8OQFCngChhgbxXKOpzhVyughjygjyErYeUXotX/i0CSBPmjxyctAf/IIUNQBL21gppF6H8AHKr8XoMtWR9q9FOoxxWaZx2FnqyzISRCG1OYGIGqLi1HSpLl/RXBhzCcQpFlCYrV4G1r3mEaztZpcNWtI4yHKLYCLINvmuPdA0GXtfjRD72bYZcsc49NIkUYRd7ovMrNel9PbYtqf0Pes9ZmWC7lXNWfqnRtnUcyZeTVMK9B/sJGQx/c1jR4eA6Fq6uArzBSfFp3JLQpjsqRDqORRm7Wg0XZNQB59bWezCVsgt5vAagSNAIhoml8pEHjpslUmw0CvKk51BJuYiKC2fIbNjk03xcMJFm54tvtCQO9fTKLpaOn03eDjl2u4Hz79uBzq+HbJhmTuW4kGbOqBGnsnj/Qtj/h9sNv79q+r0JkLz0FtDUm6EPHn5pcvvU2HDxx8asn5sA2rOz2V29lR7jWrreLPRv3WLs37J8xJ7O15g6V3flrb2y+itfamy+ZqEwxEi8dfYckuTpgbdf/3j+C9illl0=
|
701,226
|
Count Inversions
|
Given an array of integers. Find the Inversion Count in the array. Two elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.
Examples:
Input:
arr[] = [2, 4, 1, 3, 5]
Output:
3
Explanation:
The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).
Input:
arr[] = [2, 3, 4, 5, 6]
Output:
0
Explanation:
As the sequence is already sorted so there is no inversion count.
Input:
arr[] = [10, 10, 10]
Output:
0
Explanation:
As all the elements of array are same, so there is no inversion count.
Constraints:
1 ≤ arr.size()
≤ 10**5
1 ≤
arr[i]≤ 10**4**
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1618205913,
"func_sign": [
"static int inversionCount(int arr[])"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass Sorting {\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 for (int g = 0; g < t; g++) {\n String[] str = (br.readLine()).trim().split(\" \");\n int arr[] = new int[str.length];\n for (int i = 0; i < str.length; i++) arr[i] = Integer.parseInt(str[i]);\n System.out.println(new Solution().inversionCount(arr));\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "Sorting",
"solution": "class Solution {\n // Function to count inversions in the array.\n static int inversionCount(int arr[]) {\n int n = arr.length;\n int temp[] = new int[n];\n // returning the count of inversions in the array.\n return _mergeSort(arr, temp, 0, n - 1);\n }\n\n // Function to mergesort the array, which uses divide and conquer algorithm\n // on left and right halves of array for mergesort operation.\n static int _mergeSort(int arr[], int temp[], int left, int right) {\n int mid, inv_count = 0;\n if (right > left) {\n mid = (right + left) / 2;\n\n // Calling recursive function to sort left half of the array.\n inv_count = _mergeSort(arr, temp, left, mid);\n\n // Calling recursive function to sort right half of the array.\n inv_count += _mergeSort(arr, temp, mid + 1, right);\n\n // Calling merge function which sorts and merges both halves\n // of the array obtained after calling both recursive function.\n inv_count += merge(arr, temp, left, mid + 1, right);\n }\n // returning the count of inversions in the array.\n return inv_count;\n }\n\n // Function to sort and merge two parts of array and return inversion count.\n static int merge(int arr[], int temp[], int left, int mid, int right) {\n int i, j, k;\n int inv_count = 0;\n // i is pointer for left subarray.\n i = left;\n // j is pointer for right subarray.\n j = mid;\n // k is index for resultant merged subarray.\n k = left;\n\n // Using two pointers over the array which helps in storing the\n // smaller element and thus merging the subarray.\n while ((i <= mid - 1) && (j <= right)) {\n\n // Comparing element of the array at pointers i and j and accordingly\n // storing the smaller element and updating the pointers.\n if (arr[i] <= arr[j]) {\n temp[k++] = arr[i++];\n } else {\n temp[k++] = arr[j++];\n // Adding the inversions which is the number of elements which\n // are smaller than arr[j] in the left half of the array.\n inv_count = inv_count + (mid - i);\n }\n }\n\n // Copying the remaining elements of left subarray(if there are any)\n // to temp.\n while (i <= mid - 1) temp[k++] = arr[i++];\n\n // Copying the remaining elements of right subarray(if there are any)\n // to temp.\n while (j <= right) temp[k++] = arr[j++];\n\n // Copying back the merged elements to original array.\n for (i = left; i <= right; i++) arr[i] = temp[i];\n\n return inv_count;\n }\n}",
"updated_at_timestamp": 1730267630,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Function to count inversions in the array.\n static int inversionCount(int arr[]) {\n // Your Code Here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618205913,
"func_sign": [
"inversionCount(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nimport atexit\nimport io\nimport sys\n\n# Modified to skip the first line\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 _ in range(t): # Renamed variable to avoid shadowing built-in 'tt'\n a = list(map(int, input().strip().split()))\n obj = Solution()\n print(obj.inversionCount(a))\n print(\"~\")\n",
"solution": "class Solution:\n #Back-end complete function Template for Python 3\n\n #global variable to count total inversions\n inversion_count = 0\n\n #Function to count inversions in the array.\n def inversionCount(self, arr):\n n = len(arr)\n global inversion_count\n inversion_count = 0\n self.merge_sort(arr, 0, n - 1)\n #returning the count of inversions in the array.\n return inversion_count\n\n #Function to sort and merge two parts of array.\n def merge(self, arr, start, mid, end):\n global inversion_count\n temp = [0 for i in range(end - start + 1)]\n\n #i is pointer for left subarray.\n #j is pointer for right subarray.\n #k is index for resultant merged subarray.\n i, j, k = start, mid + 1, 0\n\n #Using two pointers over the array which helps in storing the\n #smaller element and thus merging the subarray.\n while i <= mid and j <= end:\n #Comparing element of the array at pointers i and j and accordingly\n #storing the smaller element and updating the pointers.\n if arr[i] <= arr[j]:\n temp[k] = arr[i]\n k += 1\n i += 1\n else:\n temp[k] = arr[j]\n k += 1\n j += 1\n #Adding the inversions which is the number of elements which\n #are smaller than arr[j] in the left half of the array.\n inversion_count += mid - i + 1\n\n #Copying the remaining elements of left subarray(if there are any) to temp.\n while i <= mid:\n temp[k] = arr[i]\n k += 1\n i += 1\n\n #Copying the remaining elements of right subarray(if there are any) to temp.\n while j <= end:\n temp[k] = arr[j]\n k += 1\n j += 1\n\n #Copying back the merged elements to original array.\n for i in range(start, end + 1):\n arr[i] = temp[i - start]\n\n #Function to mergesort the array, which uses divide and conquer algorithm\n #on left and right halves of array for mergesort operation.\n def merge_sort(self, arr, start, end):\n if start < end:\n mid = (start + end) // 2\n #Calling recursive function to sort left half of the array.\n self.merge_sort(arr, start, mid)\n #Calling recursive function to sort right half of the array.\n self.merge_sort(arr, mid + 1, end)\n #Calling merge function which sorts and merges both halves\n #of the array obtained after calling both recursive function.\n self.merge(arr, start, mid, end)\n",
"updated_at_timestamp": 1730267630,
"user_code": "class Solution:\n #User function Template for python3\n #Function to count inversions in the array.\n def inversionCount(self, arr):\n # Your Code Here"
}
|
eJytVMtKxEAQ9KD/Ucx5kXTPTDLxSwQjHjQHL3EPWVgQl/0I9+bH2j2bDavQ0RH7UDSBqulHdfaXh4+rixy3B0nuXt3zsN6M7gaOuoEqCbQSCkmhUagVokJQ8AqsQG4F12/X/ePYPz28bMZJK8Ru2HWDe1vh6wsRhACGN4i1wfPCY0QEg+cNnrK88tCgRgJJe6USQhGm8lXHi2Jx2yR9B1ANkkYakEhILQRqpSJDjC0xrsCZylmGsyRneY6WWGUOqM6D9eZorZVkm8yOSTmlo2U05aNxNM1+Ka7s28iXVsftH2okX1Il/cYdhlsCpttiivIhmf5ZeEXDYFkDjOqwpWNLFrHwoVPPaWp6+Ub4xxthpnwk4exKYJ6JtftZ75/kCodSzU5ozqwgFrN+P6e53L9ffwLDx4v2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.