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
|
|---|---|---|---|---|---|---|---|
700,218
|
Directed Graph Cycle
|
Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not.
Examples:
Input:
Output:
1
Explanation:
3 -> 3 is a cycle
Input:
Output:
0
Explanation:
no cycle in the graph
Constraints:
1 ≤ V, E ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass DriverClass {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n\n while (t-- > 0) {\n ArrayList<ArrayList<Integer>> list = new ArrayList<>();\n int V = sc.nextInt();\n int E = sc.nextInt();\n for (int i = 0; i < V; i++) list.add(i, new ArrayList<Integer>());\n for (int i = 0; i < E; i++) {\n int u = sc.nextInt();\n int v = sc.nextInt();\n list.get(u).add(v);\n }\n if (new Solution().isCyclic(V, list) == true)\n System.out.println(\"1\");\n else\n System.out.println(\"0\");\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "DriverClass",
"solution": "None",
"updated_at_timestamp": 1730268062,
"user_code": "/*Complete the function below*/\n\nclass Solution {\n // Function to detect cycle in a directed graph.\n public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isCyclic(self, V : int , adj : List[List[int]]) -> bool"
],
"initial_code": "# Initial Template for Python 3\n\nimport sys\n\nsys.setrecursionlimit(10**6)\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n V, E = list(map(int, input().strip().split()))\n adj = [[] for i in range(V)]\n for i in range(E):\n a, b = map(int, input().strip().split())\n adj[a].append(b)\n ob = Solution()\n\n if ob.isCyclic(V, adj):\n print(1)\n else:\n print(0)\n\n print(\"~\")\n",
"solution": "# Back-end Complete function Solution for Python\nclass Solution:\n\n def DFSUtil(self, adj, v, visited, recStack):\n # marking the current node as visited and part of recursion stack.\n visited[v] = True\n recStack[v] = True\n\n # calling function recursively for all neighbours\n # if any neighbour is visited and is in recStack then graph is cyclic.\n for neighbour in adj[v]:\n if visited[neighbour] == False:\n if self.DFSUtil(adj, neighbour, visited, recStack) == True:\n return True\n elif recStack[neighbour] == True:\n return True\n\n # removing the vertex from recursion stack.\n recStack[v] = False\n return False\n\n # Function to detect cycle in a directed graph.\n def isCyclic(self, V, adj):\n # marking all vertices as not visited and not a part of recursion stack\n visited = [False] * V\n recStack = [False] * V\n\n # calling the recursive helper function to detect cycle in\n # different DFS trees.\n for node in range(V):\n if visited[node] == False:\n if self.DFSUtil(adj, node, visited, recStack) == True:\n return True\n return False\n",
"updated_at_timestamp": 1730268062,
"user_code": "#User function Template for python3\nfrom typing import List\n\nclass Solution:\n \n #Function to detect cycle in a directed graph.\n def isCyclic(self, V : int , adj : List[List[int]]) -> bool :\n # code here"
}
|
eJzVVUFOwzAQ5MCBZ6x8rpDXjp2ElyCxiAPkwMX0kEpICMQj4HHceArerREqrakdglB7SqPZnfXMevJ8/Pp+ciS/87f4cPGgbsNyNaozUEjBgaegIT4hGAoGLAULDYWG3xnQagFquF8O1+Nwc3W3Gr9KnyioxwVs9sPYy+U6usTnoaXQQkehg55CD5oh8lcglmsFYirpO0BdyK7TGS34SpKWG+zjqBWu35pc/6ibZbCd4I5JLJpZcK11w3xOtGC+lvk65hN3vOjKzG4CH07ZhqbaeXSA2VXOUrHmaUhE0QYNIGtiAWMpSm1bLbSJ6tZfg4Jp+HKlo6IHjA2wBYwtMFoUm6DIJ46Ke9yn+bxTsbxW1fWmVC1zDvwdVoqLkpUhMe3p3kzbkRE7vXElKaHzUTTnKH7mWUhuy3+J8+sgqk2iLQWIyvzgM2cU4Dez+5KdiQOfPwkJwdV/YMxmcOHhJNfly+kHjW6FCg==
|
704,571
|
Incomplete Array
|
Given an array A containing N integers.Find out how many elements should be added such that all elements between the maximum and minimum of the array is present in the array.
Examples:
Input:
N=5
A=[205,173,102,324,957]
Output:
851
Explanation:
The maximum and minimum of given
array is 957 and 102 respectively.We need
to add 854 elements out of which
3 are already present.So answer is 851.
Input:
N=1
A=[545]
Output:
0
Explanation:
We don't need to add any element
to the array.
Constraints:
1<=N,A[i]<=10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int countElements(int N, int A[])"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int N = Integer.parseInt(read.readLine());\n int A[] = new int[N];\n String[] S = read.readLine().split(\" \");\n for (int i = 0; i < N; i++) A[i] = Integer.parseInt(S[i]);\n Solution ob = new Solution();\n System.out.println(ob.countElements(N, A));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n int countElements(int[] arr) {\n Set<Integer> st = new HashSet<>();\n int maxEle = arr[0], minEle = arr[0];\n int n = arr.length;\n for (int i = 0; i < n; i++) {\n st.add(arr[i]);\n minEle = Math.min(minEle, arr[i]);\n maxEle = Math.max(maxEle, arr[i]);\n }\n int totalEle = maxEle - minEle + 1;\n return totalEle - st.size();\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n int countElements(int N, int A[]) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"countElements(self,N,A)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n N = int(input())\n A = list(map(int, input().strip().split()))\n\n ob = Solution()\n print(ob.countElements(N, A))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def countElements(self, N, A):\n hash = [0]*100005 # initialize a hash table for counting elements\n minimum = 100005 # initialize minimum as a large number\n maximum = 0 # initialize maximum as 0\n for i in A: # loop through each element in A\n hash[i] += 1 # increment the count of element i in hash table\n # update maximum if i is larger than maximum\n maximum = max(maximum, i)\n # update minimum if i is smaller than minimum\n minimum = min(minimum, i)\n ans = 0 # initialize ans as 0\n # loop through the range between minimum and maximum\n for i in range(minimum + 1, maximum):\n if hash[i] == 0: # if count of element i is 0, increment ans\n ans += 1\n return ans # return ans as the result\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def countElements(self,N,A):\n #code here"
}
|
eJzVlsFuFDEMhjlw4imsOVcodpKJ0xs3HgGJIg6wBy5LD1sJCRXxEPC++P9nOYDkstpSFUbyp9XEcfxn7GS/Pv3+8tkTPq9exI/Xn5cP++ubw3Ipi17ttcDiEVDJSnbSySlzzgF0oAFluZBl9+l69+6we//2483hZ9CI+OVqv9xeyG9LdRiXChpZyUE6qBzVSKRhMXCSThrJUed7H2SazEiSMeiWKk26rAKVogguuoq6WBEzsSa2irnUItWkNqk9W6hnC3UYVBu1GLWAg1zJTlbSSPo733sjOeocdSXpMxhzMOZgtEH/Qf9B/0H/Qf+V/qsnQjzRETJ6q6YCGlnJAupMwmXFULn/im0Jq2EtLPZJ1rAR5mHzWJei8FS4Kny1HasoPhcAf8UEnVvEAGNjhlVuPoAZhhmGGYYZFjOS3M1HWstb2yAHCojIFFH7JqT1TUzvWfDWNN9pdmRBl022HipGNImE8bT6Is+H3dSsH9zv0IeUVwobR3mb1E332aVU/sta+jutYA+bP47dvBnknEtk3nWLeHj9ofl+XS7L+1E3/d5VU2Z+BB2v00c5eM8U3k9X3vsJDXN+w5d/uuNP+QiWn5Sq8Z8hO33tfhf5m2/PfwCuinAY
|
703,864
|
Maximum bitonic subarray sum
|
Given an array arr[] of integers, the task is to find the maximum sum of a bitonic subarray. A bitonic subarray is one in which the elements first increase, may stay the same, and then decrease. A strictly increasing or strictly decreasing subarray is also considered a bitonic subarray.Examples:
Examples:
Input:
arr[] = [5, 3, 9, 2, 7, 6, 4]
Output:
19
Explanation:
The subarray with the maximum sum is [2, 7, 6, 4] with a sum of 19.
Input:
arr[] = [5, 4, 3, 2, 1, 10, 6]
Output:
17
Explanation:
The subarray with the maximum sum is [10, 6], with a sum of 17.
Expected Time Complexity:
O(n)
Expected Auxiliary Space:
O(1)
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1617815347,
"func_sign": [
"public long maxSumBitonicSubArr(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 = 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.maxSumBitonicSubArr(arr));\n System.out.println(\"~\");\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n // Function to find the maximum sum of a bitonic subarray in a given array of\n // integers.\n public long maxSumBitonicSubArr(int[] arr) {\n int n = arr.length;\n long maxSum = arr[0], currentSum = arr[0];\n // flag indicates the direction of the subarray; 0: no direction, 1: increasing,\n // 2: decreasing\n int flag = 0;\n for (int i = 1; i < n; i++) {\n // Handle case when the current element is greater than the previous one.\n if (arr[i] > arr[i - 1]) {\n if (flag == 2) {\n // Start a new sum if the sequence was previously decreasing.\n currentSum = arr[i - 1] + arr[i];\n } else {\n // Continue adding to sum if the sequence is increasing.\n currentSum += arr[i];\n }\n flag = 1;\n } else if (arr[i] < arr[i - 1]) {\n // Continue adding to sum if the sequence starts or continues to\n // decrease.\n currentSum += arr[i];\n flag = 2;\n } else {\n // Handle equal elements based on the sequence type.\n if (flag == 2) {\n maxSum = Math.max(maxSum, currentSum);\n currentSum = arr[i];\n } else {\n currentSum += arr[i];\n }\n }\n // Update the maximum sum found so far.\n maxSum = Math.max(maxSum, currentSum);\n }\n return maxSum;\n }\n}\n",
"updated_at_timestamp": 1730473572,
"user_code": "class Solution {\n public long maxSumBitonicSubArr(int[] arr) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617815347,
"func_sign": [
"maxSumBitonicSubArr(self, arr)"
],
"initial_code": "def main():\n t = int(input())\n for _ in range(t):\n arr = list(map(int, input().split()))\n solution = Solution()\n print(solution.maxSumBitonicSubArr(arr))\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n\n def maxSumBitonicSubArr(self, arr):\n n = len(arr)\n\n max_sum = arr[0]\n current_sum = arr[0]\n flag = 0 # 0: no direction, 1: increasing, 2: decreasing\n\n for i in range(1, n):\n # Handle case when current element is greater than the previous\n if arr[i] > arr[i - 1]:\n if flag == 2:\n # Start new sum if previous sequence was decreasing\n current_sum = arr[i - 1] + arr[i]\n else:\n # Continue summing if increasing\n current_sum += arr[i]\n flag = 1\n elif arr[i] < arr[i - 1]:\n # Continue or start decreasing sequence\n current_sum += arr[i]\n flag = 2\n else:\n # Handle equal elements\n if flag == 2:\n max_sum = max(max_sum, current_sum)\n current_sum = arr[i]\n else:\n current_sum += arr[i]\n # Update max sum at each iteration\n max_sum = max(max_sum, current_sum)\n\n return max_sum\n",
"updated_at_timestamp": 1730473572,
"user_code": "class Solution:\n\n def maxSumBitonicSubArr(self, arr):\n # code here\n pass\n"
}
|
eJylVUtOwzAQZYHENUZZV8jjXxJOgkQRC+iCTWHRSkgIxCHgkuy4AW9spzStxqGtpXlJnJnn+WXycf71c3GW1vU3bm5em8fl83rVXFHD8yUbLOqxBDqBViAKBGKy5MhTaGbULF6eF/erxcPd03pVGAJs4nz5Pl82bzMaUzvYsthShHjKz2wUKscKz8aHEc+wx/CeOmopai4Gjdek2GuXfkhMzkxOTc5Nr6UkaWtn7vtfnhUyW3GeLMRBPCRAIqSFdOJ5CYJYNFlU2W3ueHjbF/W2mIdC5wo9lBTPOMJ2smJ/VcehOBxOEPuENu2Yf6eCTTeZVBav4TxiQCiICIEhPoQpkcilS1sxvfZJ1Rq9J2GkdmX9wwF4ASdgBVigdFZCTmgTuoQ+Ydi6d1s6WV91FeVivVuqeZlqpOM6pAuh0iC56F6vt2o8lJvqtXPq4fuVO2jmsYVVWyHfDbDGZSY6rGJXja8y146Yafj2TGWqZfLRvKySZR/8ZAr59ByO/h3RHPz3iJVv6rgB0JvNCNiZAPHEEdAbi8QOqbj9vPwFfUP51Q==
|
700,910
|
Sum the common elements
|
You are given two arrays of size n1 and n2. Your task is to find all the elements that are common to both the arrays and sum them. If there are no common elements the output would be 0.
Examples:
Input:
5 6
1 2 3 4 5
2 3 4 5 6 7
Output:
14
Explanation:
Common unique elements in both arrays are 2, 3, 4 and 5 so answer will be 2+3+4+5 = 14
Input:
5 6
1 2 2 3 5
3 3 2 2 6 5
Output:
10
Explanation:
Common unique elements in both arrays are 2, 3 and 5 so answer will be 2+3+5 = 10
|
geeksforgeeks
|
Easy
|
{
"class_name": "Geeks",
"created_at_timestamp": 1615292571,
"func_sign": [
"public\n static int commonSum(int n1, int n2, int arr1[], int arr2[])"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\n\nclass GFG {\npublic\n static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while (t-- > 0) {\n int n1 = sc.nextInt();\n int n2 = sc.nextInt();\n int arr1[] = new int[n1];\n int arr2[] = new int[n2];\n for (int i = 0; i < n1; i++)\n arr1[i] = sc.nextInt();\n\n for (int i = 0; i < n2; i++)\n arr2[i] = sc.nextInt();\n\n Geeks obj = new Geeks();\n System.out.println(obj.commonSum(n1, n2, arr1, arr2));\n \nSystem.out.println(\"~\");\n}\n }\n}\n\n// Position this line where user code will be pasted.\n",
"script_name": "GFG",
"solution": "static int commonSum(int n1, int n2, int arr1[], int arr2[])\nNone",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Geeks {\npublic\n static int commonSum(int n1, int n2, int arr1[], int arr2[]) {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1688553429,
"func_sign": [
"commonSum(self,n1,n2,arr1,arr2)"
],
"initial_code": "if __name__ == '__main__':\n for _ in range(int(input())):\n n1, n2 = map(int, input().split())\n arr1 = list(map(int, input().split()))\n arr2 = list(map(int, input().split()))\n obj = Solution()\n print(obj.commonSum(n1, n2, arr1, arr2))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n\n # Function to find sum of common elements in two arrays.\n def commonSum(self, n1, n2, arr1, arr2):\n # if size of arr1 is greater than arr2, swap them.\n if n1 > n2:\n arr1, arr2 = arr2, arr1\n # creating a set of arr1 to quickly check for common elements.\n s = set(arr1)\n ans = 0\n mod = 10**9 + 7\n\n # iterating over each element in arr2.\n for e in arr2:\n # if element is present in set, add it to ans and remove it from set.\n if e in s:\n ans += e\n s.remove(e)\n\n return ans % mod\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def commonSum(self,n1,n2,arr1,arr2):\n #code here"
}
|
eJytVDFOxDAQpIB/jFyf0NqOnYSXIGFEASlozBU5CQmBeAQ8jI7nsJvkxHGwl3OE0zi2d2Z3xt7X0/fPs5NhXH7w5OrJ3Of1pjcXMDZlQkg55YgaDVpYMiuY7nHd3fbd3c3Dpp+OUsovKZvnFX7GB4m3mL6dqYJjD+IQHMETKk6LGSOhJjSEljiz0tQiokAKpoAKqsASInHI3gITCZPGYRvSaOpRAY/AGrKCXLtP2aFCZEmLBbVSqgA6hqwY9NuaYbPln5oXA296PqQJHYJGIDYxVnFiU5xGqMU5uMGGaQhKux1whWAeftJG5nr18a94reJCE2pxgS/pnAP2oANWoMgtdYHG61AYje1zt//23o94ATMtQaP61ZqWAwzCLQOZ6yJxv42MxgzNRO0mQe0mO0UfZ9D12/kX+FelIA==
|
713,136
|
GCD Array
|
You are given an array, arrof lengthN,and also a single integerK. Your task is to split the array arrintoKnon-overlapping, non-empty subarrays. For each of the subarrays, you calculate the sum of the elements in it. Let us denote these sums as S1, S2,S3, ...,SK. Where Si denotes the sum of the elements in the i**thsubarray from left.
Examples:
Input:
N = 5
K = 4
arr[] = {6, 7, 5, 27, 3}
Output:
3
Explanation:
Since K = 4, you have to split the array into 4 subarrays.
For optimal splitting, split the array into
4 subarrays as follows: [[6], [7, 5], [27], [3]]
Therefore, S
1 = 6, S
2 = 7 + 5 = 12, S
3 = 27, S
4 = 3
Hence, G = GCD(S
1
, S
2
, S
3
, S
4
) = GCD(6, 12, 27, 3) = 3
It can be shown that 3 is the maximum value of G that can be obtained.
Thus, the answer is 3.
Input:
N = 3
K = 2
arr[] = {1, 4, 5}
Output:
5
Explanation:
Since K = 2, you have to split the array into 2 subarrays.
For optimal splitting, split the array into
2 subarrays as follows: [[1, 4], [5]]
Therefore, S
1 = 1 + 4 = 5, S
2 = 5
Hence, G = GCD(S
1
, S
2
) = GCD(5,5) = 5
It can be shown that 5 is the maximum value of G that can be obtained.
Thus, the answer is 5.
1 <= N <= 10**4
1 <= K <= N
1 <= arr[i] <= 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1671443925,
"func_sign": [
"public static int solve(int N, int K, 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 K;\n K = Integer.parseInt(br.readLine());\n \n \n int[] arr = IntArray.input(br, N);\n \n Solution obj = new Solution();\n int res = obj.solve(N, K, 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 solve(int N, int K, int[] arr) {\n // calculating the sum of all elements in the array\n int sum=0;\n for(int i:arr){\n sum+=i;\n }\n \n // finding all the divisors of the sum\n ArrayList<Integer> divisors=new ArrayList<>();\n for(int i=1;i*i<=sum;i++){\n if(sum%i==0){\n divisors.add(i);\n if(i!=sum/i)divisors.add(sum/i);\n }\n }\n \n // sorting the divisors in descending order\n Collections.sort(divisors,Collections.reverseOrder());\n \n // calculating the cumulative sum of the array\n for(int i=1;i<N;i++){\n arr[i]+=arr[i-1];\n }\n \n // checking for divisors that satisfy the condition\n int ans=1;\n for(int i:divisors){\n int cnt=0;\n for(int j=0;j<N;j++){\n if(arr[j]%i==0){\n cnt++;\n }\n }\n if(cnt>=K){\n ans=i;\n break;\n }\n }\n \n // returning the answer\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n public static int solve(int N, int K, int[] arr) {\n // code here\n }\n}\n \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1671443925,
"func_sign": [
"solve(self, N : int, K : int, arr : List[int]) -> int"
],
"initial_code": "class IntArray:\n def __init__(self) -> None:\n pass\n\n def Input(self, n):\n arr = [int(i) for i in input().strip().split()] # array input\n return arr\n\n def Print(self, arr):\n for i in arr:\n print(i, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n N = int(input())\n K = int(input())\n arr = IntArray().Input(N)\n obj = Solution()\n res = obj.solve(N, K, arr)\n print(res)\n print(\"~\")\n",
"solution": "from typing import List\n\n\nclass Solution:\n def solve(self, N: int, K: int, arr: List[int]) -> int:\n total = sum(arr) # Finding the total sum of all elements in the array.\n divisors = [] # Initializing an empty list to store the divisors.\n m = int(total ** 0.5) # Finding the square root of total.\n\n # Finding all the divisors of total and storing them in the list.\n for i in range(1, m+1):\n if total % i == 0:\n divisors.append(i)\n if i != (total // i):\n divisors.append(total // i)\n\n # Sorting the divisors in descending order.\n divisors.sort(reverse=True)\n\n # Calculating prefix sums of the array elements.\n for i in range(1, N):\n arr[i] += arr[i-1]\n\n out = 1 # Initializing the output variable to 1.\n\n # Checking each divisor in descending order.\n for x in divisors:\n # Initializing a counter variable to count the number of elements divisible by x.\n cnt = 0\n\n # Counting the number of elements divisible by x using prefix sums.\n for y in arr:\n if (y % x == 0):\n cnt += 1\n\n # If the count is greater than or equal to K, update the output and break the loop.\n if cnt >= K:\n out = x\n break\n\n return out # Returning the output.\n",
"updated_at_timestamp": 1729753320,
"user_code": "\n\nfrom typing import List\nclass Solution:\n def solve(self, N : int, K : int, arr : List[int]) -> int:\n # code here\n \n"
}
|
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
|
703,672
|
GCD of two numbers
|
Given two positive integers a and b, find GCD of a and b.
Examples:
Input:
a = 3
b = 6
Output:
3
Explanation:
GCD of 3 and 6 is 3
Input:
a = 1
b = 1
Output:
1
Explanation:
GCD of 1 and 1 is 1
Constraints:
1 ≤ a, b ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1708867817,
"func_sign": [
"public static int gcd(int a, int b)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while(t-- > 0){\n \n int a;\n a = Integer.parseInt(br.readLine());\n \n \n int b;\n b = Integer.parseInt(br.readLine());\n \n Solution obj = new Solution();\n int res = obj.gcd(a, b);\n \n System.out.println(res);\n \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730472381,
"user_code": "\nclass Solution {\n public static int gcd(int a, int b) {\n // code here\n }\n}\n \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1708867817,
"func_sign": [
"gcd(self, a : int, b : int) -> int"
],
"initial_code": "if __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n a = int(input())\n b = int(input())\n obj = Solution()\n res = obj.gcd(a, b)\n print(res)\n print(\"~\")\n",
"solution": "class Solution:\n # Function to find the greatest common divisor of two numbers.\n def gcd(self, a: int, b: int) -> int:\n # base case: if b is 0, return a as gcd.\n if b == 0:\n return a\n\n # recursively calling gcd function with b and a%b.\n return self.gcd(b, a % b)\n",
"updated_at_timestamp": 1730472381,
"user_code": "\nclass Solution:\n def gcd(self, a : int, b : int) -> int:\n # code here\n \n"
}
|
eJxrYJn6j5UBDCK+AxnR1UqZeQWlJUpWCkqGMXmGBjAQk2cJA0o6CkqpFQWpySWpKfH5pSUI5XUxeUq1OgqoZlhaGJmYGpqZGsfkmZpbWACZhiSaYGhkbGJqZm5hCTLM3MzUxNgIlxGWuBwBAcbmSExcRiCUYncNEJHqAaRgJFkvsnZSgx7hFTKsJRRQRPmWoNORFONLPmhOgqUlCgMIyUgQEy3IkGQw0zBIAckhA07IUDcTlZ6JzVQmpGcqtJCDs0EUyckFEUvIAUhxnkcElQn5YYXTpxR5FTnoKc/iWFIh4TiiWjqNnaIHAIWtv2w=
|
713,541
|
Last cell in a Matrix
|
Given a binary matrixof dimensionswith Rrows and Ccolumns. Start fromcell(0, 0), moving in theright direction. Perform the following operations:
Examples:
Input:
matrix[][] = {{0,1},
{1,0}}
R=2
C=2
Output:
(1,1)
Explanation:
Input:
matrix[][] = {{0, 1, 1, 1, 0},
{1, 0, 1, 0, 1},
{1, 1, 1, 0, 0}}
R=3
C=5
Output:
(2,0)
Explanation:
We will leave the grid after visiting the index (2,0).
Constraints:
1<= R,C<=1000
0<= matrix[i][j] <=1
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1673867042,
"func_sign": [
"static int [] endPoints(int [][]matrix, int R, int C)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out=new PrintWriter(System.out);\n int t = Integer.parseInt(read.readLine());\n \n while(t-- > 0)\n {\n String str[] = read.readLine().trim().split(\"\\\\s+\");\n int r = Integer.parseInt(str[0]);\n int c = Integer.parseInt(str[1]);\n int matrix[][] = new int[r][c];\n \n for(int i = 0; i < r; i++)\n {\n int k = 0;\n str = read.readLine().trim().split(\"\\\\s+\");\n for(int j = 0; j < c; j++){\n matrix[i][j] = Integer.parseInt(str[k]);\n k++;\n }\n }\n Solution obj = new Solution();\n int[] p = obj.endPoints(matrix,r,c);\n out.print(\"(\" + p[0]+ \", \" + p[1]+ \")\" +\"\\n\");\n \nout.println(\"~\");\n}\n out.close();\n }\n}\n\n",
"script_name": "GFG",
"solution": "class Solution {\n \n public boolean isValid(int x, int y, int n, int m) {\n if (x < 0 || y < 0 || x >= n || y >= m) {\n return false;\n }\n return true;\n }\n\n public int[] endPoints(int[][] arr, int n, int m) {\n int[] result = new int[2];\n int currx = 0, curry = 0, d = 0;\n int[] dx = {0, 1, 0, -1};\n int[] dy = {1, 0, -1, 0};\n\n while (true) {\n if (arr[currx][curry] == 0) {\n if (isValid(currx + dx[d], curry + dy[d], n, m)) {\n currx += dx[d];\n curry += dy[d];\n } else {\n result[0] = currx;\n result[1] = curry;\n return result;\n }\n } else {\n arr[currx][curry] = 0;\n d++;\n d %= 4;\n }\n }\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n static int [] endPoints(int [][]matrix, int R, int C){\n //code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1673867042,
"func_sign": [
"endPoints(self, matrix, R, C)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n r, c = map(int, input().strip().split())\n matrix = []\n for i in range(r):\n line = [int(x) for x in input().strip().split()]\n matrix.append(line)\n ob = Solution()\n ans = ob.endPoints(matrix, r, c)\n print('(', ans[0], ', ', ans[1], ')', sep='')\n print(\"~\")\n",
"solution": "class Solution:\n def isvalid(self, x, y, n, m):\n if x < 0 or y < 0 or x >= n or y >= m:\n return False\n return True\n\n def endPoints(self, arr, n, m):\n dx = [0, 1, 0, -1]\n dy = [1, 0, -1, 0]\n\n currx, curry, d = 0, 0, 0\n\n while True:\n if arr[currx][curry] == 0:\n if self.isvalid(currx + dx[d], curry + dy[d], n, m):\n currx += dx[d]\n curry += dy[d]\n else:\n return (currx, curry)\n else:\n arr[currx][curry] = 0\n d += 1\n d %= 4\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def endPoints(self, matrix, R, C):\n #code here\n"
}
|
eJzNVM0KwjAM9iDevPkAoSeFIU3cLj6J4MSD7uCl7rCBIIoPoe9r1x/ZcC1dvbjCknbJ1+RLlsf4NZuM1LOZSmV7ZSdR1hVbA8NcIMgXZwmw4lIWh6o47s91Zb7PeQJ8kYt7LtgtgR5PjPEkIOsOTgD0AKxgJYMGubrCEwx5sVB6NzwANlhq58IiT1wppAbEJKfxWidKjeEsg8wi4iff9j3O05hEyBJsgnaCoJdZUrkrCKXFhILSz3CImkcjTaG45tTKPkv8Q8vBVHD3zxbaLU1NQjqGPBMhrGt+aZtu72Ekihov1GQcM6RcV37XJNwSA8vHB1Vaj8LIWbh7Lt/RVqWi
|
700,373
|
You and your books
|
You have n stacks of books. Each stack of books has some height arr[i] equal to the number of books on that stack ( considering all the books are identical and each book has a height of 1 unit ). In one move, you can select any number of consecutive stacks of books such that the height of each selected stack of books arr[i] <= k. Once such a sequence of stacks is chosen, You can collect any number of books from the chosen sequence of stacks.What is the maximum number of books that you can collect this way?
Examples:
Input:
8 1
3 2 2 3 1 1 1 3
Output:
3
Explanation
We can collect maximum books from consecutive stacks numbered 5, 6, and 7 having height less than equal to K.
Input:
8 2
3 2 2 3 1 1 1 3
Output:
4
Explanation
We can collect maximum books from consecutive stacks numbered 2 and 3 having height less than equal to K.
Constraints:
1 <= n <=
10**5
1 <= k <=
10**9
0 <= arr[i] <= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1618519841,
"func_sign": [
"long max_Books(int arr[], int n, int k)"
],
"initial_code": "import java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws Exception {\n Scanner sc = new Scanner(System.in);\n int T = sc.nextInt();\n\n while (T > 0) {\n int N = sc.nextInt();\n int k = sc.nextInt();\n int ar[] = new int[N];\n //\tint count = 0;\n for (int i = 0; i < N; i++) ar[i] = sc.nextInt();\n\n System.out.println(new Solution().max_Books(ar, N, k));\n T--;\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function to find the maximum number of books that can be bought within the given\n // budget\n long max_Books(int a[], int n, int k) {\n int size = a.length;\n long max_so_far = 0, max_ending_here = 0;\n\n // Loop through the array to calculate the maximum sum of books' prices\n for (int i = 0; i < size; i++) {\n // Check if the price of the current book is within the budget\n if (a[i] <= k) {\n // Add the price of the current book to the current subarray sum\n max_ending_here = max_ending_here + a[i];\n\n // Update the maximum sum if the current subarray sum is greater\n if (max_so_far < max_ending_here) max_so_far = max_ending_here;\n } else {\n // Reset the current subarray sum if the price of the current book\n // exceeds the budget\n max_ending_here = 0;\n }\n }\n\n // Return the maximum sum of books' prices\n return max_so_far;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "\nclass Solution {\n long max_Books(int arr[], int n, int k) {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618519841,
"func_sign": [
"max_Books(self, n, k, arr)"
],
"initial_code": "if __name__ == '__main__':\n t = int(input())\n for i in range(t):\n temp = list(map(int, input().strip().split()))\n n = temp[0]\n k = temp[1]\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n print(ob.max_Books(n, k, arr))\n print(\"~\")\n\n# Contributed by: Harshit Sidhwa\n",
"solution": "class Solution:\n\n def max_Books(self, n, k, a):\n # initialize variables to store the sum of books and the maximum sum\n sum = 0\n ans = 0\n\n # iterate over all the books\n for i in range(n):\n # if the number of pages in the current book is less than or equal to k,\n # add the number of pages to the sum\n if a[i] <= k:\n sum += a[i]\n # if the number of pages in the current book is greater than k,\n # reset the sum to 0\n else:\n sum = 0\n # update the maximum sum with the current sum\n ans = max(ans, sum)\n\n # return the maximum sum\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "\nclass Solution:\n #Your task is to complete this function\n #Function should return an integer\n #a - list/array containing height of stack's respectively\n def max_Books(self, n, k, arr):\n #code here"
}
|
eJzFVs1OwzAM5sCFt7B6npDjNGnLkyARxAF24BJ26KRJEwjxDPC+JE6WbqwWU1XYLHXOT798sT+neb/8+ri64N/tNjh32+rZr9Z9dQOVcl4hGOctNNCCAQ0ECurg2WoB1XKzWj72y6eHl3WfXyF0/s356nUBP4AM1M5jeJ0CTM2W4BByrwCpJUhC0M5r0BkoQlGB1AxKvJyWwRuJL4F13sStQno27Nn4lMBIYmogDFFhmZhhbmHmmUZTD/dJMW7HlkFh9jEbHRbGuLeQXBX3phIjxZlA6EKu42YVt3bTihv/qTQNSAsr1EI4ahbVoIUU3TYszICDMAxbEovJhiVKphjDCDS6TmBhsnwoSyXJZ+cTk0jiwb22yjaM6NwzjOuMQOxL8WlH0xiIWYzSsyy1Uhw5TPvRsUf229wTsCTNjYvuj5Jp5GxKJTa3qKUDQ1b1qQwGChMLq5MYjAkH9dmlg/UUoTdnoqtaie7BJ4FO/CaIdfNvx49USuL5M18pmam1pGDvuhA2ka4LeHhfkGCl+8LsctNz6K18n+4/r78Br18wag==
|
703,522
|
Divisible by 7
|
Given an n-digit large number in form of string, check whether it is divisible by 7 or not.Print 1if divisible by 7, otherwise 0.
Examples:
Input:
num = "8955795758
"
Output:
1
Explanation:
8955795758 is divisible
by 7.
Input:
num = "1000"
Output:
0
Explanation:
1000 is not divisible
by 7.
Constraints:
1 ≤ |num| ≤10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int isdivisible7(String num)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass 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().trim();\n Solution ob = new Solution();\n System.out.println(ob.isdivisible7(s));\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "// Backend complete function Template for Java\nclass Solution {\n int isdivisible7(String num) {\n int n = num.length();\n // Append required 0s at the beginning.\n if (n % 3 == 1) {\n num = num + \"00\";\n n += 2;\n }\n if (n % 3 == 2) {\n num = num + \"0\";\n n += 1;\n }\n // add digits in group of three in gSum\n int gSum = 0, p = 1;\n for (int i = n - 1; i >= 0; i--) {\n // group saves 3-digit group\n int group = 0;\n group += num.charAt(i--) - '0';\n group += (num.charAt(i--) - '0') * 10;\n group += (num.charAt(i) - '0') * 100;\n gSum = gSum + group * p;\n // generate alternate series of plus and minus\n p = p * -1;\n }\n // calculate result till 3 digit sum\n if (gSum % 7 == 0) return 1;\n return 0;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n int isdivisible7(String num) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isdivisible7(self, num)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n s = input().strip()\n ob = Solution()\n print(ob.isdivisible7(s))\n print(\"~\")\n",
"solution": "# Backend complete function Template for python3\n\nclass Solution:\n def isdivisible7(self, num):\n n = len(num)\n\n # Append required 0s at the beginning.\n if (n % 3 == 1):\n num += \"00\"\n n += 2\n\n elif (n % 3 == 2):\n num += \"0\"\n n += 1\n\n # add digits in group of three in gSum\n GSum = 0\n p = 1\n i = n - 1\n while i >= 0:\n # group saves 3-digit group\n group = 0\n group += ord(num[i]) - ord('0')\n i -= 1\n group += (ord(num[i]) - ord('0')) * 10\n i -= 1\n group += (ord(num[i]) - ord('0')) * 100\n\n GSum = GSum + group * p\n\n # generate alternate series of\n # plus and minus\n p *= (-1)\n i -= 1\n\n if GSum % 7 == 0:\n return 1\n return 0\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def isdivisible7(self, num):\n # code here"
}
|
eJxrYJlayMIABhFZQEZ0tVJmXkFpiZKVgpJhTJ55TJ6SjoJSakVBanJJakp8fmkJQrIOKFmro4Cqw9CEdC1GxiamZji1GeDQZgkGJNtmZEi6FguStZiQ7jAzY5K1GKAA0rWTaSFSnBG0G1fsgQwgWQ+exIVXj6EJNGWSrB3hYSCOiQGlBEp9TlmcAcMNmrzIyTMmlrhTP1Y9+JyI03HEuCx2ih4A2xZi9A==
|
704,500
|
Minimum Cost To Make Two Strings Identical
|
Given two strings x and y, and two values costX and costY, the task is to find the minimum cost required to make the given two strings identical. You can delete characters from both the strings. The cost of deleting a character from string X is costX and from Y is costY. The cost of removing all characters from a string is the same.
Examples:
Input:
x = "abcd", y = "acdb", costX = 10
costY = 20.
Output:
30
Explanation:
For Making both strings
identical we have to delete character
'b' from both the string, hence cost
will be = 10 + 20 = 30.
Input:
x = "ef", y = "gh", costX = 10
costY = 20.
Output:
60
Explanation:
For making both strings
identical, we have to delete 2-2
characters from both the strings, hence
cost will be = 10 + 10 + 20 + 20 = 60.
Constraints:
1 ≤ |x|, |y| ≤ 1000
1<= costX, costY <= 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int findMinCost(String x, String y, int costX, int costY)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GfG {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while (t-- > 0) {\n String X = sc.next();\n String Y = sc.next();\n int costX = sc.nextInt();\n int costY = sc.nextInt();\n\n Solution ob = new Solution();\n System.out.println(ob.findMinCost(X, Y, costX, costY));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GfG",
"solution": "class Solution {\n \n public int lcs(int ind1, int ind2, String s1, String s2, int[][] dp) {\n if (ind1 == s1.length() || ind2 == s2.length()) return 0;\n\n if (dp[ind1][ind2] != -1) return dp[ind1][ind2];\n\n if (s1.charAt(ind1) == s2.charAt(ind2)) {\n return dp[ind1][ind2] = 1 + lcs(ind1 + 1, ind2 + 1, s1, s2, dp);\n }\n\n return dp[ind1][ind2] = Math.max(lcs(ind1 + 1, ind2, s1, s2, dp), lcs(ind1, ind2 + 1, s1, s2, dp));\n }\n \n public int findMinCost(String x, String y, int costX, int costY) {\n // Your code goes here\n int m = x.length();\n int n = y.length();\n int[][] dp = new int[m][n];\n for (int[] row : dp) {\n java.util.Arrays.fill(row, -1);\n }\n\n int lenLCS = lcs(0, 0, x, y, dp);\n\n // Cost of making two strings identical is sum of\n // following two:\n // 1. Cost of removing extra characters from first string\n // 2. Cost of removing extra characters from second string\n return costX * (m - lenLCS) + costY * (n - lenLCS);\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n public int findMinCost(String x, String y, int costX, int costY) {}\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"findMinCost(self, x, y, costX, costY)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n\n for i in range(T):\n X, Y, costX, costY = input().split()\n costX = int(costX)\n costY = int(costY)\n ob = Solution()\n ans = ob.findMinCost(X, Y, costX, costY)\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n def findMinCost(self, X, Y, costX, costY):\n # creating a matrix to store the lengths of the common subsequence\n dp = [[0] * (len(X) + 1) for i in range(len(Y) + 1)]\n\n for i in range(1, len(Y) + 1):\n for j in range(1, len(X) + 1):\n # if the characters at the current positions are equal,\n # then increase the length of the common subsequence by 1\n if X[j - 1] == Y[i - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n # else, take the maximum length of the common subsequence\n # from either the top cell or the left cell\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n\n # calculate the cost by multiplying the number of characters\n # not present in the common subsequence with their respective costs\n x = (len(X) - dp[-1][-1]) * costX\n y = (len(Y) - dp[-1][-1]) * costY\n\n # return the total cost\n return x + y\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef findMinCost(self, x, y, costX, costY):\n\t\t# code here"
}
|
eJy1VduO2jAQ7UMf+hmjPK8qOxcI/ZKVSlUFZ3LZje1gOxCoWvUj2u/oW7+viaGCsthQdneQAHmSOTPHZ2a+v/35+90ba/e/hj8fvwS1aDsTfICAzkW2YDkWZVU/PDZcyHaptOlW636z3W769aozWi1bKXjz+FBXZYE5W2RAwyhOJtN0RoCSwWA2WnAHAfYtMoP5Z9mZvyAJHZxkLr7NRfD1Dk7wTwyeHCQWweIQB4QreC93H9j/9hDZYJEn1mT0OeI1UpTaqFqU69pUOuPYoChNRcHlCXdcQRJHIXUhjuZAzOuiQIXCsCpT2fCi0hTOHIYjQRA6q4qcNRnUhmUax7wPVeijK3Y8QWbpdGLr2osg9LAaTj20qkzkkh+KyXQ+KBJOj7c9Wy2EhYHYDRVN3Eh6wzkO6bNdDaBLUSujWc35ZijTas1+ubRMPGVoXHYoGGpZHJKG86cDZ/+pZVyh4FIhk7xtsLeuQ/PCOfdxx5LLXURTb3UjdeeU9w+dfM8nuZZQny58kE+gvDnQC0kkJEqc6rTvv6hEY49ET0M+txvS17nSo+nqITYiMUlvnfxXjX5vR143Pdnl8Zk4IZ69P/27cywuDl/3/uiNF+jdhs3N65CG42bZY3768f4PluX0eQ==
|
703,755
|
Check an Integer is power of 3 or not
|
Given a positive integer N, write a function to find if it is a power of three or not.
Examples:
Input:
N = 3
Output:
Yes
Explanation:
3
**1
is a power of 3.
Input:
N = 5
Output:
No
Explanation:
5 is not a power of 3.
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static String isPowerof3(int N)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0)\n {\n int N = Integer.parseInt(read.readLine());\n\n Solution ob = new Solution();\n System.out.println(ob.isPowerof3(N));\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730473110,
"user_code": "//User function Template for Java\nclass Solution{\n static String isPowerof3(int N){\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isPowerof3(ob,N)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N = int(input())\n\n ob = Solution()\n print(ob.isPowerof3(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n def isPowerof3(ob, N):\n \"\"\" The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .\"\"\"\n\n # Check if the given number is a power of 3\n if 1162261467 % N == 0:\n return \"Yes\"\n else:\n return \"No\"\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def isPowerof3 (ob,N):\n # code here "
}
|
eJxrYJkax8IABhHhQEZ0tVJmXkFpiZKVgpJhTJ6lko6CUmpFQWpySWpKfH5pCVQqMrU4Jq8uJk+pVkcBVYeROclaLAxJt8XEmGQ95kZk+MbQgnT/mJmake4jQ0szC9L9ZGppYEK6rwzNzQ1NSPeXkTmeFOGXjyt2cVmERwfJWiAI4kByQh8UZZAkgksvPqtBqcSCnFQMshPkXdLDCIxiDMFejiEnuaGFGdD/eKMXT7YiIrpip+gBAJ+YZaQ=
|
713,975
|
Avoid Explosion
|
Geek is a chemical scientist who is performing an experiment to find an antidote to a poison. The experiment involves mixing some solutions in a flask. Based on the theoretical research Geek has done, he came up with an n*2 array 'mix', where mix[i] = {X, Y} denotes solutions X and Y that needs to be mixed.
Also, from his past experience, it has been known that mixing some solutions leads to an explosion and thereby completely ruining the experiment. The explosive solutions are also provided as am * 2 array 'danger' where danger[i] = {P, Q}denotes that if somehow solutions P and Q get into the same flask it will result in an explosion.
Examples:
Input:
n = 5, m = 2
mix = {{1, 2}, {2, 3}, {4, 5}, {3, 5}, {2, 4}}
danger = {{1, 3}, {4, 2}}
Output:
answer = {"Yes", "No", "Yes", "Yes", "No"}
Explanation:
Mixing the first solution(1 and 2) of 'mix' do not result in any kind of explosion hence answer[0] is "Yes", while mixing(2nd solution) 2 and 3 is not allowed because it will result in an explosion as 1 and 3 would be in same solution hence we have returned "No" as the answer for 2nd solution. Mixing the third solution(4 and 5) and 4th solution(3 and 5) of 'mix' do not result in any kind of explosion hence answer[2] and answer[3] is "Yes". While mixing 2 and 4 is not allowed because it will result in an explosion hence we have returned "No" as the answer for it.
Input:
n = 3, m = 2
mix = {{1, 2}, {2, 3}, {1, 3}}
danger = {{1, 2}, {1, 3}}
Output:
answer = {"No", "Yes", "No"}
Explanation:
Mixing solutions 1 and 2 is dangerous hence
answer[0] = "No", but solutions 2 and 3 can
be mixed without any problem therefore answer[1]
= "Yes". Again, mixing solutions 1 and 3 is
dangerous due to which answer[2] = "No".
danger[i][0] != danger[i][1]
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1675772636,
"func_sign": [
"ArrayList<String> avoidExlosion(int mix[][], int n, int danger[][], int m)"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\nimport java.io.*;\n\n public class GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n PrintWriter ot = new PrintWriter(System.out);\n\n int t = Integer.parseInt(br.readLine());\n\n while (t-- > 0) {\n String s[] = br.readLine().trim().split(\" \");\n int n = Integer.parseInt(s[0]);\n int m = Integer.parseInt(s[1]);\n int mix[][] = new int[n][2];\n int danger[][] = new int[m][2];\n\n for (int i = 0; i < n; i++) {\n s = br.readLine().trim().split(\" \");\n mix[i][0] = Integer.parseInt(s[0]);\n mix[i][1] = Integer.parseInt(s[1]);\n }\n for (int i = 0; i < m; i++) {\n s = br.readLine().trim().split(\" \");\n danger[i][0] = Integer.parseInt(s[0]);\n danger[i][1] = Integer.parseInt(s[1]);\n }\n Solution soln = new Solution();\n\n ArrayList<String> ans = soln.avoidExlosion(mix, n, danger, m);\n\n for (String x : ans) ot.print(x + \" \");\n ot.println();\n }\n\n ot.close();\n }\n\n}\n// Position this line where user code will be pasted.\n",
"script_name": "GFG",
"solution": "class Solution {\n ArrayList<String> avoidExlosion(int mix[][], int n, int danger[][], int m) {\n // Initialize the ArrayList to store the final answers\n ans = new ArrayList<>();\n\n // Initialize the parent and rank arrays for Union-Find\n par = new int[n + 1];\n rank = new int[n + 1];\n for (int i = 0; i <= n; i++) par[i] = i;\n\n // Iterate through the mix array\n for (int i = 0; i < mix.length; i++) {\n // Get the nodes of the current mix\n int x = mix[i][0];\n int y = mix[i][1];\n\n // Find the parent of x and y nodes\n int px = find(x);\n int py = find(y);\n\n // Boolean flag to keep track if the mix can be performed\n boolean bool = true;\n\n // Iterate through the danger array\n for (int j = 0; j < danger.length; j++) {\n // Get the nodes of the current danger\n int a = danger[j][0];\n int b = danger[j][1];\n\n // Find the parent of a and b nodes\n int pa = find(a);\n int pb = find(b);\n\n // If the parents of x, y and a, b are the same, mix cannot be performed\n if ((px == pa && py == pb) || (px == pb && py == pa)) {\n bool = false;\n break;\n }\n }\n\n // If mix is possible, perform the union and add \"Yes\" to the answer list\n if (bool) union(x, y);\n if (bool) {\n ans.add(\"Yes\");\n } else {\n ans.add(\"No\");\n }\n }\n\n // Return the final answer list\n return ans;\n }\n\n private ArrayList<String> ans;\n private int par[], rank[];\n\n // Union operation for Union-Find\n private void union(int u, int v) {\n u = par[u];\n v = par[v];\n if (rank[u] > rank[v])\n par[v] = u;\n else if (rank[u] < rank[v])\n par[u] = v;\n else {\n par[u] = v;\n rank[v]++;\n }\n }\n\n // Find operation for Union-Find\n private int find(int node) {\n if (par[node] == node) return node;\n return par[node] = find(par[node]);\n }\n}",
"updated_at_timestamp": 1730482084,
"user_code": "// User function Template for Java\n\nclass Solution {\n ArrayList<String> avoidExlosion(int mix[][], int n, int danger[][], int m) {\n // Code Here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1675772636,
"func_sign": [
"avoidExlosion(self, mix, n, danger, m)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n n, m = map(int, input().split())\n mix = [[0 for _ in range(2)] for _ in range(n)]\n danger = [[0 for _ in range(2)] for _ in range(m)]\n for i in range(n+m):\n if i < n:\n a, b = map(int, input().split())\n mix[i][0] = a\n mix[i][1] = b\n else:\n a, b = map(int, input().split())\n danger[i-n][0] = a\n danger[i-n][1] = b\n\n obj = Solution()\n print(*obj.avoidExlosion(mix, n, danger, m))\n\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\n# cook your dish here\nclass Solution:\n def avoidExlosion(self, mix, n, danger, m):\n # code here\n\n def find(x):\n if par[x] != x:\n par[x] = find(par[x])\n return par[x]\n\n def union(u, v):\n u = find(u)\n v = find(v)\n if (rank[u] > rank[v]):\n par[v] = u\n elif (rank[u] < rank[v]):\n par[u] = v\n else:\n par[u] = v\n rank[v] += 1\n\n ans = []\n par = [0] * (n+1)\n rank = [0] * (n+1)\n\n for i in range(n+1):\n par[i] = i\n\n for i in range(n):\n x = mix[i][0]\n y = mix[i][1]\n px, py = find(x), find(y)\n boolean = True\n\n for j in range(m):\n a, b = danger[j][0], danger[j][1]\n pa, pb = find(a), find(b)\n if (px == pa and py == pb) or (px == pb and py == pa):\n boolean = False\n\n if (boolean):\n union(x, y)\n\n if (boolean):\n ans.append(\"Yes\")\n else:\n ans.append(\"No\")\n\n return ans\n",
"updated_at_timestamp": 1730482084,
"user_code": "#User function Template for python3\n\nclass Solution:\n def avoidExlosion(self, mix, n, danger, m):\n #code here"
}
|
eJztVsuO00AQ5MAX8AUtn1fI3eMZj/kIroAwcIAcuHhX2qyEhEB8BPwvU9VZSBCOnddqI2WlSMl6prqqpro9P57+ev/sCf9evypf3n6tPg83d8vqhVTaD600/aBi/WAS+iHgZyOxH6KkfkjSYoliSYMlEUsSlpQH1ZVUiy83i4/LxacP13fLFeqbxa3g8/JaNr/2w/ey6duVbFJIKLyFAqsHPG3wP9taeK2o/xwpqjUqTAnP/ZCl64dOtOYeconYk7CnxZ7M55N2/IfdNEvW2Z0ltqqoEYGcExBaIGQgdEDgap0wdAb9rRLybJ//OecWT0l2xxO//zrmKaEP9RSRDaJonkY0EnYkHBE4iTgtYXYPyhbjx4Va7dz/eBpArgG5v+62IJe5sHONtWtU12iuMbjGIjW5VFhYNBUELaIKhmYxVGMrlNLAIKwRNhC1IWgkZiJkS8RMwM7xauLNjOSBn/GM7DUdZmYkA7ajKTVNUZoyvxHn5WK8KW3V/KcQmDwZrScjMxkMSMeAIBpgUGqjuIkhnkEM75fS69HZMT1kp6Sn5KckqP5a8FeTjw6SNCdp81psu3F7BWrU71C7PQ/dirbqRXPDgxveuOHRDU803AqKJTFEsxUrKJYl4LzY0OG+oTnelPNNOeCUE0454owjzjj1UbNjSRxJ42+aSBkoWWSgZJGBkkWGHa/ny+ntcYAb15XDrypyvLvK+iDXyyQ/5iSXsx/lU5E8USZ3uJk+2qvpmga5iJgU4ftOKOURXFjPd86dLgYPGOYzvSddLkrvfj7/DbeDPy0=
|
706,104
|
Jump Game
|
Given an positive integer N and a list of N integers A[]. Each element in the array denotes the maximum length of jump you can cover. Find out if you can make it to the last index if you start at the first index of the list.
Examples:
Input:
N =
6
A[] =
{1, 2, 0, 3, 0, 0}
Output:
1
Explanation:
Jump 1 step from first index to
second index. Then jump 2 steps to reach
4
th
index, and now jump 2 steps to reach
the end.
Input:
N =
3
A[]
=
{1, 0, 2}
Output:
0
Explanation:
You can't reach the end of the array.
Constraints:
1 <= N <= 10**5
0 <= A[i] <= 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int canReach(int[] A, int N)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int N = Integer.parseInt(read.readLine());\n \n String S1[] = read.readLine().split(\" \");\n \n int[] A = new int[N];\n \n for(int i=0; i<N; i++)\n A[i] = Integer.parseInt(S1[i]);\n\n Solution ob = new Solution();\n System.out.println(ob.canReach(A,N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function to check if we can reach the last index from the 0th index.\n public boolean canReach(int[] arr) {\n int n = arr.length;\n\n // Initializing the current index to the last index.\n int cur = n - 1;\n\n // Iterating from the last index to the 0th index.\n for (int i = n - 1; i >= 0; i--) {\n // Checking if we can reach the current index from the ith index.\n if (i + arr[i] >= cur) {\n cur = i; // Updating the current index if true.\n }\n }\n\n // Returning 1 if we can reach the last index from 0th index,\n // otherwise returning 0.\n return cur == 0 ? true : false;\n }\n}",
"updated_at_timestamp": 1730269578,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int canReach(int[] A, int N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"canReach(self, A, 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 A = list(map(int, input().split()))\n\n ob = Solution()\n print(ob.canReach(A, N))\n print(\"~\")\n",
"solution": "class Solution:\n # Function to check if it is possible to reach the end of the array from start\n def canReach(self, A, N):\n cur = N - 1\n for i in range(N - 1, -1, -1):\n if i + A[i] >= cur:\n cur = i\n\n # If cur becomes greater than 0, return 0 (not possible to reach end)\n if cur > 0:\n return 0\n else:\n return 1\n",
"updated_at_timestamp": 1730269578,
"user_code": "#User function Template for python3\n\nclass Solution:\n def canReach(self, A, N):\n # code here "
}
|
eJytVDsOwjAMZYB7RJkr5CTtwkmQCGKADiyhQyshIRCHgCuwcUecNKVQYcCFRpYy2O9j1zkOz9fRIHzTC15mO7l2RVXKiZDKOgXWGQFCY6QY9VEyETLfFvmyzFeLTVXGAkw+WCf3ieigZBiIYZr6cE9F1hNPg1eGMA0ckIcNjVJ1NPxtUByK4DChqXVb1V199qC6bbV5cuPzgeOISu6kkaAvZmkdlUz51X76PYp6TC8w8bkEmwyA3g7WhOqWRgUBkCneV3P9vtmfnxYICPD/oP++OrzdYZtpf0D2CxmtaWu1c58elPlpfANQQI0p
|
701,966
|
Print Anagrams Together
|
Given an array of strings, return all groups of strings that are anagrams. The groups must be created in order of their appearance in the original array. Look at the sample case for clarification.
Examples:
Input:
N = 5
words[] = {act,god,cat,dog,tac}
Output:
act cat tac
god dog
Explanation:
There are 2 groups of
anagrams "god", "dog" make group 1.
"act", "cat", "tac" make group 2.
Input:
N = 3
words[] = {no,on,is}
Output:
is
no on
Explanation:
There are 2 groups of
anagrams "is" makes group 1.
"no", "on" make group 2.
1<=|S|<=10
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1730726713,
"func_sign": [
"public ArrayList<ArrayList<String>> anagrams(String[] arr)"
],
"initial_code": "import 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 sc = new Scanner(System.in);\n int t = sc.nextInt();\n sc.nextLine(); // Ignore the newline after the test case input\n while (t-- > 0) {\n String inputLine = sc.nextLine();\n String[] arr = inputLine.split(\" \");\n\n Solution ob = new Solution();\n ArrayList<ArrayList<String>> result = ob.anagrams(arr);\n result.sort(Comparator.comparing(a -> a.get(0)));\n for (ArrayList<String> group : result) {\n for (String word : group) {\n System.out.print(word + \" \");\n }\n System.out.println();\n }\n System.out.println(\"~\");\n }\n sc.close();\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730828142,
"user_code": "class Solution {\n public ArrayList<ArrayList<String>> anagrams(String[] arr) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1729589971,
"func_sign": [
"Anagrams(self, words, n)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n t = int(input())\n for tcs in range(t):\n words = input().split()\n\n ob = Solution()\n ans = ob.Anagrams(words)\n\n for grp in sorted(ans):\n for word in grp:\n print(word, end=' ')\n print()\n\n print(\"~\")\n",
"solution": "#Back-end complete function Template for Python 3\n\nfrom collections import defaultdict\n\n\nclass Solution:\n # Function to find all anagrams in a given list of strings.\n def Anagrams(self, s):\n # Creating a defaultdict to store anagrams.\n d = defaultdict(list)\n\n # Iterating over the given list of strings.\n for i, e in enumerate(s):\n # Sorting each string to form a key for grouping anagrams.\n e = str(sorted(e))\n # Appending the current string to its corresponding group.\n d[e].append(s[i])\n\n # Creating a list to store the groups of anagrams.\n res = []\n # Iterating over the values of the defaultdict.\n # Each value represents a group of anagrams.\n for l in d.values():\n # Appending the group of anagrams to the result list.\n res.append(l)\n\n # Returning the final list of groups of anagrams.\n return res\n",
"updated_at_timestamp": 1730828142,
"user_code": "#User function Template for python3\nclass Solution:\n\n def Anagrams(self, words, n):\n '''\n words: list of word\n n: no of words\n return : list of group of anagram {list will be sorted in driver code (not word in grp)}\n '''\n\n #code here\n"
}
|
eJzNV2uO00AM5gcX4AZW+YdWSPuXkyAxCE1ek1c9aR5tEgTiEHBf7EnaZJKdqNsuaCM1mThj+7PHr/56++fDuzfm+vyeFl++7xIsmnr3CXaPAiVd4NEFPl0Q0AXS8wMIfI8++IEEScvdA+zCtgj9Ogy+6aYeBRhuErJmIKqRKtDIFWgkC/wpcPfjAWwQbde1QL92pnqPuoBC4x7aru876Lu+daG4MAmc2OZiec1CBLIYFwyWE0YqTtIsZzmHsqqb48mwtqdjU1flgUXnWZrEKgqNysMpLOuuSXShk6ary/B0AFkFJIakZCntCyoJfesfPQLnHf22B/Ia+Yb9Qj/PG8/ApwfTzJ2+S7fTR+7LTrgRPLGtoPLBnaGY0xsBCnzKVPKoZZrLtajKTpUSAaWSZVeiglyWSqJZ8pdSKuyANoZlR3daoe4SVIrJtAllJ7vS5ZML29O6JgX8fSZY4AyGwIueq2IEbG/OnSthpA5EoJXFN7FlG1Ht0rQhjYDbmgXauByGKa1VroFvms6GbkoDR5rvB0EYRpFScZwkcIYVK5Zn0Kx3OSN3LW5Nmpw80+EA6DDmIPtT1ZK5ZXSslQc62ycpNrHXHVUdgSF2cYPpPsk00CbaSgy9pNyVVRUEA5g05VStmMCUOD3n8ZA1MKmpj55yp+tcApdcS4PAbXRra+YUVsxxOzfhkpMjzI1QBnYzcBgNBddUDTBlw5z0rJaYreYLbTe7kzTOjRBD5QM0AQl2wZkqpOW10ZbhMXhg8ufwvlXuB/hzeALDwVgLp0ADaWwMw+OCe+bIEcGZMnl6lL00wrh8Qi5w8Nn4nHzBHcfyhuswrDwADv2BFEVBCGe67zMRrBIPpsa37Ym11FyEdJJSKc8zKtpFEUVah5REWZbnQD9i1AWzVlcl6VK1wAU0gTYagZaSofzMEAlcYBJoG+Bw0KVBSQ5uoOgejoTOhJO071lE2/pDX5QtvfOaO1fvj4Se3zgxzsJOMCQKvSN6PtjN8ODO6Ll4M0RZ+qmFzuGtwAtcKOK4sWDRwGIBozCyjLihO6V2Gwiv6E8v054oI5cdKV22pLnCG6fEgoLI6oTPHhfXEhZDpCNzrQn6FqDPnLofYdS6nLG3Ry/36DSOSy+feXbvW+fhavq8OzGd6ozL/k3ablixzuO7Qns92twf7I9XBfk1hcWE8euoK+O/zRcqK/eVlGeWE2P/egI2Nm/6zMHzvycONu41Th1rXI7J4+vvj38BLUZ/Cw==
|
703,220
|
Longest Palindrome in a String
|
Given a string str, find the longest palindromic substring in str. Substring of string str: str[ i . . . . j ] where 0 ≤ i ≤ j < len(str). Return the longest palindromic substring of str.
Examples:
Input:
str = "aaaabbaa"
Output:
aabbaa
Explanation:
The longest Palindromic substring is "aabbaa".
Input:
str = "abc"
Output:
a
Explanation:
"a", "b" and "c" are the longest palindromes with same length. The result is the one with the least starting index.
Constraints:
1 ≤ |str| ≤ 10**3
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1731263624,
"func_sign": [
"static String longestPalindrome(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 = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S = read.readLine();\n\n Solution ob = new Solution();\n System.out.println(ob.longestPalindrome(S));\n }\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1731263624,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Static method to find the longest palindromic substring\n static String longestPalindrome(String s) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731263624,
"func_sign": [
"longestPalindrome(self, s: str) -> str"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n S = input()\n\n ob = Solution()\n\n ans = ob.longestPalindrome(S)\n\n print(ans)\n",
"solution": "class Solution:\n\n def longestPalindrome(self, s: str) -> str:\n # Edge case: if the input string is empty, return an empty string\n if not s:\n return \"\"\n\n start, end = 0, 0 # Initialize the start and end indices of the longest palindrome\n\n # Loop through each character in the string to consider each as the center of a potential palindrome\n for i in range(len(s)):\n # Expand around the current character for odd-length palindromes\n odd = self.expandAroundCenter(s, i, i)\n\n # Expand around the current character and the next character for even-length palindromes\n even = self.expandAroundCenter(s, i, i + 1)\n\n # Get the maximum length palindrome from both odd and even expansion\n max_len = max(odd, even)\n\n # If a longer palindrome is found, update the start and end indices\n if max_len > end - start + 1:\n start = i - (max_len - 1) // 2\n end = i + max_len // 2\n\n # Return the longest palindromic substring from the calculated start and end indices\n return s[start:end + 1]\n\n def expandAroundCenter(self, s: str, left: int, right: int) -> int:\n # Expand outwards while the characters at both ends are equal and within bounds\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n # Return the length of the palindrome found\n return right - left - 1\n",
"updated_at_timestamp": 1731263624,
"user_code": "#User function Template for python3\n\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n # code here"
}
|
eJzlVc1OhDAQ9uDJp9hw3pioN5/ERIwZygBdoIVS/jQmPoQ+kDcfy9LFXRYpCu5uTOyGbCkz30y/6dd5Pn19PzvR4+ZNTW4fLcqSXFrXC+vKZuA4AIS4rn4A1itETdd/jl4hLjZTa7mwsEqQSHTveS5bmE/vHd+Om82sp+ViN25VP9SVtvB8r7VinDMBBAkImxFaUBKDC3G7ZAjew9j4bya92Jc287jwEcMsCxF99WIzB5j6GSJsbW2m7b5gXugPBY9oTCNemKF6VkPJgSKvYRPR83w/CGwWYYGRZqIhyIQMreFgcscYzoxxjLyMhB1+/FVKBs/IWkcBXYWROmhJKjKZF6XSqRJqWeQyE2nCWRyFKxq0chuX5CSooZT0macMXWS0exMAYxBCDaHAghYoBJcguemC+IIyFCotUci6lgLLFDJXKc9zM9P+usZDYHrDzSa7hr/AGrmyfhom2QP2iOmksMNlPWAZp1/5cyqcmUjYmnzbjEyHZ1qTGs2+6b0z5b6vll3NC2/u6br/epvW2rDaq/NIT26dBss8k6hJckjL/96hu4pVehVGVTb03b2cfwD0Og3q
|
705,830
|
Nth digit of pi
|
Calculate the Nth digit in the representation of Pi.
Examples:
Input:
N =
1
Output:
3
Explanation:
Value of Pi is 3.14...
So, the first digit is 3.
Input:
N =
2
Output:
1
Explanation:
Value of Pi is 3.14...
So, the second digit is 1.
Constraints:
1 <= N <= 10**4
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int nthDigOfPi(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\n Solution ob = new Solution();\n System.out.println(ob.nthDigOfPi(N));\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int nthDigOfPi(int N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"nthDigOfPi(self, N)"
],
"initial_code": "# Initial Template for Python 3\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.nthDigOfPi(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\n# Function to calculate the square root of a number using Newton's method.\ndef sqrt(n, MAX):\n # Using floating point arithmetic to get a more accurate result.\n float_max = 10**16\n n_float = float((n*float_max)//MAX)/float_max\n\n # Calculating an initial approximation using the floating point square root.\n curr = (int(float_max*math.sqrt(n_float))*MAX)//float_max\n\n n_MAX = n*MAX\n\n # Iteratively improving the approximation using Newton's method.\n while True:\n prev = curr\n curr = (curr+n_MAX//curr)//2\n if curr == prev:\n break\n return curr\n\n# Function to calculate the power of 10.\n\n\ndef power(n):\n if n == 0:\n return 1\n ans = power(n//2)\n if n % 2 == 0:\n return ans*ans\n return ans*ans*10\n\n# Function to calculate the nth digit of pi.\n\n\ndef pi(n):\n MAX = power(n+10)\n c = (640320**3)//24\n n = 1\n a_n = MAX\n a_summation = MAX\n b_summation = 0\n\n # Calculating the series expansion of pi up to the nth term.\n while a_n != 0:\n a_n *= -(6*n-5)*(2*n-1)*(6*n-1)\n a_n //= n*n*n*c\n a_summation += a_n\n b_summation += n*a_n\n n += 1\n\n # Using the series expansion to calculate pi.\n ans = (426880*sqrt(10005*MAX, MAX)*MAX)//(13591409 *\n a_summation+545140134*b_summation)\n\n return ans\n\n# Solution class to solve the problem.\n\n\nclass Solution:\n\n def nthDigOfPi(self, N):\n # Calculating the nth digit of pi.\n p = str(pi(N))\n\n return p[N-1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def nthDigOfPi(self, N):\n # code here "
}
|
eJytk00OgjAQhVngPUjXxJSWgnoSE2tcKAs3lQUkJkbjIfSw7uwPKmBnkMRZsGm+N2/eMNfwHkwCW8tHGASrE9mrsq7IIiKJVAmllMQRKY5lsa2K3eZQV83rTKqLVOQcR11EwAgDENMFYnIfwzXjMKmY/XJYgVsFZ5f61LStRBiRXIAioiXyPcBcFwBmUEeKRuVMewPTT+xtFw+PtVx7gzQpMp6iQ/eQVAvmmX5KOTO4LjQAF7lozeONxDpplgoa8s7QWt/45X1g/z+FS3onGdgJZIAN2OfgvTX9kJ4Jxkpp5x6D9lKTzdn/I73OGn68avzGUIHXeOvb9AkqnJC6
|
703,440
|
Subarray Inversions
|
Given an array arr[], the task is to find the sum of the number of inversions in all subarrays of length k. To clarify, determine the number of inversions in each of the n-k+1 (where, n is the size of the array)subarrays of length k and add them together.
Examples:
Input:
arr[] = [1, 6, 7, 2], k = 3
Output:
2
Explanation:
There are two subarrays of size 3, {1, 6, 7} and {6, 7, 2}. Count of inversions in first subarray is 0 and count of inversions in second subarray is 2. So sum is 0 + 2 = 2.
Input:
arr[] = [12, 3, 14, 8, 15, 1, 4, 22], k = 4
Output:
14
Constraints:
1 ≤ arr.size ≤ 10**3
1 ≤ arr[i] ≤ 10**3**
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public long inversion_count(int[] a, int k)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass Abc {\n public static void main(String args[]) throws IOException {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while (t-- > 0) {\n String a[] = in.readLine().trim().split(\"\\\\s+\");\n int N = a.length;\n int arr[] = new int[N];\n for (int i = 0; i < N; i++) arr[i] = Integer.parseInt(a[i]);\n int k = Integer.parseInt(in.readLine());\n Solution ob = new Solution();\n long result = ob.inversion_count(arr, k);\n System.out.println(result);\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Abc",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n public long inversion_count(int[] a, int k) {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"inversion_count(self, arr, k)"
],
"initial_code": "if __name__ == '__main__':\n t = int(input())\n for _ in range(0, t):\n a = list(map(int, input().split()))\n k = int(input())\n ob = Solution()\n ans = ob.inversion_count(a, k)\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n def inversion_count(self, arr, k):\n n = len(arr)\n count = 0\n # Iterate over all possible subarrays of length k\n for start in range(n - k + 1):\n sub_array = arr[start:start + k]\n count += self.subarray_inversion_count(sub_array)\n return count\n\n # Merge function that counts the number of inversions during the merge process\n def merge_inversion_count(self, arr, left, right):\n i = j = count = 0\n while i < len(left) or j < len(right):\n if i == len(left):\n arr[i + j] = right[j]\n j += 1\n elif j == len(right):\n arr[i + j] = left[i]\n i += 1\n elif left[i] <= right[j]:\n arr[i + j] = left[i]\n i += 1\n else:\n arr[i + j] = right[j]\n count += len(left) - i # Count the number of inversions\n j += 1\n return count\n\n # Recursive function to count inversions in the subarray using divide and conquer\n def subarray_inversion_count(self, arr):\n if len(arr) < 2:\n return 0\n\n m = (len(arr) + 1) // 2\n left = arr[:m]\n right = arr[m:]\n\n return (self.subarray_inversion_count(left) +\n self.subarray_inversion_count(right) +\n self.merge_inversion_count(arr, left, right))\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution:\n def inversion_count(self, arr, k):\n # Your code goes here"
}
|
eJy1VUFu3DAM7KGHPoPweRGIFCVReUmAuuih3UMuzh42QIEiQR7RPiG3PrIjGRsgBzp2drPA0DZWpkYzJP30+e+/L5/67+YZN19/D7fT4f44XNPA48QhkAAR4IR7IAKKZ8U1hYZxSuM07GjY/zrsfxz3P7/f3R9PSWScHvHvw45ep661Uq0GFCADCVAgAgIwEBoHN7kmJ7lSJKFETIWMkJxaluizDE4ixotNA2p0YyesnXLqpGfapRO3mXojP07Z3apmb6uAlw3JMpLPB2Ba1LZ4rJst3M2RHmOPOtvVY+6x9Gg91h55WXBWVyiJqIhMxZrWkI1BPzIpw4UMH9iIYatgnShoSSYpQibQNcSlY0ZzFWu819URVRCrhnWGdYZ1hnWm41TcjSWyt3MCaTojLlVI8apaqFUZZ4pCWYnF0JBwskkdRNGpivIMEMGa1JyjoY6kZLRAShE7mrup66tflXOhba3N2S+4Y71XXpp8zoZDJi+ll1GaCB+nTNmozCUY6UxprJdy3e+u9ZNPzh59roOk68+YebV19X2Dg06To54zPIJuHR75EtPDvJkl20uyrO8S96u29gP6ZvWU08G+/bn6D/gJMcA=
|
706,303
|
Find all Critical Connections in the Graph
|
A critical connection refers to an edge that, upon removal, will make it impossible for certain nodes to reach each other through any path. You are given an undirected connected graph with v vertices and e edges and each vertex distinct and ranges from 0 to v-1, and you have to find all critical connections in the graph. It is ensured that there is at least one such edge present.
Examples:
Input:
Output:
0 1
0 2
Explanation:
On removing edge (0, 1), you will not be able to
reach node 0 and 2 from node 1. Also, on removing
edge (0, 2), you will not be able to reach node 0
and 1 from node 2.
Input:
Output:
2 3
Explanation:
The edge between nodes 2 and 3 is the only
Critical connection in the given graph.
Constraints:
1 ≤ v, e ≤ 10**4
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1616310748,
"func_sign": [
"public ArrayList<ArrayList<Integer>> criticalConnections(int v, ArrayList<ArrayList<Integer>> adj)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String[] s = br.readLine().trim().split(\" \");\n int V = Integer.parseInt(s[0]);\n int E = Integer.parseInt(s[1]);\n ArrayList<ArrayList<Integer>>adj = new ArrayList<>();\n for(int i = 0; i < V; i++)\n adj.add(i, new ArrayList<Integer>());\n for(int i = 0; i < E; i++){\n String[] S = br.readLine().trim().split(\" \");\n int u = Integer.parseInt(S[0]);\n int v = Integer.parseInt(S[1]);\n adj.get(u).add(v);\n adj.get(v).add(u);\n }\n Solution obj = new Solution();\n ArrayList<ArrayList<Integer>> ans = obj.criticalConnections(V, adj);\n for(int i=0;i<ans.size();i++)\n System.out.println(ans.get(i).get(0) + \" \" + ans.get(i).get(1));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n int time = 0; // Initialize a variable to keep track of time\n\n public ArrayList<ArrayList<Integer>> criticalConnections(\n int v, ArrayList<ArrayList<Integer>> adj) {\n int[] id =\n new int[v]; // Initialize an array to store discovery times of vertices\n boolean[] visited =\n new boolean[v]; // Initialize an array to keep track of visited vertices\n int[] low = new int[v]; // Initialize an array to store the lowest discovery\n // time reachable from a vertex\n ArrayList<ArrayList<Integer>> out =\n new ArrayList<>(); // Initialize a list to store critical connections\n\n // Loop through all vertices\n for (int i = 0; i < v; i++) {\n if (!visited[i]) {\n // Perform Depth First Search (DFS) on unvisited vertices\n DFSUtil(i, -1, adj, visited, id, low, out);\n }\n }\n\n // Sort the list of critical connections\n Collections.sort(out, new Comparator<ArrayList<Integer>>() {\n @Override\n public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {\n return (o1.get(0) - o2.get(0) == 0) ? o1.get(1) - o2.get(1)\n : o1.get(0) - o2.get(0);\n }\n });\n\n return out; // Return the list of critical connections\n }\n\n // Depth First Search utility function\n private void DFSUtil(int u, int parent, ArrayList<ArrayList<Integer>> adj,\n boolean[] visited, int[] id, int[] low,\n ArrayList<ArrayList<Integer>> out) {\n visited[u] = true; // Mark the current vertex as visited\n id[u] = low[u] = ++time; // Initialize discovery time and lowest reachable time\n // for the current vertex\n Iterator<Integer> it =\n adj.get(u).iterator(); // Initialize an iterator for the adjacency list of\n // the current vertex\n\n // Iterate through the adjacency list of the current vertex\n while (it.hasNext()) {\n int v = it.next(); // Get the next adjacent vertex\n if (v == parent) continue; // Skip if the adjacent vertex is the parent\n\n if (!visited[v]) {\n // If the adjacent vertex is not visited, perform DFS recursively\n DFSUtil(v, u, adj, visited, id, low, out);\n low[u] = Math.min(\n low[v],\n low[u]); // Update the lowest reachable time for the current vertex\n\n // Check if the edge is a critical connection\n if (low[v] > id[u]) {\n ArrayList<Integer> edge =\n new ArrayList<Integer>(); // Create a new array list to store\n // the edge\n edge.add(u < v ? u : v); // Add the smaller vertex to the edge\n edge.add(u < v ? v : u); // Add the larger vertex to the edge\n out.add(edge); // Add the edge to the list of critical connections\n }\n } else {\n // If the adjacent vertex is visited, update the lowest reachable time\n // for the current vertex\n low[u] = Math.min(id[v], low[u]);\n }\n }\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public ArrayList<ArrayList<Integer>> criticalConnections(int v, ArrayList<ArrayList<Integer>> adj)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616310748,
"func_sign": [
"criticalConnections(self, v, adj)"
],
"initial_code": "# Initial Template for Python 3\n\nimport sys\nsys.setrecursionlimit(10**6)\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n V, E = map(int, input().split())\n adj = [[] for i in range(V)]\n for _ in range(E):\n u, v = map(int, input().split())\n adj[u].append(v)\n adj[v].append(u)\n obj = Solution()\n ans = obj.criticalConnections(V, adj)\n for i in range(len(ans)):\n print(ans[i][0], ans[i][1])\n",
"solution": "class Solution:\n def criticalConnections(self, v, adj):\n # Function to find critical connections in a graph\n\n def Articulation_Point(u):\n # Function to find Articulation Point and critical connections\n\n low[u] = time[0]\n disc[u] = time[0]\n time[0] += 1\n visited[u] = True\n\n for v in adj[u]:\n if visited[v] == False:\n parent[v] = u\n Articulation_Point(v)\n\n low[u] = min(low[u], low[v])\n\n if low[v] > disc[u]:\n ans.append(sorted([u, v]))\n\n elif parent[u] != v:\n low[u] = min(low[u], disc[v])\n\n ans = []\n\n # Initializing low, disc, parent, time, and visited arrays\n low = [sys.maxsize for i in range(v)]\n disc = [sys.maxsize for i in range(v)]\n parent = [-1 for i in range(v)]\n time = [0]\n visited = [False for i in range(v)]\n\n # Calling Articulation_Point function for each unvisited vertex\n for i in range(v):\n if visited[i] == False:\n Articulation_Point(i)\n\n return sorted(ans)\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\n\nclass Solution:\n def criticalConnections(self, v, adj):\n # code here"
}
|
eJy9VbFOwzAQZWBhZmM6ea5Qzo7thC9BwogBMrCYDqlUCSHxEfC/9F1MRaU2jVOXDKfEl3vP9+45+bz8vrm6kOv+enPz8K5e43LVqztSHKIlF2JFjKBD5CGYEA3VIWoEtSDVrZfdc9+9PL2t+lSsPha0i+XIJyyB0VuYmizWLLI2A7ChdgRQti6cniokcqB5A2v/dl4BnIemLdAcaDxoGtC0oGnSnjyCNKTxnsmSCdR6V/SDff0SSusyDYvHA1xSPt7rMSGbreptmhYjq5E1yNYj/HuoNXGdSd0SV8OmRSCWUtEA61ky85yuGY+TabzsapylGiS0yWDirSwJXQkJsaSRTXP0qfYk49J5nTvFn8dHjaoMGwv2PtJTJaFSp3m+r0UvPXnkE34PJgev9EDPMc/54hbXdcYHd47A9j8VLuUAV+pMP37d/gB9nI/z
|
701,275
|
Distance of nearest cell having 1
|
Given a binary grid of n*m. Find the distance of the nearest 1 in the gridfor each cell.The distance is calculated as|i1 - i2| + |j1- j2|, where i1, j1are the row number and column number of the current cell, and i2, j2are the row number and column number of the nearest cell having value 1.There should be atleast one 1 in the grid.
Examples:
Input:
grid = {{0,1,1,0},{1,1,0,0},{0,0,1,1}}
Output:
{{1,0,0,1},{0,0,1,1},{1,1,0,0}}
Explanation:
The grid is-
0 1 1 0
1 1 0 0
0 0 1 1
- 0's at (0,0), (0,3), (1,2), (1,3), (2,0) and (2,1) are at a distance of 1 from 1's at (0,1), (0,2), (0,2), (2,3), (1,0) and (1,1) respectively.
Input:
grid = {{1,0,1},{1,1,0},{1,0,0}}
Output:
{{0,1,0},{0,0,1},{0,1,2}}
Explanation:
The grid is-
1 0 1
1 1 0
1 0 0
- 0's at (0,1), (1,2), (2,1) and (2,2) are at a distance of 1, 1, 1 and 2 from 1's at (0,0), (0,2), (2,0) and (1,1) respectively.
Constraints:
1 ≤ n, m ≤ 500
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int[][] nearest(int[][] grid)"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String[] s = br.readLine().trim().split(\" \");\n int n = Integer.parseInt(s[0]);\n int m = Integer.parseInt(s[1]);\n int[][] grid = new int[n][m];\n for(int i = 0; i < n; i++){\n String[] S = br.readLine().trim().split(\" \");\n for(int j = 0; j < m; j++){\n grid[i][j] = Integer.parseInt(S[j]);\n }\n }\n Solution obj = new Solution();\n int[][] ans = obj.nearest(grid);\n for(int i = 0; i < ans.length; i++){\n for(int j = 0; j < ans[i].length; j++){\n System.out.print(ans[i][j] + \" \");\n }\n System.out.println();\n }\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end Complete function Template for JAVA\n\nclass Solution\n{\n int[] dx = {1, -1, 0, 0};\n int[] dy = {0, 0, 1, -1};\n \n //Function to check whether the cell is within the matrix bounds.\n boolean isValid(int x, int y, int n, int m)\n {\n\t\tif (x>=0 && x<n && y>=0 && y<m)\n\t\t return true;\n\t\treturn false;\n\t}\n\t\n\t//Function to find distance of nearest 1 in the grid for each cell.\n public int[][] nearest(int[][] grid)\n {\n int n = grid.length;\n int m = grid[0].length;\n \n //using dp list which will store the output.\n int[][] dp = new int[n][m];\n \n for(int i=0; i<n; i++)\n for(int j=0; j<m; j++)\n dp[i][j] = 10000000;\n \n //queue to store the cell indexes which have grid value 1.\n Queue<ArrayList<Integer>> q = new LinkedList<>(); \n \n \n //traversing all the cells of the matrix.\n for(int i = 0; i < n; i++)\n {\n\t\t\tfor(int j = 0; j < m; j++)\n\t\t\t{\n\t\t\t //if grid value is 1, we update the dp value at same cell as 0 \n\t\t\t //and push the cell indexes into queue.\n\t\t\t\tif(grid[i][j] == 1){\n\t\t\t\t\tdp[i][j] = 0;\n\t\t\t\t\tArrayList<Integer> temp = new ArrayList<>();\n\t\t\t\t\ttemp.add(i);\n\t\t\t\t\ttemp.add(j);\n\t\t\t\t\tq.add(temp);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\twhile(!q.isEmpty())\n\t\t{\n\t\t //storing the cell indexes at top of queue and popping them.\n\t\t\tArrayList <Integer> curr = q.poll();\n\t\t\tint x = curr.get(0);\n\t\t\tint y = curr.get(1);\n\t\t\t\n\t\t\t//iterating over the adjacent cells.\n\t\t\tfor(int i = 0; i < 4; i++)\n\t\t\t{\n\t\t\t\tint n_x = x + dx[i];\n\t\t\t\tint n_y = y + dy[i];\n\t\t\t\t\n\t\t\t\tif(isValid(n_x, n_y, n, m) && dp[n_x][n_y] > dp[x][y] + 1)\n\t\t\t\t{\n\t\t\t\t //updating dp and pushing cell indexes in queue.\n\t\t\t\t\tdp[n_x][n_y] = dp[x][y] + 1;\n\t\t\t\t\tArrayList<Integer> temp = new ArrayList<>();\n\t\t\t\t\ttemp.add(n_x);\n\t\t\t\t\ttemp.add(n_y);\n\t\t\t\t\tq.add(temp);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//returning the dp list.\n\t\treturn dp;\n }\n}",
"updated_at_timestamp": 1730268154,
"user_code": "class Solution\n{\n //Function to find distance of nearest 1 in the grid for each cell.\n public int[][] nearest(int[][] grid)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"nearest(self, grid)"
],
"initial_code": "if __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n, m = map(int, input().split())\n grid = []\n for _ in range(n):\n a = list(map(int, input().split()))\n grid.append(a)\n obj = Solution()\n ans = obj.nearest(grid)\n for i in ans:\n for j in i:\n print(j, end=\" \")\n print()\n",
"solution": "from collections import deque\n\n\nclass Solution:\n\n # Function to check whether the cell is within the matrix bounds.\n def isValid(self, x, y, n, m):\n return (x >= 0 and x < n and y >= 0 and y < m)\n\n # Function to find distance of nearest 1 in the grid for each cell.\n def nearest(self, grid):\n dx = [-1, 1, 0, 0]\n dy = [0, 0, -1, 1]\n n = len(grid)\n m = len(grid[0])\n\n # Using dp list which will store the output.\n dp = [[100000 for _ in range(m)] for _ in range(n)]\n\n # Queue to store the cell indexes which have grid value 1.\n q = deque()\n\n # Traversing all the cells of the matrix.\n for i in range(n):\n for j in range(m):\n # If grid value is 1, we update the dp value at same cell as 0\n # and push the cell indexes into queue.\n if grid[i][j] == 1:\n dp[i][j] = 0\n q.append([i, j])\n\n while len(q):\n # Storing the cell indexes at top of queue and popping them.\n cur = q.popleft()\n x, y = cur\n\n # Iterating over the adjacent cells.\n for i in range(4):\n n_x, n_y = x + dx[i], y + dy[i]\n if self.isValid(n_x, n_y, n, m) and dp[n_x][n_y] > dp[x][y] + 1:\n # Updating dp and pushing cell indexes in queue.\n dp[n_x][n_y] = dp[x][y] + 1\n q.append([n_x, n_y])\n\n # Returning the dp list.\n return dp\n",
"updated_at_timestamp": 1730268154,
"user_code": "class Solution:\n\n #Function to find distance of nearest 1 in the grid for each cell.\n\tdef nearest(self, grid):\n\t\t#Code here"
}
|
eJztV81OwzAM5sAD8AhWzxOK1x9WngSJIg6wA5eywyYhISQeAi7ceFPiOF2dv6bSLhtae3G/fk1s57OTfl5+/15dmOvuRxv378VLv9lti1soVLGAYv22WT9t18+Pr7utxYuPBQgadn0Nddcr4BsHE0GxifRIJjKl660BqSkqKGFp6F0/WKjtwVoCj0FWCTw0WZW2Q/caaMSUo4PCReGkcHNvOj4nvWYvBr9Hmz2Xvo926URSObHU0WhQE9QYgorFFYlPQD4o4vUgCYr4nZy5oAN5OYzmMpPTFlZwA43OhdREiFGOQ4xyHWKU8xCj3IdY7ShwwBpvDRm78daSsZW3poy18bWtAetozsLkn1+fyGtMSDsmlRaovBFQq6u0IptiGFKZo+DSanuag2gLI0NCZcsqx2ptUeZYK1vSORYVWDuDReVpHnI0qm5GMjRqDhaeZJl2XmZJZv+qchwcWWmKijcS2g1Swpv4JNWGUdEVfqdg9iFB74Cms5keOVES3P5iHtoReFNJjGCzlkiL9IHOLRk3YgGn0+oz55+fpFvU/g9KDwd33kz+5+sZqo2rgzVB8k3uR4kaDwWaazDzdcqDnbzczbH84BmOV3WnqfjIj9J+yGCW85/SUf8pPXxd/wGk+35k
|
703,459
|
First and Last Occurrences
|
Given a sorted array arr containing n elements with possibly some duplicate, the task is to find the first and last occurrences of an element x in the given array.Note:If the numberx is not found in the array then return both the indices as -1.
Examples:
Input:
n=9, x=5
arr[] = { 1, 3, 5, 5, 5, 5, 67, 123, 125 }
Output:
2 5
Explanation:
First occurrence of 5 is at index 2 and last occurrence of 5 is at index 5.
Input:
n=9, x=7
arr[] = { 1, 3, 5, 5, 5, 5, 7, 123, 125 }
Output:
6 6
Explanation:
First and last occurrence of 7 is at index 6.
Constraints:
1 ≤ N ≤ 10**6
1 ≤ arr[i],x ≤ 10**9
|
geeksforgeeks
|
Medium
|
{
"class_name": "GFG",
"created_at_timestamp": 1729172286,
"func_sign": [
"ArrayList<Integer> find(int arr[], int x)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\n// Driver class\nclass Array {\n\n // Driver code\n public static void main(String[] args) throws IOException {\n // Taking input using buffered reader\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n int testcases = Integer.parseInt(br.readLine());\n // looping through all testcases\n while (testcases-- > 0) {\n\n String line1 = br.readLine();\n String[] a1 = line1.trim().split(\"\\\\s+\");\n int n = a1.length;\n int arr[] = new int[n];\n for (int i = 0; i < n; i++) {\n arr[i] = Integer.parseInt(a1[i]);\n }\n int x = Integer.parseInt(br.readLine());\n GFG ob = new GFG();\n ArrayList<Integer> ans = ob.find(arr, x);\n System.out.println(ans.get(0) + \" \" + ans.get(1));\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Array",
"solution": "None",
"updated_at_timestamp": 1730471043,
"user_code": "// User function Template for Java\n\nclass GFG {\n ArrayList<Integer> find(int arr[], int x) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1729172286,
"func_sign": [
"find(self, arr, x)"
],
"initial_code": "t = int(input()) # Number of test cases\nfor _ in range(t):\n arr = list(map(int, input().split())) # Input array for each test case\n x = int(input()) # Element to search for\n ob = Solution()\n ans = ob.find(arr, x) # Call the find function in the Solution class\n print(*ans) # Print the result as space-separated values\n print() # Empty line for readability\n # Removed the tilde (~) print statement, as it's not clear what it's meant to represent\n",
"solution": "class Solution:\n\n def find(self, arr, x):\n n = len(arr) # Length of the array\n ans = [-1, -1] # Initialize answer as [-1, -1] if x is not found\n\n # Find the first occurrence of x\n left, right = 0, n - 1\n while left <= right:\n mid = left + (right - left) // 2\n if arr[mid] == x:\n ans[0] = mid # Store the index of the first occurrence\n right = mid - 1 # Move left to find any earlier occurrence\n elif arr[mid] < x:\n left = mid + 1 # Move right as x would be in the right half\n else:\n right = mid - 1 # Move left as x would be in the left half\n\n # Find the last occurrence of x\n left, right = 0, n - 1\n while left <= right:\n mid = left + (right - left) // 2\n if arr[mid] == x:\n ans[1] = mid # Store the index of the last occurrence\n left = mid + 1 # Move right to find any later occurrence\n elif arr[mid] < x:\n left = mid + 1 # Move right as x would be in the right half\n else:\n right = mid - 1 # Move left as x would be in the left half\n\n return ans # Return the indices of the first and last occurrences\n",
"updated_at_timestamp": 1730471043,
"user_code": "#User function Template for python3\nclass Solution:\n def find(self, arr, x):\n \n # code here"
}
|
eJy1VstOw0AM5MCFvxjlXCF7d/PiS5AI4gA9cAkVaqUihMRHwP8ymwJKIN6mKdRdqVId22PPePN6+v50dtJ9Lh/54+o5u29Xm3V2gUybVuHgEZAnrUCJCjVUoAp1UA8N0BxaQEtoBa3hpGnzbIFsuV0tb9fLu5uHzfozFZ2rpm3a7GWBYQUOKfOGhV82qLhpvVEIa3bFeCVE5wS+9w2CXFAISkElqAlfYgt46Km+d+iq9FU6K72V7lrHgDwxMP2d7x36u5wN82IU6iKK0TJxnDmGMHIStFq9idj5uHD4wukLJyp54pAYQmYIqSF17FkMYtGDD1iJoT0ahAQZw5CSZZ+YnAFHwM6z8YxZWj133f/jdaQlst80IQ+Fd1MaP/d8DywGdCbj1FJGUqPjWh2OKiFIzsdg+hTxD9dU0aUsu7RVl5rWtMHKTcjl3L5P6KcVewKnqxSpZ1J4t7uOwhRMTCPBp7TIH7CLg/zHNj5mE+8uTyc/lD7xUtzthBlXUcSbgn/wbTQTPzc7UySEMk0m5sr9y3eTGNAehcCcxKho9qLyX6iu384/ABFoNG8=
|
703,751
|
Gray Code
|
You are given a decimal number n. You need to find the gray code of the number n and convertit into decimal.
Examples:
Input:
n =
7
Output:
4
Explanation:
7 is represented as 111 in binary form.
The gray code of 111 is 100, in the binary
form whose decimal equivalent is 4.
Input:
n =
10
Output:
15
Explanation:
10 is represented as 1010 in binary form.
The gray code of 1010 is 1111, in thebinary
form whose decimal equivalent is 15
.
Constraints:
0 <= n <= 10**8
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int getGray(int n)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int n = Integer.parseInt(read.readLine());\n\n Solution ob = new Solution();\n System.out.println(ob.getGray(n));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static int getGray(int n) {\n int q = n >> 1; // Left shift n and store the output in q.\n int ans = n ^ q; // xor of n and q.\n return ans;\n }\n}\n;\n",
"updated_at_timestamp": 1730473085,
"user_code": "class Solution {\n static int getGray(int n) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"getGray(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\n ob = Solution()\n print(ob.getGray(n))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def getGray(self, n):\n q = n >> 1 # Left shift n and store the output in q.\n ans = n ^ q # xor of n and q.\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def getGray(self, n):\n # code here "
}
|
eJydk8EKAiEURVvMhwyuh8inI0NfEmS0KBdtbBYKQVP0EfW/OVpB0LXMjeLj4L33PS/VbagmcS18OCyPbGd779i8ZlzbmbasqZk59GbjzHa99+5RDJVzKJ6a+p3gkOCAIEgIQAhIECAkJBQgOuwDPcJbyHQIUdiKRO4zESM3AocskTaRuklpK3+TUoq4u2ggUr+K54irXJjtd5da/+VzzDbfykzE/Gn2NxGk4PSF+zHu4r8U1ev016OJz7qiMF1skLCiF7S6Tu+SzXFS
|
703,433
|
Sort the pile of cards
|
Given a shuffled array arr[] where each element represents a card numbered from 1 to n, your task is to determine the minimum number of operations required to sort the array in increasing order. In each operation, called moveCard(x), you can move the card with value x (where 1 ≤ x ≤ n) to the top of the array, without altering the order of the other cards. Your goal is to sort the array with the fewest possible moveCard(x) operations.
Examples:
Input:
arr[] = [5, 1, 2, 3, 4]
Output:
4
Explanation:
5 1 2 3 4 //given sequence
4 5 1 2 3 //moveCard(4)
3 4 5 1 2 //moveCard(3)
2 3 4 5 1 //moveCard(2)
1 2 3 4 5 //moveCard(1)
Hence, minimum 4 operations are required.
Input:
arr[] = [3, 4, 2, 1]
Output:
2
Explanation:
3 4 2 1 //given sequence
2 3 4 1 //moveCard(2)
1 2 3 4 //moveCard(1)
Hence, minimum 2 operations are required.
Constraints:
1 <= arr.size() <=10**6
1 <= arr[i] <= arr.size()
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int minOps(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.minOps(arr);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n public int minOps(int arr[]) {\n int n = arr.length; // Get the size of the array\n int check = n; // Variable to keep track of the expected value (starts from n)\n int count = 0; // Variable to count the number of matched elements\n // Loop through the array from right to left\n for (int i = n - 1; i >= 0; i--) {\n if (arr[i] == check) {\n count++; // Increment the count if the current element matches the\n // expected value\n check--; // Decrement the expected value\n }\n }\n // Return the minimum number of operations needed\n return (n - count); // Total elements minus the matched elements gives the min\n // operations\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n public int minOps(int arr[]) {}\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"minOps(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 res = ob.minOps(arr)\n print(res)\n t -= 1\n print(\"~\")\n",
"solution": "class Solution:\n def minOps(self, arr):\n n = len(arr) # Get the size of the array\n # Variable to keep track of the expected value (starts from n)\n check = n\n count = 0 # Variable to count the number of matched elements\n\n # Loop through the array from right to left\n for i in range(n - 1, -1, -1):\n if arr[i] == check:\n count += 1 # Increment the count if the current element matches the expected value\n check -= 1 # Decrement the expected value\n\n # Return the minimum number of operations needed\n return n - count # Total elements minus the matched elements gives the min operations\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def minOps(self, arr):\n \n\n \n"
}
|
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
|
702,990
|
Odd to Even
|
Given an odd number in the form of string, the task is to make largest even number possible from the given number provided one is allowed to do exactly only one swap operation, if no such number is possible then return the input string itself.
Examples:
Input:
s = 4543
Output:
4534
Explanation:
Swap 4(3rd pos) and 3.
Input:
s = 1539
Output:
1539
Explanation:
No even no. present.
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public String makeEven(String s)"
],
"initial_code": "import 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 String str = sc.next();\n Solution obj = new Solution();\n System.out.println(obj.makeEven(str));\n }\n \n }\n}\n",
"script_name": "GfG",
"solution": "None",
"updated_at_timestamp": 1730469672,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public String makeEven(String s)\n {\n //code here.\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"makeEven(self, s)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n\n for tcs in range(T):\n Str = input()\n ob = Solution()\n print(ob.makeEven(Str))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n\n # Function to make string even.\n def makeEven(self, Str):\n\n n = len(Str)\n mei = -1\n\n # iterating over the string to find the first even number\n # that is less than the last number in the string.\n for i, e in enumerate(Str):\n if int(e) % 2 == 0 and int(e) < int(Str[-1]):\n mei = i\n break\n elif int(e) % 2 == 0:\n mei = i\n\n # if no even number is found, return the original string as it is.\n if mei == -1:\n return Str\n\n # rearranging the string to make it even.\n ans = Str[:mei] + Str[-1] + Str[mei+1:n-1]+Str[mei]\n return ans\n",
"updated_at_timestamp": 1730469672,
"user_code": "#User function Template for python3\n\nclass Solution:\n def makeEven(self, s):\n # code here"
}
|
eJyNVLEOgjAQddDJzS8gnYnh2tIWv8REjIMyuFQGSEyMxo/Q/xVKITg86E0k797x7t1d38vvZrVwsV83H4cHu9qyrtguYpTbzGiVSkEsjlhxL4tzVVxOt7ryGQ4mIXP7yi17xtE/m0tlSKQ6Q3SPc8B33LYI4DvcSAX5CRcyVdogAZT5hARU6NrnlIACA44KCEAUyLImAKWFUKdZL2RqUM0cEV/7APQeRj7P2tzh6O8C9ixwyzpQMxLdWTLjGDTMtzwxYZdBWk0MOgnYsDaP0HY5kXP3OXGgerw6jVUWu0mwj5BD43jzaGzCIMdpmX+AHDvI3/FzEuT18bP9AbVWfdg=
|
703,776
|
if-else (Decision Making)
|
Given two integers, nand m. The task is to check the relation between n and m.
Examples:
Input:
n = 4, m = 8
Output:
lesser
Explanation:
4 < 8 so print '
lesser
'.
Input:
n = 8, m = 8
Output:
equal
Explanation:
8 = 8 so print '
equal
'.
Constraints:
-10**9
<= m , n <= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1708935411,
"func_sign": [
"public static String compareNM(int n, int m)"
],
"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 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 m;\n m = Integer.parseInt(br.readLine());\n \n Solution obj = new Solution();\n String res = obj.compareNM(n, m);\n \n System.out.println(res);\n \n \nSystem.out.println(\"~\");\n}\n }\n}\n\n//Position this line where user code will be pasted.\n",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\nclass Solution {\n public static String compareNM(int n, int m) {\n //If n is lesser than m, return \"lesser\"\n if(n<m)\n return \"lesser\";\n //If n is greater than m, return \"greater\"\n else if(n>m)\n return \"greater\";\n //If n is equal to m, return \"equal\"\n else\n return \"equal\";\n \n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution {\n public static String compareNM(int n, int m) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1708935411,
"func_sign": [
"compareNM(self, n : int, m : int) -> str"
],
"initial_code": "if __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n n = int(input())\n m = int(input())\n obj = Solution()\n res = obj.compareNM(n, m)\n print(res)\n print(\"~\")\n",
"solution": "class Solution:\n # Function to compare two numbers\n def compareNM(self, n: int, m: int) -> str:\n # If n is less than m\n if n < m:\n return \"lesser\"\n # If n is equal to m\n elif n == m:\n return \"equal\"\n # If n is greater than m\n else:\n return \"greater\"\n",
"updated_at_timestamp": 1729753320,
"user_code": "\nclass Solution:\n def compareNM(self, n : int, m : int) -> str:\n # code here\n \n"
}
|
eJxrYJm6hI0BDCLmAhnR1UqZeQWlJUpWCkqGMXmGBjAQk6eL4CjpKCilVhSkJpekpsTnl5ZANaQXpSaWpBbF5NXF5CnV6iigmqWLbBhBs3JSi4txG2UJA8hsHCalFpYm5uAwiCQn4TMIxXMEnYTXc8gmETIIf4gDDSDHL8iBS3GcgzDF4Un1qCEnXrAGC1mhYmmJM5ThTEuyMoYl2GhIqEMMpo0DifYE2T7BEmvQFE1G7BGZwUkPCEsc6YsyL+O0GHcpiiXgKQ82FDdZ4g0NNMsJRCB5boudogcAkwDypQ==
|
709,857
|
Maximum number of events that can be attended
|
There are N events inGeek's city. You are given two arrays start[] and end[] denoting starting and ending day of the events respectively. Event i starts at start[i] and ends at end[i].
You can attend an event i at any day d between start[i] and end[i] (start[i] ≤ d ≤ end[i]). But you can attend only one event in a day.
Find the maximum number of events you can attend.
Examples:
Input:
N = 3
start[] = {1, 2, 1}
end[] = {1, 2, 2}
Output:
2
Explanation:
You can attend a maximum of two events.
You can attend 2 events by attending 1st event
at Day 1 and 2nd event at Day 2.
Input:
N = 3
start[i] = {1, 2, 3}
end[i] = {2, 3, 4}
Output:
3
Explanation:
You can attend all events by attending event 1
at Day 1, event 2 at Day 2, and event 3 at Day 3.
Constraints:
1 ≤ N ≤ 10**5
1 ≤ start[i]≤ end[i] ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1644383491,
"func_sign": [
"static int maxEvents(int[] start, int[] end, int N)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int N = Integer.parseInt(read.readLine());\n \n String S1[] = read.readLine().split(\" \");\n String S2[] = read.readLine().split(\" \");\n int[] start = new int[N];\n int[] end = new int[N];\n \n for(int i=0; i<N; i++)\n {\n start[i] = Integer.parseInt(S1[i]);\n end[i] = Integer.parseInt(S2[i]);\n }\n\n Solution ob = new Solution();\n System.out.println(ob.maxEvents(start,end,N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end function Template for Java\nclass Solution {\n static int maxEvents(int[] start, int[] end, int N) {\n // Create a 2D array to store start and end times of events\n int[][] A = new int[N][2];\n // Copy the start and end times from the input arrays to the 2D array\n for (int i = 0; i < N; i++) {\n A[i][0] = start[i];\n A[i][1] = end[i];\n }\n // Create a priority queue to store the end times of events in ascending order\n PriorityQueue<Integer> pq = new PriorityQueue<Integer>();\n // Sort the 2D array based on the start times of events\n Arrays.sort(A, (a, b) -> Integer.compare(a[0], b[0]));\n int i = 0, res = 0, d = 0;\n while (!pq.isEmpty() || i < N) {\n // If the priority queue is empty, set the current day equal to the start time of the next\n // event\n if (pq.isEmpty()) d = A[i][0];\n // Add the end times of all events that start on or before the current day to the priority\n // queue\n while (i < N && A[i][0] <= d) pq.offer(A[i++][1]);\n // Remove the smallest end time from the priority queue\n pq.poll();\n // Increment the number of attended events\n ++res;\n ++d;\n // Remove all past events from the priority queue\n while (!pq.isEmpty() && pq.peek() < d) pq.poll();\n }\n // Return the total number of attended events\n return res;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int maxEvents(int[] start, int[] end, int N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1644383491,
"func_sign": [
"maxEvents(self, start, end, 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 start = list(map(int, input().split()))\n end = list(map(int, input().split()))\n\n ob = Solution()\n print(ob.maxEvents(start, end, N))\n print(\"~\")\n",
"solution": "# Back-end function Template for python3\n\nimport heapq\n\n\nclass Solution:\n def maxEvents(self, start, end, N):\n A = []\n for i in range(N):\n A.append([start[i], end[i]])\n\n # sorting the events in reverse order based on the start time\n A.sort(reverse=True)\n\n h = []\n res = d = 0\n\n # iterating through the events or the heap until both are empty\n while A or h:\n # if the heap is empty, set d as the start time of the next event\n if not h:\n d = A[-1][0]\n\n # pushing the end time of all ongoing events into the heap\n while A and A[-1][0] <= d:\n heapq.heappush(h, A.pop()[1])\n\n # removing the earliest ending event from the heap\n heapq.heappop(h)\n\n # incrementing the result count\n res += 1\n\n # incrementing the day\n d += 1\n\n # removing events from the heap that have already ended\n while h and h[0] < d:\n heapq.heappop(h)\n\n # returning the total number of attended events\n return res\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def maxEvents(self, start, end, N):\n # code here "
}
|
eJztl09uJkUMxVlwAk5gZT1CtstdfzgJEkEsIAs2YRYZCQmBOATcix3X4T2XiYiSDpNMiFjMfJH6m1Z/7ld+/rlcv376+5+ffZL/vvwDX7766eL767fvbi6+kAu7vD4ur01cGj742iTkkC7j4o1cXP349urbm6vvvvnh3U39AI/8cnl98fMbuRtl7CiBn04xFfPLa0ekIUvMxJpYnIQcJyFNIU6OlNMz7mIw3B34PvP/fNPtnz/1Bbn0dlflITbEljiW08QP8SG+uJh/rA2LEetiU1zFXTzEu/iUpica7Cxxrlwp4+DVeF1TaYeESmDlKgdWr9IhUWUcMlXmIUtlQady2VyDUwNkQ2qDk0MCaoccMGBId+lDhstA2lwm1uqysEbFb/TMZ8p6UO+x9VKsPksvEo0r88w1I4IhhCGGIYghih0MjysCWacfuCKWIZghmiGcLb6facOV6aOe9AJXxHPEc8TzYFIplHkymkZjuzQY3yVMosthcqDATDrq3mTAZpPZZZksmKz4meLKn9N0BDBEsMaCwRVBDFEMYQxxrPM1uCKUDRYJrohmCGeI54jnSh24Ug8FsXoaKw5XxHPEc8Tzo59xeOYPsvzeVZ1ZaPQPNdNWpqPRSBRPrMxLo6OoomNlghqtRTn1lZlq9Bh1NVamrNFsFNhcmbtG11Fpa1US2/ZfWXyrEtp2LVAe9O3ktl0X0GgQuRPddo1AqEHpTnrb9QK1BrnbgLZrB5INmrcZbdcRdBuEb2ParimIN6jfJrVdX1iBYQnbsJa1ZgRmPaENJIjBGmsz6cAPg8UWMzEBmsGqO2byAkaD5ddnggNYg3U4ZhIEaoMFOWeiBHyDlblmMUWQYxepzuIL96iO8qBvs4Z7kJjFC5GbO9yDzixkKN0McmGxixpyN4+4B8VZ4NC82cS9HrvYIXxzykYUu/ChfjOLe1hAQoAlbH5xD6sgELaYv9PGqWeV7rvSuXXVnnW7JVia09KfIy2ipQmAJgOeGESS0BOGmTxoIuFJRSQYPdmYiYcmIZ6QRHLSE5WZtGgC48lMJDY9yZkJjyY/nghFUtQTpJksaeLkSVQkVD25momWJl2egEUy1hOzmaRpwubJWyRyPambGzwt+LwAjIKwF4izYNQC0gvKKDB7wTkLUC1IvUCNgrUXsLOg1QLXC94ogHtBPAtkLZi9gI6CuhfYs+DWAtwL8ijQe8E+C3gt6L3Aj4K/VwOY1QS0GoFXM4hqCL2awqzGoNUcvBpEVJPo1ShmNQuthuHVNKIaR6/mwfJj/eX++dGU/5kptS2jL8APhx85WXCbhh+u7FCrJg1u23gOfjj8yMkjxwo8x52ATSa3A7YZTmZ4jp2GrYa9hs2G3QZ+7EmFWzL7EZ6DHzm5cAyAHw4/HH7sSYZjAfcYNq7Ykw3HBPjh8MPhx550ODbguYP7PDscJyCOE3gOfjj8cPjhnXMQnoMf3rlxsRXiOfjh8MPhh8MPhx8OPxx+OPzwweGBPZPzJp6DHw4/HH44/HD44fDD4YdP7oZsrngOfjj8cPjh8MPhh8MP5yTHsWhxImEXZhs+2w38dDewk82AR5p7n9O95tHg9z57Ej79e+pbnn4UGOMFDgMskA85ENw7P8bxnBPkPu49eN6TOwe+0f5O8CNnvvXsMvmQOsHakr+djfb84/SDR9Por304fdET8isekW+5oIqHyBivgsZjwtHnn3e6x6Z2V/hLn/D/Ld3G1p6yuaf+F80Ie/j7y//6t8//AjNp+7E=
|
705,157
|
Surround the 1's
|
Given a matrix of order nxm, composed of only 0's and 1's, find the number of 1's in the matrix that are surrounded by an even number (>0) of 0's. The surrounding of a cell in the matrix is defined as the elements above, below, on left, on right as well as the 4 diagonal elements around the cell of the matrix. Hence, the surrounding of any matrix elements is composed of 8 elements. Find the number of such 1's.
Examples:
Input:
matrix = {{1, 0, 0},
{1, 1, 0},
{0, 1, 0}}
Output:
1
Explanation:
1 that occurs in the 1st row and 1st column, has 3 surrounding elements 0,1 and 1. The occurrence of zero is odd.
1 that occurs in 2nd row and 1st column has 5 surrounding elements 1,0,1,1 and 0. The occurrence of zero is even.
1 that occurs in 2nd row and 2nd column has 8 surrounding elements. The occurrence of 0 is odd.
Similarly, for the 1 that occurs in 3rd row and 2nd column, the occurrence of zero in it's 5 surrounding elements is odd.
Hence, the output is 1.
Input:
matrix = {{1}}
Output:
0
Explanation:
There is only 1 element in the matrix. Hence, it has no surroundings, so it's count for even 0's is 0 for the whole matrix.
0 is even but we want occurrence of a zero in the surrounding at least once.
Hence, output is 0.
Constraints:
1 <= n, m <= 10**3
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int Count(int[][] matrix)"
],
"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 n = Integer.parseInt(s[0]);\n int m = Integer.parseInt(s[1]);\n int[][] matrix = new int[n][m];\n for(int i = 0; i < n; i++){\n String[] S = br.readLine().trim().split(\" \");\n for(int j = 0; j < m; j++)\n matrix[i][j] = Integer.parseInt(S[j]);\n }\n Solution ob = new Solution();\n int ans = ob.Count(matrix);\n out.println(ans);\n \nout.println(\"~\");\n}\n out.close();\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution\n{\n public int Count(int[][] matrix)\n {\n // code here\n int n = matrix.length;\n int m = matrix[0].length;\n int ans = 0;\n for(int i = 0; i < n; i++){\n \tfor(int j = 0; j < m; j++){\n \t\tif(matrix[i][j]==1){\n \t\t\tint cnt = 0;\n \t\t\tif(i - 1 >= 0)\n \t\t\t\tcnt += matrix[i-1][j] == 0?1:0;\n \t\t\tif(i + 1 < n)\n \t\t\t\tcnt += matrix[i+1][j] == 0?1:0;\n \t\t\tif(j - 1 >= 0)\n \t\t\t\tcnt += matrix[i][j-1] == 0?1:0;\n \t\t\tif(j + 1 < m)\n \t\t\t\tcnt += matrix[i][j+1] == 0?1:0;\n \t\t\tif(i - 1 >= 0 && j - 1 >= 0)\n \t\t\t\tcnt += matrix[i-1][j-1] == 0?1:0;\n \t\t\tif(i - 1 >= 0 && j + 1 < m)\n \t\t\t\tcnt += matrix[i-1][j+1] == 0?1:0;\n \t\t\tif(i + 1 < n && j - 1 >= 0)\n \t\t\t\tcnt += matrix[i+1][j-1] == 0?1:0;\n \t\t\tif(i + 1 < n && j + 1 < m)\n \t\t\t\tcnt += matrix[i+1][j+1] == 0?1:0;\n \t\t\tif((cnt & 1)==0 && cnt!=0)\n \t\t\t\tans++;\n \t\t}\n \t}\n }\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public int Count(int[][] matrix)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"Count(self, matrix)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n, m = input().split()\n n = int(n)\n m = int(m)\n matrix = []\n for _ in range(n):\n matrix.append(list(map(int, input().split())))\n ob = Solution()\n ans = ob.Count(matrix)\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n def Count(self, matrix):\n n = len(matrix)\n m = len(matrix[0])\n ans = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j]:\n cnt = 0\n if i - 1 >= 0:\n cnt += matrix[i-1][j] == 0\n if i + 1 < n:\n cnt += matrix[i+1][j] == 0\n if j - 1 >= 0:\n cnt += matrix[i][j-1] == 0\n if j + 1 < m:\n cnt += matrix[i][j+1] == 0\n if i - 1 >= 0 and j - 1 >= 0:\n cnt += matrix[i-1][j-1] == 0\n if i - 1 >= 0 and j + 1 < m:\n cnt += matrix[i-1][j+1] == 0\n if i + 1 < n and j - 1 >= 0:\n cnt += matrix[i+1][j-1] == 0\n if i + 1 < n and j + 1 < m:\n cnt += matrix[i+1][j+1] == 0\n if not (cnt & 1) and cnt:\n ans += 1\n return ans\n",
"updated_at_timestamp": 1731586310,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef Count(self, matrix):\n\t\t# Code here"
}
|
eJzNVDuOwjAQpVhxjpFrhDz5KctJkDaIYklBEyiChIQWcQi42nZ7l40/JCbhOfwKMlLi2J434+c3c/g4/Q0H+pn+VoOvnVgW600pJiQ4K5iqlxQjEvl2nX+X+WK+2pR2XWbFPivEz4gunQIKlGe1LImBbwB8Qwp1VNLBpfkwhEEpRBSp6Np0GsStgbY7UWOKbVYmMztQgD2zINCnjwUn+XPGAIYBTEKJpY8cSo2d+SUGP8622kD8FMRnShss9lKOjsCVo0skOex2pppzvPtOwEIY+fXMRhJt5HrmnmKTuLBRSSe9ZY0qBwn6xm4B1dERmBXLEzhpj1LREa+IXTWDx1NJGzn5oR5rggrf3wZxjzY3ylevtHPRL46heVF/t4PPjuN/jbfYXw==
|
703,269
|
Count subsets having distinct even numbers
|
Given an array arr of integers, you need to count all unique subsets that contain only even numbers from the array. Two subsets are considered identical if they contain the same set of elements, regardless of their order.
Examples:
Input:
arr[] = [4, 2, 1, 9, 2, 6, 5, 3]
Output:
7
Explanation:
The subsets are: [4], [2], [6], [4, 2], [2, 6], [4, 6], [4, 2, 6]
Input:
arr[] = [10, 3, 4, 2, 4, 20, 10, 6, 8, 14, 2, 6, 9]
Output:
127
Explanation:
The distinct even numbers are {2, 4, 6, 8, 10, 14, 20}. The number of unique subsets that can be formed from these numbers is 127.
Constraints:
1<= arr.size() <=10**6
1<=arr[i]<=10**4
It is Guaranteed that answers will fit in
64-bits
.
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public long countSubsets(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 while (t-- > 0) {\n String line = scanner.nextLine().trim();\n\n if (line.isEmpty()) {\n continue; // Skip empty lines\n }\n\n String[] elements = line.split(\" \");\n int[] arr = new int[elements.length];\n\n for (int i = 0; i < elements.length; i++) {\n arr[i] = Integer.parseInt(elements[i]);\n }\n\n Solution ob = new Solution();\n System.out.println(ob.countSubsets(arr));\n System.out.println(\"~\");\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1731514538,
"user_code": "class Solution {\n public long countSubsets(int[] arr) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"countSubsets(self, arr)"
],
"initial_code": "def main():\n T = int(input()) # Read the number of test cases\n while T > 0:\n # Convert input to list of integers\n a = list(map(int, input().strip().split()))\n print(Solution().countSubsets(a))\n print(\"~\")\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n def countSubsets(self, arr):\n st = set() # Create a set to store distinct even numbers\n for num in arr:\n if num % 2 == 0:\n st.add(num) # Add even numbers to the set\n # Calculate the number of subsets using bitwise operations\n return (1 << len(st)) - 1\n",
"updated_at_timestamp": 1731514538,
"user_code": "#User function Template for python3\nclass Solution:\n #Function to count the number of subsets with distinct even numbers\n def countSubsets(self, arr):\n # code here\n \n \n"
}
|
eJy1lMFKA0EMhj2Iz/Gz5yKZZLIz65MIVjxoD15qDy0URPEh9ObNFzUZldZKlC12IMMuy+RL8v87T8cvbydHbZ2/2sPFfXc7X6yW3Rm6NJ0nsoW99m6CbrZezK6Xs5uru9Vyk/RxOu8eJtghQaAoGIJzFJ1rvGTBFmKRLdSitygW1SLKKlE5o8snMEEImaCEnlAIlTC0aUTJiCXIx8jo4aUjWWPWk7VTncEMzuAeXJ0nDMmQHlKNHYJy1aLh6C2H8dSIxZhDo6YGlsbWhi9eQRqsiPH9pE9fuEhNoSZP0yY1Af2Do8hJ5CAKOUy5BBx1Tu9b8a36NsRuDPX39qU1XlrLNiMBK7iAB4i5VSAKKZABOSHbABW5II83sGW3hn+458M6ItEQNNIzF5tdv/Fjoi0rhjMN0+1a0XqOzKji73/7UTlzjSTcsopuvCKHcMuXyvx/MkeG4tEXSnxr/XIXfv/JEh/sR0tpZHHNlZz29+Xl8+k76HG5jg==
|
704,857
|
Kill Captain America
|
Captain America is hiding from Thanos in a maze full of N rooms connected by M gates.
The maze is designed in such a way that each room leads to another room via gates. All connecting gates are unidirectional.Captain America is hiding only in those rooms which are accessible directly/indirectly through every other room in the maze.
Help Thanos find the number of rooms in which Captain America can hide.
Examples:
Input:
N = 5 and M = 5
V = [[1, 2], [2, 3], [3, 4], [4, 3], [5, 4]]
Output:
2
Explanation:
We can look closesly after forming graph
than captain america only can hide in a
room 3 and 4 because they are the only room
which have gates through them. So,
answer is 2.
Input:
N = 2, M = 1
V = [[1, 2]]
Output:
1
Constraints:
1 ≤ n ≤ 30000
1 ≤ m ≤ 200000
1 ≤ p,q ≤ n
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int captainAmerica(int N, int M, int V[][])"
],
"initial_code": "//Initial Template for Java\n\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n \n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0)\n {\n String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n int N = Integer.parseInt(input_line[0]);\n int M = Integer.parseInt(input_line[1]);\n int V[][] = new int[M+1][2];\n for(int i=0;i<M;i++){\n String input_line1[] = read.readLine().trim().split(\"\\\\s+\");\n V[i][0] = Integer.parseInt(input_line1[0]);\n V[i][1] = Integer.parseInt(input_line1[1]);\n }\n Solution ob = new Solution();\n int ans = ob.captainAmerica(N, M, V);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n\n",
"script_name": "GFG",
"solution": "class Solution {\n static int MAXN = 40000;\n static ArrayList<ArrayList<Integer>> graph;\n static ArrayList<ArrayList<Integer>> graphT;\n static ArrayList<Integer> sol;\n static boolean[] visited;\n static int[] conne, in;\n\n void dfs1(int S) {\n visited[S] = true;\n int i;\n for (i = 0; i < graph.get(S).size(); ++i) {\n if (!visited[graph.get(S).get(i)]) {\n dfs1(graph.get(S).get(i));\n }\n }\n sol.add(S);\n }\n\n void dfs2(int S, int c) {\n visited[S] = false;\n conne[S] = c;\n int i;\n for (i = 0; i < graphT.get(S).size(); ++i) {\n if (visited[graphT.get(S).get(i)]) {\n dfs2(graphT.get(S).get(i), c);\n }\n }\n }\n\n int captainAmerica(int n, int gates[][]) {\n int t, i, v, j, compon, u, ou, lim, aa, bb, cc;\n int m = gates.length;\n\n sol = new ArrayList<>();\n graph = new ArrayList<>();\n graphT = new ArrayList<>();\n for (i = 0; i < MAXN + 1; i++) {\n graph.add(new ArrayList<>());\n graphT.add(new ArrayList<>());\n }\n\n visited = new boolean[MAXN + 1];\n conne = new int[MAXN + 1];\n in = new int[MAXN + 1];\n for (i = 1; i <= m; ++i) {\n u = gates[i - 1][0];\n v = gates[i - 1][1];\n graph.get(v).add(u);\n graphT.get(u).add(v);\n }\n for (i = 1; i <= n; ++i) {\n if (!visited[i]) {\n dfs1(i);\n }\n }\n compon = 0;\n for (i = sol.size() - 1; i >= 0; --i) {\n if (visited[sol.get(i)]) {\n dfs2(sol.get(i), compon++);\n }\n }\n lim = compon;\n for (i = 1; i <= n; ++i) {\n for (j = 0; j < graph.get(i).size(); ++j) {\n if (conne[i] != conne[graph.get(i).get(j)]) {\n in[conne[graph.get(i).get(j)]] += 1;\n }\n }\n }\n ou = 0;\n for (i = 0; i < lim; ++i) {\n if (in[i] == 0) {\n ++ou;\n }\n }\n if (ou > 1) {\n return 0;\n } else {\n ou = 0;\n for (i = 1; i <= n; ++i) {\n if (in[conne[i]] == 0) {\n ++ou;\n }\n }\n return ou;\n }\n }\n}\n",
"updated_at_timestamp": 1730476510,
"user_code": "//User function Template for Java\nclass Solution{\n \n int captainAmerica(int N, int M, int V[][]){\n \n }\n \n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"captainAmerica(self, N, M, V)"
],
"initial_code": "# Initial Template for Python 3\n\n\nif __name__ == '__main__':\n ob = Solution()\n t = int(input())\n for _ in range(t):\n N, M = map(int, input().split())\n V = list()\n for i in range(0, M):\n l = list(map(int, input().split()))\n V.append(l)\n ans = ob.captainAmerica(N, M, V)\n print(ans)\n print(\"~\")\n",
"solution": "import sys\n# setting recursion limit to prevent stack overflow\nsys.setrecursionlimit(10**6)\nMAX = 40000 # maximum number of nodes in the graph\n\n# adjacency list representation of the graph and its transpose\ngraph = [[] for i in range(MAX)] # graph\ngraphT = [[] for i in range(MAX)] # transpose of graph\n\nsol = [] # list to store the nodes in topological order\n\nvisited = [False for i in range(MAX)] # boolean list to mark visited nodes\n# array to store the component number of each node\nconne = [0 for i in range(MAX)]\n# array to store the number of initial outgoing edges of each component\nini = [0 for i in range(MAX)]\n\n\nclass Solution:\n\n # depth-first search to perform a topological sort\n def dfs(self, S):\n visited[S] = True\n for v in graph[S]:\n if visited[v] == False:\n self.dfs(v)\n sol.append(S)\n\n # depth-first search to find strongly connected components\n def dfs2(self, S, C):\n visited[S] = False\n conne[S] = C\n for v in graphT[S]:\n if visited[v]:\n self.dfs2(v, C)\n\n def captainAmerica(self, N, M, V):\n sol.clear() # clearing the list to store the nodes in topological order\n\n # clearing the graph, graph transpose, visited list, component number list, and initial outgoing edge count list\n for i in range(1, N+1):\n graph[i].clear()\n graphT[i].clear()\n visited[i] = False\n conne[i] = 0\n ini[i] = 0\n\n # creating the adjacency list representation of the graph and its transpose\n for i in range(M):\n u = V[i][0]\n v = V[i][1]\n graph[v].append(u)\n graphT[u].append(v)\n\n # performing a depth-first search to get the nodes in topological order\n for i in range(1, N+1):\n if visited[i] == False:\n self.dfs(i)\n\n compon = 0 # variable to store the number of components\n\n # finding strongly connected components and assigning component numbers\n for i in range(len(sol)-1, -1, -1):\n if visited[sol[i]]:\n compon = compon + 1\n self.dfs2(sol[i], compon)\n\n lim = compon # storing the number of components\n\n # counting the number of initial outgoing edges of each component\n for i in range(1, N+1):\n for j in range(len(graph[i])):\n if conne[i] != conne[graph[i][j]]:\n ini[conne[graph[i][j]]] = ini[conne[graph[i][j]]] + 1\n\n ou = 0 # variable to store the number of components with 0 initial outgoing edges\n\n # counting the number of components with 0 initial outgoing edges\n for i in range(1, lim+1):\n if ini[i] == 0:\n ou = ou + 1\n\n if ou > 1:\n return 0 # returning 0 if there is more than 1 component with 0 initial outgoing edges\n\n ou = 0 # variable to store the number of nodes with 0 initial outgoing edges\n\n # counting the number of nodes with 0 initial outgoing edges\n for i in range(1, N+1):\n if ini[conne[i]] == 0:\n ou = ou + 1\n\n return ou # returning the number of nodes with 0 initial outgoing edges\n",
"updated_at_timestamp": 1730476510,
"user_code": "#User function Template for python3\nclass Solution:\n def captainAmerica (self, N, M, V):\n # code here\n\n"
}
|
eJytk00OgjAQhV3oPSZdE0NL+fMYrjSOcaEs3FQWkJgYjYfQ+0prwQAptCqrJu18b96b4T59rmcT9a2W1WFzIUeRlwVZAKEoKPgoiAckO+fZvsgOu1NZfK5v1eXVg3YNH6jxjTWBFGMomDwFQJ0REcQ9BIcQRQiRvOVaxYANDFjqQzrGjSFBkch3KVB380zCtYLZNzP67kTHv4ju5/QDe4QpaRVqxwgHtYTmsfGhJXQ1QaE/Ddf9hzYGUYOwacoZqQsl6B+GqjDdGhjWtttI+o5SenHxoKRR/l22+nUFjjdiD61H0KTJmjjHdmz7mL8AtE2imQ==
|
704,969
|
Triangular Number
|
Given a number N.Check whether it is a triangular number or not.Note:A number is termed as a triangular number if we can represent it in the form of a triangular grid of points such that the points form an equilateral triangle and each row contains as many points as the row number, i.e., the first row has one point, the second row has two points, the third row has three points and so on.The starting triangular numbers are 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4).
Examples:
Input:
N=55
Output:
1
Explanation:
55 is a triangular number.
It can be represented in 10 rows.
Input:
N=56
Output:
0
Explanation:
56 is not a triangular number.
Constraints:
1<=N<=10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int isTriangular(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.isTriangular(N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n int isTriangular(int N) {\n // using the equation:\n // sum of first N natural numbers=N*(N+1)/2\n int x = (int) (Math.sqrt(2 * N));\n if (x * (x + 1) == 2 * N) return 1;\n return 0;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n int isTriangular(int N){\n //code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isTriangular(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 ob = Solution()\n print(ob.isTriangular(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def isTriangular(self, N):\n # using the equation:\n # sum of first N natural numbers=N*(N+1)/2\n x = (int)(math.sqrt(2*N))\n if x*(x+1) == 2*N:\n return 1\n return 0\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def isTriangular(self, N):\n #code here"
}
|
eJxrYJlax8IABhHlQEZ0tVJmXkFpiZKVgpJhTJ5ZTJ6SjoJSakVBanJJakp8fmkJQrIOKFmro4Cqw9CAdC2mJGsxMiRdiwXJWoxJ974J6X4xI90Wc9L9Ykl6iIG0ABHJ0YnHQwa4wsCQdD2goIYkhRhISiU54A3NYM4l3cFguyl2gqEhifYCXUtW6BricK+hGRl+NyTCTDNoygYlIII2xE7RAwBoFnCQ
|
703,498
|
Smallest number repeating K times
|
Given an array arr, the goal is to find out the smallest number that is repeated exactly ‘k’ times.Note:If there is no such element then return-1.
Examples:
Input:
arr[] = [2, 2, 1, 3, 1], k = 2
Output:
1
Explanation:
Here in array, 2 is repeated 2 times, 1 is repeated 2 times, 3 is repeated 1 time. Hence 2 and 1 both are repeated 'k' times i.e 2 and min(2, 1) is 1 .
Input:
arr[] = [3, 5, 3, 2], k = 1
Output:
2
Explanation:
Both 2 and 5 are repeating 1 time but min(5, 2) is 2.
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ arr[i] ≤ 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int findDuplicate(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.findDuplicate(nums, d);\n System.out.println(ans);\n }\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n public int findDuplicate(int[] arr, int k) {\n Map<Integer, Integer> freq = new HashMap<>();\n // Computing frequencies of all elements\n for (int num : arr) {\n freq.put(num, freq.getOrDefault(num, 0) + 1);\n }\n int smallest = -1; // Initialize the smallest element with the desired frequency\n // Finding the smallest element with frequency as k\n for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {\n if (entry.getValue() == k) {\n // Update smallest if it is -1 or if the current element is smaller\n if (smallest == -1 || entry.getKey() < smallest) {\n smallest = entry.getKey();\n }\n }\n }\n return smallest;\n }\n}\n",
"updated_at_timestamp": 1727776457,
"user_code": "\nclass Solution {\n public int findDuplicate(int[] arr, int k) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"findDuplicate(self, arr, k)"
],
"initial_code": "if __name__ == '__main__':\n tc = int(input().strip())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n k = int(input().strip())\n ob = Solution()\n print(ob.findDuplicate(arr, k))\n tc -= 1\n",
"solution": "class Solution:\n\n def findDuplicate(self, arr, k):\n freq = {}\n\n # Computing frequencies of all elements\n for num in arr:\n if num in freq:\n freq[num] += 1\n else:\n freq[num] = 1\n\n smallest = -1 # Initialize the smallest element with the desired frequency\n\n # Finding the smallest element with frequency as k\n for num, count in freq.items():\n if count == k:\n if smallest == -1 or num < smallest:\n smallest = num\n\n return smallest\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findDuplicate(self, arr, k):\n # code here\n"
}
|
eJzNVMFOwzAMrRCC33jKeUxz0qTtvgSJoh1YD1zKDp2EhCbtI7av5ULiVp2AuTRjaCTRO8S1/Z4dd3u9v7pNeN2/3yTJw5t6rlfrRs2hqKzDUROo6nVVPTXVcvGybg5WtZngy/czvwZ8WvMRP3jQ0ZnQBRQ95XwaBiksHDLkKHykaKmQTzCLnIQCIJDSTMwwuZQJWibpd1mbKH74+/29iCB/r0EGlIIsyIEyUA4qoL1yK5blhyaj8KuHvIesB8cgP4bWOi5J/jmqDZAGMAF0AApw0tvz92z8D8pmF5BG59Dm4kZYx44wB7PiFN8N/v4kFoLXYfa5+OeZfzMmLBfSdczHNURWPtD5tt/Fbxoeq4cbGKHocTf9ALagySY=
|
701,742
|
Check Equal Arrays
|
Given two arrays arr1 and arr2 of equal size, the task is to find whether the given arrays are equal. Two arrays are said to be equal if both contain the same set of elements, arrangements (or permutations) of elements may be different though.Note: If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal.
Examples:
Input:
arr1[] = [1, 2, 5, 4, 0], arr2[] = [2, 4, 5, 0, 1]
Output:
true
Explanation:
Both the array can be rearranged to [0,1,2,4,5]
Input:
arr1[] = [1, 2, 5], arr2[] = [2, 4, 15]
Output:
false
Explanation:
arr1[] and arr2[] have only one common value.
Constraints:
1<= arr1.size, arr2.size<=10**7
0<=arr1[], arr2[]<=10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1616488754,
"func_sign": [
"public static boolean check(int[] arr1, int[] arr2)"
],
"initial_code": "// Initial Template for Java\n\n/*package whatever //do not write package name here */\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().trim());\n\n while (t-- > 0) {\n String line1 = read.readLine().trim();\n String[] numsStr1 = line1.split(\" \");\n int[] arr1 = new int[numsStr1.length];\n for (int i = 0; i < numsStr1.length; i++) {\n arr1[i] = Integer.parseInt(numsStr1[i]);\n }\n\n String line2 = read.readLine().trim();\n String[] numsStr2 = line2.split(\" \");\n int[] arr2 = new int[numsStr2.length];\n for (int i = 0; i < numsStr2.length; i++) {\n arr2[i] = Integer.parseInt(numsStr2[i]);\n }\n\n Solution ob = new Solution();\n System.out.println(ob.check(arr1, arr2) ? \"true\" : \"false\");\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Function to check if two arrays are equal or not.\n public static boolean check(int[] arr1, int[] arr2) {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616488754,
"func_sign": [
"check(self, arr1, arr2) -> bool"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for tc in range(t):\n arr1 = [int(x) for x in input().replace(' ', ' ').strip().split(' ')]\n arr2 = [int(x) for x in input().replace(' ', ' ').strip().split(' ')]\n ob = Solution()\n if ob.check(arr1, arr2):\n print(\"true\")\n else:\n print(\"false\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n # Function to check if two arrays are equal or not.\n def check(self, arr1, arr2) -> bool:\n # using a dictionary to store frequency of elements.\n mp = {}\n\n # Check if lengths of arrays are equal\n if len(arr1) != len(arr2):\n return False\n\n # incrementing frequencies of elements present in first array in the dictionary.\n for num in arr1:\n if num in mp:\n mp[num] += 1\n else:\n mp[num] = 1\n\n # decrementing frequencies of elements present in second array in the dictionary.\n for num in arr2:\n if num not in mp or mp[num] == 0:\n return False\n mp[num] -= 1\n\n # iterating over the dictionary.\n for count in mp.values():\n # if frequency of any element in dictionary now is not zero it means that its\n # count in two arrays was not equal so the arrays are not equal.\n if count != 0:\n # returning false since arrays are not equal.\n return False\n\n # returning true if arrays are equal.\n return True\n",
"updated_at_timestamp": 1727947200,
"user_code": "# User function Template for python3\n\nclass Solution:\n # Function to check if two arrays are equal or not.\n def check(self, arr1, arr2) -> bool:\n #code here"
}
|
eJzdVs1q3DAQ7qHnPsOHz6Fo9K+8Q285FLqllHYLheCGZBcKodCHaN+3I1mW7UYb7PVuSSMzZizNr/XNSD9f/r569SKNt2+YeXfffG1v9rvmEo3ctCQEJJNi0kyGyTI5Js8UmFhGJMnu0+dlm8V1Vped6KYN/QBBQkHDwMLBg2eipcosilJzgWb7/Wb7abf9/OHbfpdj3d3ut5u2ezc/LjBKgzatwqxntuCjQTx0HzgLx9kYzkpxdgROUzxMf6FZkkob63xA8M4arSSB+gHZD6h+cCSDYFEeVIrgoLwkpIgXHP2sVY4IY6Ax3hh2jD4GIWORIdmhjhI844xLqyZJqqRF4ihUDUDuGV84VzhbOFM4XThVOFk4KtyoWkRlWVbM6Io7WwnLzyypCuxEPwYTFW7VvxjyPlGOI26If2HiAkc/q5SX7k+tf1KseJACaZABWZADeVCIBSBju4DkuteQBtJCOkgPGbhCuCuKyMVvl9ZMklNJh1IBhWTLJbsm+VDJH6Xe/Xf7+2+ayhg7GUwZXRluGX8ZkBmhGbK5TvsaFpNZOdHQE2t24qkH8bNpUWv70peP13cHTvlzHOp1dyeDZV1iBTDDU0Fm/nEHt+uMfWp2yzkPlpaCaeSvu8n8M6fLr8WnK6HJxXjVgTpcdZeerY9du59G1KcL+5jdPgC0ebv9/tfrP5j1NzY=
|
702,810
|
Find pairs with given relation
|
Given an array arr[] of distinct integers, write a program to determine if there are two distinct pairs of elements (a, b) and (c, d) in the array such that the product of the first pair a * b is equal to the product of the second pair c * d. All four elements a, b, c, and d are distinct. If such pairs exist, return 1, otherwise, return -1.
Examples:
Input:
arr[] = [3, 4, 7, 1, 2, 9, 8]
Output:
1
Explanation:
Product of 4 and 2 is 8 and also,the product of 1 and 8 is 8.
Input:
arr[] = [1, 6, 3, 9, 2, 10]
Output:
1
Explanation:
Product of 1 and 6 is 6 and also,the product of 2 and 3 is 6.
Constraints:
4 ≤ arr.size() ≤ 10**3
1 ≤ arr[i] ≤ 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int findPairs(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.findPairs(arr);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "// User function Template for Java\nimport java.util.HashMap;\n\nclass Solution {\n // Function to find if there are any pairs with the same product.\n public static int findPairs(int arr[]) {\n int n = arr.length; // Get the length of the array\n // Creating HashMap to store products as keys and pair of indices as values.\n HashMap<Integer, int[]> map = new HashMap<>(); // Using int[] to store pairs of indices\n // Looping through the array to find all possible pairs.\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n // Calculating the product of the pair.\n int prod = arr[i] * arr[j];\n // Checking if the product already exists in the map.\n if (!map.containsKey(prod)) {\n // If not, storing the pair of indices in the map.\n map.put(prod, new int[] {i, j});\n } else {\n // If the product already exists in the map, returning 1 (found pair\n // with same product).\n return 1;\n }\n }\n }\n // If no pair with the same product is found, returning -1.\n return -1;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\nclass Solution {\n public static int findPairs(int arr[]) {}\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"findPairs(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.findPairs(arr)\n print(res)\n t -= 1\n print(\"~\")\n",
"solution": "# User function Template for python3\nclass Solution:\n # Function to find if there are any pairs with the same product.\n def findPairs(self, arr):\n n = len(arr) # Get the length of the array\n # Creating a dictionary to store products as keys and pairs of indices as values.\n products = {}\n\n # Looping through the array to find all possible pairs.\n for i in range(n):\n for j in range(i + 1, n):\n # Calculating the product of the pair.\n prod = arr[i] * arr[j]\n # Checking if the product already exists in the dictionary.\n if prod not in products:\n # If not, storing the pair of indices in the dictionary.\n products[prod] = (i, j)\n else:\n # If the product already exists in the dictionary, returning 1 (found pair with the same product).\n return 1\n\n # If no pair with the same product is found, returning -1.\n return -1\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findPairs(self,arr):\n #code here.\n"
}
|
eJy1UztOxDAUpIB7jFwvaF6cxDYnQWIRBaSgCVtkJaQViEPAfXl2vLAgJeAALhIXnt/7PB+/7k6O0rkY9HK5M3f9ZjuYcxhZ94IKFrVZwXQPm+5m6G6v77dDfnCqL57WvXlc4SssAqsJ2BQqSjVwxWJERViiJhqiJRzhiUAIWeghB1YfLRw8gnJANE8FsZAa0kBaiIN4SFDlYgE1ReZv0FNcpWbEJ4pCcNTT3ow/luMPy3OQo5QlwSBLEkhu8seU/aTdM5M6BhL/y0jRS3kUO1uDGdd/ZTvtTkLaT47Ktumb3YyE+xplHV2j/1IaFcSTNSVk+gV0yRPF6cpxP2ULjE1NxTvg6uXsDTgnhZM=
|
702,881
|
Fascinating Number
|
Given a number n. Your task is to check whether it is fascinating or not.
Examples:
Input:
n = 192
Output:
true
Explanation:
After multiplication with 2 and 3, and concatenating with original number, number will become 192384576 which contains all digits from 1 to 9.
Input:
n = 853
Output:
false
Explanation:
It is not a fascinating number
Constraints:
100 <= n <=
2*10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615306351,
"func_sign": [
"boolean fascinating(long n)"
],
"initial_code": "import java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n Solution ob = new Solution();\n\n int T = sc.nextInt();\n\n while (T != 0) {\n long n = sc.nextLong();\n if (ob.fascinating(n))\n System.out.println(\"true\");\n else\n System.out.println(\"false\");\n T--;\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // determines if a number is fascinating\n boolean fascinating(long n) {\n // calculating the multiples of n\n long x = 2 * n;\n long y = 3 * n;\n // converting the multiples to strings\n String s = Long.toString(x);\n String ss = Long.toString(y);\n String q = Long.toString(n);\n // concatenating the strings\n q = q + s;\n q = q + ss;\n // initializing an array to store the frequency of digits\n int[] hash = new int[10];\n // counting the frequency of each digit in the concatenated string\n for (int i = 0; i < q.length(); i++) {\n hash[q.charAt(i) - '0']++;\n }\n // checking if each digit appears only once in the concatenated string\n for (int i = 1; i <= 9; i++) {\n if (hash[i] != 1) {\n // returning false if any digit appears more than once\n return false;\n }\n }\n // returning true if each digit appears only once in the concatenated string\n return true;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n boolean fascinating(long n) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615306351,
"func_sign": [
"fascinating(self,n)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n n = int(input().strip())\n ob = Solution()\n ans = ob.fascinating(n)\n if ans:\n print(\"true\")\n else:\n print(\"false\")\n print(\"~\")\n tc -= 1\n",
"solution": "class Solution:\n def fascinating(self, n: int) -> bool:\n s = str(n) + str(n * 2) + str(n * 3)\n hash = [0] * 10\n\n for c in s:\n hash[int(c)] += 1\n\n for i in range(1, 10):\n if hash[i] != 1:\n return False\n\n return True\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n\n\tdef fascinating(self,n):\n\t # code here"
}
|
eJxrYJl6nYUBDCIuABnR1UqZeQWlJUpWCkqGMXmGBgZKOgpKqRUFqcklqSnx+aUlUMm0xJzi1Ji8upg8pVodBVRdlpaWZOgyNDImR5elBRm6jAxxubCkqBSnJnMzMqwyNjIn3SpjE1MyrDI3NiJDl4Uhmd6CuNMwJoacNGJkCNFOTkqB6Y2JgUQleWaA0imQQLjEEmeiwJvYIYFBliPgeuFsSDKDiJCX3gzIzLNogYotmC1xhhtZ+R2SiMjK9QaGxPkydooeABrxjYc=
|
701,207
|
Rearrange an array with O(1) extra space
|
Given an arrayarr[]of size N where every element is in the range from0ton-1. Rearrange the given array so that the transformed array arr**T[i] becomesarr[arr[i]].
Examples:
Input:
N = 2
arr[] = {1,0}
Output:
0 1
Explanation:
arr[arr[0]] = arr[1] = 0
arr[arr[1]] = arr[0] = 1
So, arr
**T
becomes {0, 1}
Input:
N = 5
arr[] = {4,0,2,1,3}
Output:
3 4 2 0 1
Explanation:
arr[arr[0]] = arr[4] = 3
arr[arr[1]] = arr[0] = 4
arr[arr[2]] = arr[2] = 2
arr[arr[3]] = arr[1] = 0
arr[arr[4]] = arr[3] = 1
and so on
So, arr
**T
becomes {3, 4, 2, 0, 1}
Constraints:
1 <= N <= 10**5
0 <= Arr[i] < N
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static void arrange(long arr[], int n)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass Main\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n //testcases\n int t =Integer.parseInt(read.readLine());\n \n while(t-- > 0)\n {\n //size of array\n int n = Integer.parseInt(read.readLine());\n String st[] = read.readLine().trim().split(\"\\\\s+\");\n long arr[] = new long[(int)n];\n \n //adding elements to the array\n for(int i = 0; i < n; i++)\n arr[(int)i] =Integer.parseInt(st[(int)i]);\n \n //calling arrange() function\n new Solution().arrange(arr, n);\n \n //printing the elements \n for(int i = 0; i < n; i++)\n System.out.print(arr[i] + \" \");\n System.out.println();\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "Main",
"solution": "//Back-end complete function Template for Java\n\nclass Solution\n{\n //Function to rearrange an array so that arr[i] becomes arr[arr[i]]\n //with O(1) extra space. \n static void arrange(long arr[], int n)\n {\n int i = 0;\n \n //Increasing all values by (arr[arr[i]]%n)*n to store the new element.\n for(i = 0; i < n; i++)\n arr[(int)i]+=(arr[(int)arr[(int)i]]%n)*n;\n \n //Since we had multiplied each element with n.\n //We will divide by n too to get the new element at that \n //position after rearranging.\n for(i = 0; i < n; i++)\n arr[(int)i] = arr[(int)i]/n;\n }\n}",
"updated_at_timestamp": 1730272441,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n // arr: input array\n // n: size of array\n //Function to rearrange an array so that arr[i] becomes arr[arr[i]]\n //with O(1) extra space.\n static void arrange(long arr[], int n)\n {\n // your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"arrange(self,arr, n)"
],
"initial_code": "# Initial Template for Python 3\nimport math\n\n\ndef main():\n T = int(input())\n while T > 0:\n n = int(input())\n arr = [int(x) for x in input().strip().split()]\n ob = Solution()\n ob.arrange(arr, n)\n for i in arr:\n print(i, end=\" \")\n print()\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n # Function to rearrange an array so that arr[i] becomes arr[arr[i]]\n # with O(1) extra space.\n def arrange(self, arr, n):\n # Increasing all values by (arr[arr[i]]%n)*n to store the new element.\n for i in range(0, n):\n arr[i] += (arr[arr[i]] % n)*n\n\n # Since we had multiplied each element with n.\n # We will divide by n too to get the new element at that\n # position after rearranging.\n for i in range(0, n):\n arr[i] = arr[i]//n\n",
"updated_at_timestamp": 1730272441,
"user_code": "#User function Template for python3\n\n##Complete this code\n\nclass Solution:\n #Function to rearrange an array so that arr[i] becomes arr[arr[i]]\n #with O(1) extra space.\n def arrange(self,arr, n): \n #Your code here"
}
|
eJy1VjFOw0AQpKDhFyPXEfKufWeblyBxiAJS0BwpEikSAvEI+Acd32P34sKJfYePJHFjrce7M3O763xcfv1cXYTf7bfc3L0Wz361WRc3KCrnqXS+Q4sGFgY1KjAIEiTjfCm3LKFaHlmBtOhAEiSQoCpQ7TwrVsItqAFZkJFweMgBWGIifbFAsdyulo/r5dPDy2bd85mq5/z7HCKzccrPBq7CuE9fvC0wsIV2tmgi4TrkH+GtKFU24n2QmJ0XVxUdnNiVKYMlGtASWqr7056o2KmqcsrWeUX1iqSu1o4djvOtJt+7EsI1qUlx2h1A/3j/ipjUCONxN56orbIa6oBbnRgYu5d1LuX+LCJkjhqULKGR+qBYSxltqWHHjIRVmnWOhkmig2CkS/61eTJoZa2QOFPZJixmcQ0WDgwWYIlzrsw0XSmuFDjQmW5zMbfSBSjgFtyALdjgWAXR2TmXNOVsA39RkfiSTFnQD3SE2hjccpMDn48Uzxw7l/GC7pP4orLpTWVOvaoOCc7WoXOa4ZIXm8KoUe6sDf7FjDVnGK9fzayj1Re8lki8c/95/QspTla9
|
701,163
|
Longest Consecutive 1's
|
Given a number N. Find the length of the longest consecutive 1s in its binary representation.
Examples:
Input:
N = 14
Output:
3
Explanation:
Binary representation of 14 is
1110, in which 111 is the longest
consecutive set bits of length is 3.
Input:
N = 222
Output:
4
Explanation:
Binary representation of222 is
11011110, in which 1111 is the
longest consecutive set bits of length 4.
Example 2:
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int maxConsecutiveOnes(int N)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass Main {\n \n\tpublic static void main (String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();//testcases\n\t\twhile(t-->0){\n\t\t int n = sc.nextInt();//input n\n\t\t \n\t\t Solution obj = new Solution();\n\t\t \n\t\t //calling maxConsecutiveOnes() function\n\t\t System.out.println(obj.maxConsecutiveOnes(n));\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\nclass Solution{\n \n /* Function to calculate the longest consecutive ones\n * N: given input to calculate the longest consecutive ones\n */\n public static int maxConsecutiveOnes(int N) {\n \n // Your code here\n \n }\n}\n\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxConsecutiveOnes(self, N)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\n\ndef main():\n T = int(input())\n\n while T > 0:\n n = int(input())\n obj = Solution()\n print(obj.maxConsecutiveOnes(n))\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to calculate the longest consecutive ones\n def maxConsecutiveOnes(self, N):\n count = 0\n # We use a loop to perform AND operation on N and N<<1 and everytime\n # the trailing 1 from every sequence of consecutive 1s is removed.\n # Loop continues till N is reduced to 0.\n while N != 0:\n # Assigning result of AND operation to N\n N = (N & (N << 1))\n # increment of counter variable.\n count += 1\n\n # returning the answer.\n return count\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n ##Complete this function\n # Function to calculate the longest consecutive ones\n def maxConsecutiveOnes(self, N):\n ##Your code here\n"
}
|
eJxrYJlawsIABhG5QEZ0tVJmXkFpiZKVgpJhTJ5BTJ6SjoJSakVBanJJakp8fmkJVBIoUweUrNVRQNVhiFOHIQ4dRiTrMMapwwiXqwyMcGsyxOUXIwMTc9y6cLrOyNwMjzZTHNrMTE2NTXFrM8PpMxMLU3PcGo1weQ63E41xRxRhd+LQa4AvZeBMS+BYI6QbZ/QBfUiJF2NIT8eGELeSa4IB1NGkBq4hVttJzSMwE/Io8wAEEeON2Cl6AI2Ia6Y=
|
703,149
|
Sid and his prime money
|
Given an array arr[] of selling prices in the cities, find the longest subsequence of consecutive cities where prices are strictly increasing. Also, calculate the maximum sum of prime numbers in that subsequence. If multiple subsequences have the same length, choose the one with the highest prime sum. If no primes are present, the prime sum is 0.
Examples:
Input:
arr[] = [4, 2, 3, 5, 1, 6, 7, 8, 9]
Output:
[5, 7]
Explanation:
5 cities are maximum number of cities in which the trend followed, And amount in those cities were 1, 6, 7, 8, 9. Out of these amounts only 7 is prime money.
Input:
arr[] = [2, 3, 5, 7, 4, 1, 6, 5, 4, 8]
Output:
[4, 17]
Explanation:
4 cities are maximum number of cities in which the trend followed, And amount in those cities were 2, 3, 5, 7. Out of these amounts, maximum total prime money is 2+3+5+7=17.
Input:
arr[] = [2, 2, 2, 2, 2]
Output:
[1, 2]
Explanation:
He was successful in one city only, And maximum total prime money is 2.
Constraints:
1 ≤ arr.size() ≤ 10**5
1 ≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1616524384,
"func_sign": [
"public static List<Integer> primeMoney(int arr[])"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n\n Solution obj = new Solution();\n List<Integer> ans = obj.primeMoney(arr);\n System.out.println(ans.get(0) + \" \" + ans.get(1));\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n public static List<Integer> primeMoney(int arr[]) {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616524384,
"func_sign": [
"primeMoney(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input()) # Read the number of test cases\n while t > 0:\n arr = list(map(int, input().split())) # Read the array of integers\n ob = Solution() # Create an instance of the Solution class\n res = ob.primeMoney(arr) # Get the result from the primeMoney method\n # Using format() method for older Python versions\n print(\"{} {}\".format(res[0], res[1])) # Properly format the output\n t -= 1 # Decrement the number of test cases\n print(\"~\")\n",
"solution": "import math\n\n\nclass Solution:\n # Function to check if a number is prime.\n def isPrime(self, x):\n if x < 2:\n return False\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n return False\n return True\n\n # Function to find the maximum consecutive increasing subsequence and\n # the sum of prime numbers in that subsequence.\n def primeMoney(self, arr):\n n = len(arr)\n if n == 0:\n return (0, 0) # Edge case if array is empty.\n\n c = [] # List to store the lengths of increasing subsequences.\n d = [] # List to store the start and end indices of subsequences.\n max1 = 1 # For tracking maximum length of increasing subsequences.\n # To store the maximum sum of prime numbers in subsequences.\n amount2 = 0\n\n i = 0\n while i < n - 1:\n max2 = 1\n if arr[i] < arr[i + 1]:\n d.append(i) # Start index of subsequence.\n\n # Finding the length of the consecutive increasing subsequence.\n while i < n - 1 and arr[i] < arr[i + 1]:\n max2 += 1\n i += 1\n\n c.append(max2) # Storing the length of subsequence.\n d.append(i) # End index of subsequence.\n\n if max1 < max2:\n max1 = max2 # Updating the maximum length.\n i += 1\n\n # If no increasing subsequence was found.\n if len(c) == 0:\n for i in range(n):\n if self.isPrime(arr[i]):\n # Finding the largest prime number.\n amount2 = max(amount2, arr[i])\n else:\n for i in range(len(c)):\n if c[i] == max1: # If the subsequence has the max length.\n amount1 = 0\n for m in range(d[2 * i], d[2 * i + 1] + 1):\n if self.isPrime(arr[m]):\n # Sum of prime numbers in subsequence.\n amount1 += arr[m]\n # Updating the maximum sum.\n amount2 = max(amount2, amount1)\n\n return (max1, amount2) # Returning the results.\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def primeMoney(self, arr):\n # return (0,0)\n"
}
|
eJy9VctuFDEQ5MCBzyjNEUWR2267bb4kEos4wB64LDlspEhRIj4C/jflHjY8lN5sgsTMdtsz9rinyjW1317/kDev/Lh4y877m+XL7vJqv7zDIpudoCCjokEEBimQgZyRBbkiK/JAYb8j23KGZXt9uf20337++PVq/3MVRRmb3d1mt9ye4a/VU4IkYWQG107KqAzWSyyXOmOwNufxBUQ4b76DcJ7UoKA01FKCkhXqkByNTkBEwCo2AQphJOTiwNoEVtLEJiMoZWg1xkZ0gwdmVzwXz+Z5zMGJL4kPig9K9RyRSc452oKaxaACLVB2MlShxEs6ErRDB3lBNdSBJmglBCUW0cc3fTgziVRqYz19izA3qKy/GEEkhzGMnAhGJze9M3jdG6MyCiNjGMeM9433TRm8bxJJgetZCOUAoFELrPYnBGqDoJoro7vqk6s+H/QRyS/7DkYQXRXdsz30xXP2XDxXz82zeR4zi88MuSWAqDA/LcsTIhv/0GwCm438fuU61WZ+1epYm7I2EcukJA3NPSQ69pDVPE4hhoI4jZuXOdGJPnfc6Fq47SN66LhCX6I/AqgRzOe43z/a3yOEikR/HRpzKpGs6BQxqeFncIoW++NiLP9NjU/6+C8j12NOziee7eRPmLccmP3w/fwesFMBmA==
|
703,679
|
Number of edges in a Planar Graph
|
On a wall, there are C circles. You need to connect various circles using straight lines so that the resulting figure is a planar graph with exactly F faces. Print the units digit of number of edges we can draw between various circles so as the resulting graph is planar with F faces.
Examples:
Input:
C =
"6" ,
F =
"10"
Output:
4
Explanation:
14 edges will be needed. Unit digit
of 14 is 4. So,Output is 4.
Input:
C =
"100" ,
F =
"667"
Output:
5
Explanation:
765 edges will be needed. Unit digit
of 765 is 5. So,Output is 5.
Constraints:
1 <= C,F <= 10**10000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int findNoOfEdges(String C, String F)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n String C = S[0];\n String F = S[1];\n\n Solution ob = new Solution();\n System.out.println(ob.findNoOfEdges(C,F));\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static int findNoOfEdges(String C, String F) {\n // Since we are concerned with units digit only, so we extract the units digits.\n int C_last = C.charAt(C.length() - 1) - '0';\n int F_last = F.charAt(F.length() - 1) - '0';\n // Summing both units digit of c and f. Mod 10 gives the units digit of the sum.\n // The sum is done according to Euler's planar formula. Vertices+Faces-Edges=2.\n // Here C is vertices, F is faces, and we need to find units digit of E.\n int Edges = (C_last + F_last) % 10;\n // If Edges come as less than 2. 10 is added to avoid negative answer.\n if (Edges < 2) Edges += 10;\n Edges -= 2;\n return Edges;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int findNoOfEdges(String C, String F) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"findNoOfEdges(self, C , F)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n C, F = map(str, input().split())\n\n ob = Solution()\n print(ob.findNoOfEdges(C, F))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def findNoOfEdges(self, C, F):\n # Since we are concerned with units digit only, so we extract the units digits.\n C_last = int(C[len(C)-1])\n F_last = int(F[len(F)-1])\n\n # Summing both units digit of c and f. Mod 10 gives the units digit of the sum.\n # The sum is done according to Euler's planar formula. Vertices+Faces-Edges=2.\n # Here C is vertices, F is faces, and we need to find units digit of E.\n\n Edges = (C_last + F_last) % 10\n\n # If Edges come as less than 2. 10 is added to avoid negative answer.\n\n if Edges < 2:\n Edges += 10\n\n Edges -= 2\n\n return Edges\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findNoOfEdges(self, C , F):\n # code here "
}
|
eJytVMtOxDAM5ID4DqsnDitwm0cTvgSJIA7QA5ewh660EgLxEfC/TL2sKGzcUmAsRankmXEsuy/Hb+cnR4LLU1yuHqv7vN701QVVJuUIUGi9S7lujCXn24ArAxQGpFytqOq26+627+5uHjb9B7lJ+TllltPLWT2taKSOhMYNOqKGRCuqZvehqAZRCiU9m7KxzlMbIvgRRZOzBi41QA2ABIAsoBrYUcG1nK5khtY4gDyQcgvQrhvSsMFRdYiiZ/SHDL1mBDWMQCojyDICrowgzwj4MoICI+DMCBKm6j1+0WwdSK5J12KFE6UFcqrc4kDU+8Ga5rYK1wnX/WB8iu/kSWKcJY42Y6mGFM4xDveplxcFDpe0Xrylrb6l3xqb9M1pli75r7b8sF8pLexYsaY/lKT8C/7nZ7Bfwi/TPTOs2mYqQp91j64z0tevZ+9xB9Sr
|
703,186
|
Pair the minimum
|
Given an array arr[] of size 2n, where n is a positive integer, the task is to divide the array into n pairs such that the maximum sum of any pair is minimized.Examples:
Examples:
Input:
arr[] = [5, 8, 3, 9]
Output:
13
Explanation:
Possible pairs:
Case 1: (8, 9), (3, 5) → max sum: 17
Case 2: (5, 9), (3, 8) → max sum: 14
Case 3: (3, 9), (5, 8) → max sum: 13
The minimum of these maximum sums is 13. Hence, the answer is 13.
Input:
arr[] = [1, 6, 5, 9]
Output:
11
Constraints:
1 ≤ arr.size()≤ 10**5
1 ≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1616693371,
"func_sign": [
"public static int Pair_minimum(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.Pair_minimum(arr);\n System.out.println(ans);\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n // Function for finding the maximum pair sum\n public static int Pair_minimum(int arr[]) {\n int n = arr.length / 2;\n // Sorting the array in ascending order\n Arrays.sort(arr);\n // Initializing the maximum sum to -1\n int ans = -1;\n // Iterating over the first half and the last half of the sorted array\n for (int k = 0, j = 2 * n - 1; k < n && j >= n; k++, j--) {\n // Calculating the sum of the current pair and updating the maximum sum\n ans = Math.max(ans, arr[k] + arr[j]);\n }\n // Returning the maximum pair sum\n return ans;\n }\n}\n",
"updated_at_timestamp": 1727947200,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n // Function for finding maximum and value pair\n public static int Pair_minimum(int arr[]) {\n // Complete the function\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616693371,
"func_sign": [
"Pair_minimum(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.Pair_minimum(arr)\n print(res)\n t -= 1\n print(\"~\")\n",
"solution": "# User function Template for Python3\nclass Solution:\n\n def Pair_minimum(self, arr):\n # Calculate the length of half the array\n n = len(arr) // 2\n\n # Sorting the array in ascending order\n arr.sort()\n\n # Initialize the maximum pair sum\n ans = -1\n\n # Iterate over the first half and the last half of the sorted array\n for k in range(n):\n j = 2 * n - 1 - k # Index from the end\n # Calculate the sum of the current pair and update the maximum sum\n ans = max(ans, arr[k] + arr[j])\n\n # Return the maximum pair sum\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def Pair_minimum (self, arr) : \n #Complete the function\n\n"
}
|
eJytVEEOgjAQ9MBDNj2j6RZ6wJeYiPGgHLwgB0hMjMZH6Oe8+RPbRaIxDAhxmyxturPdnSm9BLdHMBFb3N1keVS7vKhKNSfFac7E2htZ8Ym3NFchqexQZJsy2673VdnEx/X22UWcQvrKVOdp+8CE5rXdnpBkYDDEGYoohjiLz/MVe48Z0Izbd1jriRyBFt4b0j4XOFfSpUWNFlG9wyT6ONwSGU2RphiXYZF6lmR0HAxr1/+9kgA5xVpwMhTDgwGOW4a1Gcb0DG9Irl3fX4HRbz2SHwSRIFyJ4TGSyEPQ8wysrrMn2CdxHA==
|
702,823
|
Chocolate Distribution Problem
|
Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M studentssuch that :1. Each student gets exactly one packet.2. The difference between maximum number of chocolates given to a student and minimumnumber of chocolates given to a student is minimum.
Examples:
Input:
N = 8, M = 5
A = {3, 4, 1, 9, 56, 7, 9, 12}
Output:
6
Explanation:
The minimum difference between maximum chocolates and minimum chocolates is 9 - 3 = 6 by choosing following M packets :{3, 4, 9, 7, 9}.
Input:
N = 7, M = 3
A = {7, 3, 2, 4, 9, 12, 56}
Output:
2
Explanation:
The minimum difference between maximum chocolates and minimum chocolates is 4 - 2 = 2 by choosing following M packets :{3, 2, 4}.
Constraints:
1 ≤ T ≤100
1≤N≤10**5
1 ≤A
i
≤10**9
1 ≤M ≤N
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1729287951,
"func_sign": [
"public int findMinDiff(ArrayList<Integer> arr, int m)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GfG {\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n\n while (t-- > 0) {\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> arr = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n arr.add(Integer.parseInt(token));\n }\n\n int m = Integer.parseInt(br.readLine());\n Solution ob = new Solution();\n\n System.out.println(ob.findMinDiff(arr, m));\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GfG",
"solution": "class Solution {\n public int findMinDiff(ArrayList<Integer> a, int m) {\n int n = a.size();\n Collections.sort(a);\n\n int start = 0, end = 0;\n // Largest number of chocolates\n int mind = Integer.MAX_VALUE;\n\n // Find the subarray of size m such that\n // difference between last (maximum in case\n // of sorted) and first (minimum in case of\n // sorted) elements of subarray is minimum.\n for (int i = 0; i + m - 1 < n; i++) {\n int diff = a.get(i + m - 1) - a.get(i);\n if (mind > diff) {\n mind = diff;\n start = i;\n end = i + m - 1;\n }\n }\n return a.get(end) - a.get(start);\n }\n}",
"updated_at_timestamp": 1730468820,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int findMinDiff(ArrayList<Integer> arr, int m) {\n // your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1729287951,
"func_sign": [
"findMinDiff(self, arr,M)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n A = [int(x) for x in input().split()]\n M = int(input())\n\n solObj = Solution()\n print(solObj.findMinDiff(A, M))\n print(\"~\")\n",
"solution": "#User function Template for python3\n\n\nclass Solution:\n\n def findMinDiff(self, arr, m):\n n = len(arr)\n\n # if there are no chocolates or number\n # of students is 0\n if (m == 0 or n == 0):\n return 0\n\n # Sort the given packets\n arr.sort()\n\n # Number of students cannot be more than\n # number of packets\n if (n < m):\n return -1\n\n # Largest number of chocolates\n min_diff = arr[n - 1] - arr[0]\n\n # Find the subarray of size m such that\n # difference between last (maximum in case\n # of sorted) and first (minimum in case of\n # sorted) elements of subarray is minimum.\n for i in range(len(arr) - m + 1):\n min_diff = min(min_diff, arr[i + m - 1] - arr[i])\n\n return min_diff\n",
"updated_at_timestamp": 1730468820,
"user_code": "#User function Template for python3\n\nclass Solution:\n\n def findMinDiff(self, arr,M):\n\n # code here"
}
|
eJy1lU1ugzAQhbuo1FtEI0vdJVXGYAM9SaW66iJh0c00CyJFihL1EM19YxzxWw8EJ/WwMAjevPnsMT+Pp+enBzfeZnbyvhdftNkW4hUEGsJlNSCrBiDI9t3fV1JDkZiDyHebfFXk68/vbdFoHg2Jwxx6iaxmBDEo0JBACqWuoYxRSTkVn93aVdvqJV/zwJBickkmVwQjwUsuGUmlAUtbDN7E8rHlWDroQumy4nsg8q2hQ9QmNsjWUDKRH0IvPPqG5H8jrC/riEumonGY49Mmpu+M6lNZh688Q/Etug6fZhQWfOd2JeAOGkrjZI3hbsxuashrN0qgOZRh9jrYJMYXcKH8PEewO4MHzuErFtRJdMyF/1MCK+s1D5dqvHs+fl/OlQzeLg==
|
711,971
|
Maximum Connected group
|
You are given a squarebinary grid. A grid is considered binary if every value in the grid is either1 or 0.You can changeat most onecell in the grid from0 to 1.You need to find the largest group of connected1's.Two cells are said to be connected if both areadjacent(top, bottom, left, right)to each other and both have the same value.
Examples:
Input:
grid = [1, 1]
[0, 1]
Output:
4
Explanation:
By changing cell (2,1), we can obtain a connected group of 4 1's
[1, 1]
[
1,
1]
Input:
grid = [1, 0, 1]
[1, 0, 1]
[1, 0, 1]
Output:
7
Explanation:
By changing cell (3,2), we can obtain a connected group of 7 1's
[1, 0, 1]
[1, 0, 1]
[1,
1,
1]
Constraints
:
1 <= size of the grid<= 500
0 <= grid[i][j] <= 1
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1661770666,
"func_sign": [
"public int MaxConnection(int grid[][])"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\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 int n = sc.nextInt();\n int[][] grid = new int[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n grid[i][j] = sc.nextInt();\n }\n }\n\n Solution obj = new Solution();\n int ans = obj.MaxConnection(grid);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class DisjointSet {\n List<Integer> rank, parent, size;\n\n DisjointSet(int n) {\n rank = new ArrayList<>(Collections.nCopies(n + 1, 0));\n parent = new ArrayList<>(n + 1);\n size = new ArrayList<>(n + 1);\n for (int i = 0; i <= n; i++) {\n parent.add(i);\n size.add(1);\n }\n }\n\n int findUPar(int node) {\n if (node == parent.get(node)) {\n return node;\n }\n int ultimateParent = findUPar(parent.get(node));\n parent.set(node, ultimateParent);\n return ultimateParent;\n }\n\n void unionBySize(int u, int v) {\n u = findUPar(u);\n v = findUPar(v);\n if (u == v) return;\n\n if (size.get(u) < size.get(v)) {\n parent.set(u, v);\n size.set(v, size.get(v) + size.get(u));\n } else {\n parent.set(v, u);\n size.set(u, size.get(u) + size.get(v));\n }\n }\n}\n\nclass Solution {\n \n boolean isValid(int r, int c, int n) {\n return r >= 0 && r < n && c >= 0 && c < n;\n }\n \n public int MaxConnection(int grid[][]) {\n // Your code here\n int n = grid.length;\n DisjointSet ds = new DisjointSet(n * n);\n int[] dr = { -1, 0, 1, 0 };\n int[] dc = { 0, -1, 0, 1 };\n\n for (int row = 0; row < n; row++) {\n for (int col = 0; col < n; col++) {\n if (grid[row][col] == 0) continue;\n\n for (int ind = 0; ind < 4; ind++) {\n int r = row + dr[ind];\n int c = col + dc[ind];\n\n if (isValid(r, c, n) && grid[r][c] == 1) {\n int nodeNo = row * n + col;\n int adjNodeNo = r * n + c;\n ds.unionBySize(nodeNo, adjNodeNo);\n }\n }\n }\n }\n\n int mx = 0;\n for (int row = 0; row < n; row++) {\n for (int col = 0; col < n; col++) {\n if (grid[row][col] == 1) continue;\n\n Set<Integer> components = new HashSet<>();\n for (int ind = 0; ind < 4; ind++) {\n int r = row + dr[ind];\n int c = col + dc[ind];\n if (isValid(r, c, n)) {\n if (grid[r][c] == 1) {\n components.add(ds.findUPar(r * n + c));\n }\n }\n }\n int sizeTotal = 0;\n for (int component : components) {\n sizeTotal += ds.size.get(component);\n }\n mx = Math.max(mx, sizeTotal + 1);\n }\n }\n\n for (int cellNo = 0; cellNo < n * n; cellNo++) {\n mx = Math.max(mx, ds.size.get(ds.findUPar(cellNo)));\n }\n\n return mx;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n\n public int MaxConnection(int grid[][]) {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1668177573,
"func_sign": [
"MaxConnection(self, grid : List[List[int]]) -> int"
],
"initial_code": "class IntMatrix:\n\n def __init__(self) -> None:\n pass\n\n def Input(self, n, m):\n matrix = []\n # matrix input\n for _ in range(n):\n matrix.append([int(i) for i in input().strip().split()])\n return matrix\n\n def Print(self, arr):\n for i in arr:\n for j in i:\n print(j, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n n = int(input())\n grid = IntMatrix().Input(n, n)\n obj = Solution()\n res = obj.MaxConnection(grid)\n print(res)\n print(\"~\")\n",
"solution": "from typing import List, Set\nfrom collections import defaultdict\n\n\nclass Solution:\n # Function to perform depth-first search on grid.\n def dfs(self, grid: List[List[int]], i: int, j: int, index: int) -> int:\n n = len(grid)\n if i < 0 or i >= n or j < 0 or j >= n or grid[i][j] != 1:\n return 0\n grid[i][j] = index\n count = (self.dfs(grid, i + 1, j, index) +\n self.dfs(grid, i - 1, j, index) +\n self.dfs(grid, i, j + 1, index) +\n self.dfs(grid, i, j - 1, index))\n return count + 1\n\n # Function to find neighbors of a cell in the grid.\n def findNeighbours(self, grid: List[List[int]], i: int, j: int, s: Set[int]) -> None:\n n = len(grid)\n if i > 0:\n s.add(grid[i - 1][j])\n if j > 0:\n s.add(grid[i][j - 1])\n if i < n - 1:\n s.add(grid[i + 1][j])\n if j < n - 1:\n s.add(grid[i][j + 1])\n\n # Function to find maximum connections in the grid.\n def MaxConnection(self, grid: List[List[int]]) -> int:\n n = len(grid)\n res = 0\n index = 2\n area = defaultdict(int)\n\n # Iterating over the grid to perform dfs on islands.\n for i in range(n):\n for j in range(n):\n if grid[i][j] == 1:\n area[index] = self.dfs(grid, i, j, index)\n res = max(res, area[index])\n index += 1\n\n # Iterating over the grid to find maximum connections.\n for i in range(n):\n for j in range(n):\n if grid[i][j] == 0:\n s = set()\n self.findNeighbours(grid, i, j, s)\n count = 1 # to account for the converted island\n for val in s:\n count += area[val]\n res = max(res, count)\n\n return res\n",
"updated_at_timestamp": 1729753320,
"user_code": "from typing import List\nclass Solution:\n def MaxConnection(self, grid : List[List[int]]) -> int:\n # code here\n \n"
}
|
eJxrYJlaz8oABhEVQEZ0tVJmXkFpiZKVgpJhTB4QGSjpKCilVhSkJpekpsTnl5YgZOti8pRqdRQwtBiSqMUIqEXBAGiVAi7LjHDrNIDoxGUnLp3GYJ1QW+EUiQ43Bjkc7HRDwoaY4DDEBKoNrh8Lg1TfmUBchHAaCgNqOA4zTXGYaQrXiGQGYSapTjeFhCkYkmIjDmvM8CRTXE4zwKbHAJcN6Opi8nBmAAwjaRH9BrjzLPZggEStKam5FuZ6bMkN5gEDQwPCFmANbjwlD/boAQU71RMphb6GeBtPhMC8EjtFDwAQl5aS
|
703,622
|
Ways to split string such that each partition starts with distinct letter
|
Given a string S. Letkbe the maximum number of partitions possible of the given string with each partition starts with a distinct letter. The task is to find the number of ways string S can be split intokpartition (non-empty) such that each partition starts with a distinct letter. Print number modulo1000000007.
Examples:
Input:
S =
"abb"
Output:
2
Explanation:
"abb" can be maximum split into 2 partitions
{a, bb} with distinct starting letter, for k = 2.
And, the number of ways to split "abb"
into 2 partitions with distinct starting letter
are 2 {a, bb} and {ab, b}.
Input:
S =
"abbcc"
Output:
4
Explanation:
"abbcc" can be maximum split into 3 partitions
with distinct letter, so k=3. Thus the number
of ways to split "abbcc" into 3 partitions with
distinct letter is 4 i.e. {ab, b, cc},
{ab, bc, c},{a, bb, cc} and {a, bbc, c}.
Constraints:
1 <= |S| <=10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int waysToSplit(String S)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n \n String S = read.readLine();\n\n Solution ob = new Solution();\n\n System.out.println(ob.waysToSplit(S));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static Long waysToSplit(String S) {\n int count[] = new int[26];\n Arrays.fill(count, 0);\n // Finding the frequency of each\n // character.\n for (int i = 0; i < S.length(); i++) count[S.charAt(i) - 'a']++;\n // making frequency of first character\n // of string equal to 1.\n count[S.charAt(0) - 'a'] = 1;\n Long ans = new Long(1);\n // Finding the product of frequency\n // of occurrence of each character.\n for (int i = 0; i < 26; ++i) {\n if (count[i] != 0) ans *= count[i];\n ans = ans % 1000000007;\n }\n\n ans = ans % 1000000007;\n return ans;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int waysToSplit(String S){\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"waysToSplit(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.waysToSplit(S))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def waysToSplit(self, S):\n\n # Finding the frequency of each\n # character.\n\n count = [0]*26\n\n for i in range(len(S)):\n count[ord(S[i])-97] += 1\n\n # making frequency of first character\n # of string equal to 1.\n count[ord(S[0])-97] = 1\n\n ans = 1\n\n # Finding the product of frequency\n # of occurrence of each character.\n for i in range(26):\n if count[i]:\n ans *= count[i]\n ans %= 1000000007\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def waysToSplit(self, S):\n # code here"
}
|
eJy1U1tOwzAQ5AOJa1T5rhBtXpSTIBGE4kfecZzETuwiEIeAm/HHZWgprUjbTRsKo3zYSjK7szvzcv72cXH2hdv3xeHu0YgZl8K4GRkTj/k+QhgTQmkQhKHHjPHIoIpTLCh5KKT4/tKxPPa8ePs0Hm39jzChQRjFSZrlrOBlVQvZtErPQa4JRNUB+gncAemAdgBWNW3HnQKV5zvQ21AKZh4+G63aRoq6KnnB8ixN4igMKMHIh4fmuK47nTiQAqUBRrgJeEOmaduWZULj6nomiuI4SdI0y/KcsaLgvCyrqq6FkLJp2lYpfUothA8+8NAscDUbCf0nkNq6mkG78OdIY0Va2gQyFFEdV0mZ8qzI2fBI7Fd8lPa+kfbacm1Fr4S4p5btgupXnS3zAnf9d2kH9V/3ZV3DYe8x0wlL2rEFWvmiWhrjFzvcl/eDqR6YsW0Bp/a8n3p9gfhms4ExEz05O9DaP5t2WPaOt/j96+UnGJnb0A==
|
704,550
|
Subsets with XOR value
|
Given an array arrof N integersand an integerK, find the number of subsets of arr having XOR of elements as K.
Examples:
Input:
N = 4
k = 6
arr: 6 9 4 2
Output:
2
Explanation:
The subsets are
{4,2} and {6}
Input:
N = 5
K = 4
arr:
1 2 3 4 5
Output:
4
Explanation:
The subsets are {1, 5},
{4}, {1, 2, 3, 4},
and {2, 3, 5}
Constraints:
1<=N<=20
1<=K<=100
0<=arr[i]<=100
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int subsetXOR(int arr[], int N, int K)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n//Position this line where user code will be pasted.\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n Scanner s = new Scanner(System.in);\n int t = s.nextInt();\n while(t-- > 0)\n {\n int N = s.nextInt();\n int K = s.nextInt();\n int arr[] = new int[N];\n for(int i =0;i<N;i++)\n {\n arr[i] =s.nextInt();\n }\n Solution ob = new Solution();\n System.out.println(ob.subsetXOR(arr,N,K));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static int subsetXOR(int arr[], int N, int K) {\n // Find maximum element in arr[]\n int max_ele = arr[0];\n for (int i = 1; i < N; i++) if (arr[i] > max_ele) max_ele = arr[i];\n // Maximum possible XOR value\n int m = 10 * max_ele;\n int[][] dp = new int[N + 1][m + 1];\n // The xor of empty subset is 0\n dp[0][0] = 1;\n // Fill the dp table\n for (int i = 1; i <= N; i++) {\n for (int j = 0; j <= m; j++) {\n dp[i][j] += dp[i - 1][j];\n if ((j ^ arr[i - 1]) <= m) {\n dp[i][j] += dp[i - 1][j ^ arr[i - 1]];\n }\n }\n }\n // The answer is the number of subset from set\n // arr[0..n-1] having XOR of elements as k\n return dp[N][K];\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n static int subsetXOR(int arr[], int N, int K) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"subsetXOR(self, arr, N, K)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, K = input().split()\n N = int(N)\n K = int(K)\n arr = input().split(' ')\n for itr in range(N):\n arr[itr] = int(arr[itr])\n ob = Solution()\n print(ob.subsetXOR(arr, N, K))\n print(\"~\")\n",
"solution": "import math\n\nclass Solution:\n def subsetXOR(self, arr, N, K):\n # Find maximum element in arr[]\n max_ele = arr[0]\n for i in range(1, N):\n if arr[i] > max_ele:\n max_ele = arr[i]\n\n # Maximum possible XOR value\n m = (1 << (int)(math.log2(max_ele) + 1)) - 1\n if K > m:\n return 0\n\n # The value of dp[i][j] is the number of subsets having XOR of their elements as j from the set arr[0...i-1]\n dp = [[0 for _ in range(m + 1)] for _ in range(N + 1)]\n\n # The xor of empty subset is 0\n dp[0][0] = 1\n\n # Fill the dp table\n for i in range(1, N + 1):\n for j in range(m + 1):\n dp[i][j] = (dp[i - 1][j] + dp[i - 1][j ^ arr[i - 1]])\n\n # The answer is the number of subset from set arr[0..n-1] having XOR of elements as k\n return dp[N][K]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nimport math\nclass Solution:\n def subsetXOR(self, arr, N, K): \n # code here"
}
|
eJzFVcuOEzEQ5MCFvyjNeYXc7ce0+RIkBnGAHLgMe8hKSAjER8A/ceOXqLZDWLJxNloCZKSMx+Ppqq7qtj8//vr9yaP2e/6Ngxcfprfr9c12eoYpLmvGvKyimFEgGbasvIdlDRAoIhLysiZw5dye83SFafP+evN6u3nz6t3NdhdKl/UTv2r/fTx9vMItLE4aMhfUimwgZMrQiDLDKkScihJLImSGVH+ndYDWcWSAIwExeDwOmJMGBuYMYkYKDus0SKD4jVklkE9B5EwiMePygswFEjTx82QDGlLGPJpiEhwiBDDpaqgzakHNqIk6IGfX+TjNloVqJ9hsoEGUCtQqDOikxsNuOXHAiUSJ0rI+6xrgZE1qNki6JUOciEjSe84UM7nIYk16d/qUP9Sm28MXFIHW8FujDBwgUpNWIiyU6HXLZ4ZMp10qXR76Oigb8mh+kcBcvChr471LgyUSnWev1xp6NzA9oreabWStp55+rlNBIkW+mA9jMds8Dyib1M6SlTjQOXfIHYnqfRvjXVG9Cjl9SPZkX/X/NK4g6eXpwbTFSw7p7hLBWvMGT91doWjJqWhx07y5Rk0ddS5Hq6qD5lEroUZURRV3hZqbudpGCyk7ezvCFDYqZinRTqS6bxbTh7aLFpV0DsTR6xIIQ+kY/Y/E29fpGPYey1K8gxvPAPZN+RjwaGs8Y3PW8Je3Z71ve37IEdmpnD4nT5wFO4vqv/TowuLrhdT/r2eXjBz8/fD6dRy8/PL0Bxusdho=
|
703,124
|
Smaller and Larger
|
Given a sorted array arr and a value x, return an array of size 2. The first value is the number of elements less than or equal to x, and the second value is the number of elements greater than or equal to x.
Examples:
Input:
arr[] = [1, 2, 8, 10, 11, 12, 19],
x = 0
Output:
0, 7
Explanation:
There are no elements less or equal to 0 and 7 elements greater to 0.
Input:
arr[] = [1, 5, 8, 12, 12, 12, 19], x = 12
Output:
6, 4
Explanation:
There are 6 elements less or equal to 12 and 4 elements greater or equal to 12.
Constraints:
1 ≤ arr.size ≤ 10**5
0 ≤ arr[i], x ≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int[] getMoreAndLess(int[] arr, int x)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\npublic class GFG {\n public static void main(String[] args) throws IOException {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n sc.nextLine(); // consume the newline\n while (t-- > 0) {\n String input = sc.nextLine();\n String[] strNumbers = input.split(\" \");\n int[] arr = new int[strNumbers.length];\n for (int i = 0; i < strNumbers.length; i++) {\n arr[i] = Integer.parseInt(strNumbers[i]);\n }\n int x = sc.nextInt();\n sc.nextLine(); // consume the newline\n int[] ans = new Solution().getMoreAndLess(arr, x);\n System.out.println(ans[0] + \" \" + ans[1]);\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n int[] getMoreAndLess(int[] arr, int x) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"getMoreAndLess(self, arr, x)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n x = int(input())\n ob = Solution()\n ans = ob.getMoreAndLess(arr, x)\n print(str(ans[0]) + \" \" + str(ans[1]))\n tc -= 1\n print(\"~\")\n",
"solution": "from bisect import bisect_left, bisect_right\n\n\nclass Solution:\n def getMoreAndLess(self, arr, x):\n l = bisect_left(arr, x)\n r = bisect_right(arr, x)\n return [r, len(arr) - l]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def getMoreAndLess(self, arr, x):\n\t\t# code here"
}
|
eJytlM9KxDAQxj3oe3zkvEgmaZLWJxGseNAevNQ9dGFBFB9CX9Wb4JeuCrJMmnVND9OSyS/z55u+nL59nJ3M6/KdL1eP5n5cbyZzASP9KNh7+tH2o1nBDNv1cDsNdzcPm+nrhIVw85n7TytUkEQlSQHl0CCiRfZxkAYSIS0c/Z0eW/ZWY3PwhAZiE8HdfHdQUfRTSZ6UlAlM0EMCJEE6RqYHhk6j2byY2Gz8zjQ7E2bz7aOnHaB2JJNJJZE0RItk0Vp0ufQ5/1IBggYtNlXvwIKqDhLVQkWYd1lZDeoUldS4yAn/KFGr+P9lOsS5wwdEyYfqXsiI9xZKLXaPmb/9MZNc9XeJ6gAvde64uSmXuEIgpXL+iruiN/EHdv16/gllAqpu
|
703,852
|
Ceil The Floor
|
Given an unsorted array arr[] of integers and an integer x, find the floor and ceiling of x in arr[].
Examples:
Input:
x = 7 , arr[] = [5, 6, 8, 9, 6, 5, 5, 6]
Output:
6, 8
Explanation:
Floor of 7 is 6 and ceil of 7 is 8.
Input:
x = 10 , arr[] = [5, 6, 8, 8, 6, 5, 5, 6]
Output:
8, -1
Explanation:
Floor of 10 is 8 but ceil of 10 is not possible.
Constraints :
1 ≤ arr.size ≤ 10**5
1 ≤ arr[i], x ≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1728109714,
"func_sign": [
"public int[] getFloorAndCeil(int x, int[] arr)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n\n while (t-- > 0) {\n int x = Integer.parseInt(br.readLine());\n String[] input = br.readLine().split(\" \");\n int[] arr = new int[input.length];\n for (int i = 0; i < input.length; i++) {\n arr[i] = Integer.parseInt(input[i]);\n }\n\n Solution ob = new Solution();\n int[] ans = ob.getFloorAndCeil(x, arr);\n System.out.println(ans[0] + \" \" + ans[1]);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "Main",
"solution": null,
"updated_at_timestamp": 1730280397,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int[] getFloorAndCeil(int x, int[] arr) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1728109714,
"func_sign": [
"getFloorAndCeil(self, x: int, arr: list) -> list"
],
"initial_code": "# Initial Template for Python 3\ndef main():\n t = int(input())\n for _ in range(t):\n x = int(input())\n arr = list(map(int, input().split()))\n\n ob = Solution()\n ans = ob.getFloorAndCeil(x, arr)\n print(ans[0], ans[1])\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n\n def getFloorAndCeil(self, x: int, arr: list) -> list:\n floor_val, ceil_val = -1, -1\n floor_diff, ceil_diff = float('inf'), float('inf')\n\n # Looping through the array to find the floor and ceil of x\n for num in arr:\n # Updating the ceil if the current element is greater than or equal to x and the difference is smaller\n if num >= x and ceil_diff > (num - x):\n ceil_diff = num - x\n ceil_val = num\n # Updating the floor if the current element is smaller than or equal to x and the difference is smaller\n if num <= x and floor_diff > (x - num):\n floor_diff = x - num\n floor_val = num\n\n return [floor_val, ceil_val]\n",
"updated_at_timestamp": 1730280397,
"user_code": "#User function Template for python3\n\nclass Solution:\n def getFloorAndCeil(self, x: int, arr: list) -> list:\n # code here"
}
|
eJytVMtOwzAQ5ID4jlHOLVq7dh58BDckJIo4QA9cQg+thIRAfAT8L/toopZkA5Xq5BDHu7OPmfXn+ffNxZmu22v+uHsrntv1dlNcoYjLNtCyzShR81Mi81PyzywHiIQFIREyoSRUhJrQEAKxUzFDsXpdrx43q6eHl+1mB1ljHpbtx85fv4r3GfaC8nGjS2x0Qbc1h9FdQHfuxLDj3mo0RCaFR2qQA0NKES5gttNRIHsdR0b23Ky0rlb0ew9p14rebho1IGKBJHShYuokwAR2R8pIn5SphiEq5T8xbIRfMSvEQYqS10JaTtJOLYUlIBoS+fjpRbNzYPn/XOj7VbGLRhhFiiIJ04RGY0DNUYLXliBytsQTyzyx2lPJDpV4iUVDMgLGkJlbrROqUhvNpjLno2iVPv7BrNqMc0uOy7AvdgUMZn9viPgWmKizPBj5IwfChx3YjcPWND2grvIHej2BWPeJ5HvzRFQeAB9ZqPik5n9aoO4+mPLhYQx9/fdflz/b+L+O
|
702,698
|
Last seen array element
|
Given an array arr[] of integers that might contain duplicates, find the element whose last appearance is earliest.
Examples:
Input:
arr[] = [10, 30, 20, 10, 20]
Output:
30
Explanation:
The element 30 has the earliest last appearance at index 1. Therefore, the output is 30. Even though 10 and 20 appear multiple times, their last appearances occur at later indices (3 and 4, respectively), so 30 is the correct answer.
Input:
arr[] = [10, 20, 30, 40, 10]
Output:
20
Explanation:
The element 20 has the earliest last appearance at index 1. Therefore, the output is 20.
Constraints:
1<=arr.size()<=10**6
1<=arr[i]<=10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int lastSeenElement(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.lastSeenElement(arr);\n System.out.println(ans);\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "import java.util.HashMap;\n\nclass Solution {\n public static int lastSeenElement(int[] arr) {\n // Store last occurrence index of every element\n HashMap<Integer, Integer> hash = new HashMap<>();\n for (int i = 0; i < arr.length; i++) {\n hash.put(arr[i], i);\n }\n // Find the element with the minimum index value\n int resInd = Integer.MAX_VALUE;\n int res = -1;\n for (HashMap.Entry<Integer, Integer> entry : hash.entrySet()) {\n if (entry.getValue() < resInd) {\n resInd = entry.getValue();\n res = entry.getKey();\n }\n }\n return res;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n public static int lastSeenElement(int arr[]) {\n // Complete the function\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"lastSeenElement(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 res = ob.lastSeenElement(arr)\n print(res)\n t -= 1\n print(\"~\")\n",
"solution": "class Solution:\n\n def lastSeenElement(self, arr):\n # Dictionary to store the last occurrence index of each element\n last_occurrence = {}\n for i, num in enumerate(arr):\n last_occurrence[num] = i\n\n # Find the element with the minimum index value\n min_index = float('inf')\n result = None\n for key, index in last_occurrence.items():\n if index < min_index:\n min_index = index\n result = key\n\n return result\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n def lastSeenElement(self, arr): \n # Complete the function\n"
}
|
eJzFVEtOwzAQZYHENZ6yrlBsj+OUkyBRxAK6YBNYtBISAnEIOAE7TsnzmKYq0rglIPHsKHbiefP1vBy/fZwcKc7fubh4bG6H+/WqOUPjFoNrFZgrsLPtyys1MzTLh/vl9Wp5c3W3Xn1JF5HF8LwYmqcZvvHCI0AQ0SGBTKSGM5i8QVKEdyjKy+CJljF0iJKJRJE2Bdo22mdQudbmKtNvZtApOqNlWoWvRNyNsffjKowr2awseiuCFJ1DekiCdBC6LxA67iEO1b9WjCuOMBo5FjkSORQtOj6JT59LKjupnuaTzpdtTcSqu9Y0wQf6ECV4hy71cyrtU0ev+CFr46A+DmrkoE4OauWAylo+ZwJLJwFPIBAMIEMYCXQEEoGewPZ6lb3+0TN6WuUyg5VgonJLYr4m23viNNB5ad65mP6sZPZUjMie0q/0nonN55CcxMOTIhOyMtoQ/tGInK1fp+8nZac6p5denZItYgqrUWakd9Mr7LBmp80mH93f1dzY1S5fTz8BirfuYw==
|
702,051
|
Top K Frequent in Array
|
Given a non-empty array arr[] of integers, find the top k elements which have the highest frequency in the array. If two numbers have the same frequencies, then the larger number should be given more preference.
Examples:
Input:
k = 2,
arr[] = [1, 1, 1, 3, 3, 4]
Output:
[1, 3]
Explanation:
Elements 1 and 3 have the same frequency ie. 2. Therefore, in this case, the answer includes the element 1 and 3.
Input:
k =
2
,
arr[] = [1, 1, 2, 2, 3, 3, 3, 4]
Output:
[3, 2]
Explanation:
Elements 3 and 2 occured three and two times respectively.
Constraints:
1 <= arr.size() <= 10**5
1<= arr[i] <=10**5
1 <= k <= no. of distinct elements
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1727681526,
"func_sign": [
"public ArrayList<Integer> topKFrequent(int[] arr, int k)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\npublic class Main {\n public static void main(String args[]) throws IOException {\n // taking input using class Scanner\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n\n while (t-- > 0) {\n // taking total number of elements\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 ArrayList<Integer> res = new Solution().topKFrequent(arr, k);\n\n // printing the elements of the ArrayList\n for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + \" \");\n System.out.println();\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730273865,
"user_code": "// User function Template for Java\n\nclass Solution {\n public ArrayList<Integer> topKFrequent(int[] arr, int k) {\n // Code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1727681526,
"func_sign": [
"topKFrequent(self, arr, k)"
],
"initial_code": "# Initial Template for Python 3\n\nimport atexit\nimport io\nimport sys\nfrom collections import deque\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 k = int(input())\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n res = ob.topKFrequent(arr, k)\n for i in range(len(res)):\n print(res[i], end=\" \")\n print()\n print(\"~\")\n",
"solution": "#Back-end complete function Template for Python 3\nclass Solution:\n\n def topKFrequent(self, nums, k):\n um = {} # create an empty dictionary to store the count of each number\n n = len(nums) # get the length of the input array\n for i in range(n): # iterate through the array\n if nums[i] in um: # if the number is already in the dictionary\n um[nums[i]] += 1 # increment its count by 1\n else: # if the number is not in the dictionary\n um[nums[i]] = 1 # add it to the dictionary with a count of 1\n a = [0] * (\n len(um)\n ) # create a new array with length equal to the number of unique numbers\n j = 0 # initialize a counter\n for i in um: # iterate through the dictionary\n a[j] = [i,\n um[i]] # store the number and its count in the new array\n j += 1 # increment the counter\n a = sorted(\n a, key=lambda x: x[0],\n reverse=True) # sort the array in descending order of numbers\n a = sorted(\n a, key=lambda x: x[1],\n reverse=True) # sort the array in descending order of counts\n res = [] # create an empty array to store the result\n for i in range(k): # iterate the indices from 0 to k-1\n res.append(\n a[i]\n [0]) # append the number at the ith index to the result array\n return res # return the result array\n",
"updated_at_timestamp": 1730273865,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef topKFrequent(self, arr, k):\n\t\t#Code here"
}
|
eJytVEGOwjAM7AF4h5UzQoQkQHkJEkUcoAcugUORkNCu9hHLdxGxCxEB2S2CuDdPJuPpJH+dc7eX0Zpfulm2OKmt3x8qNQOlC4/fEJfqgyqP+3JdlZvV7lDdIdSEwv8WXv30Id1tCu8Ay4QaYTE0LvQMx+KCBupbcOx+SydojmN0V4JIG/Vo0AIjw2VRj6b9hlTZG3OTOt4lPYT6y6mmVBOqMRbrPoEF32oAskSLZC6E8h7muKBNImokw6Tj32Ad4716GAViLliLarTskGxMaAeQmC6keneSNEUPMZqIORJUPOdo+laQENZaqmuhFZW6Zs6vzp9mw5iP0vF6z/Pmmy7mJHkPjfwgyg9GOujLZc9jt8kBTU/D7aDl/+AKhOqhIg==
|
703,723
|
Days of Our Lives
|
Given a month with arbitrary number of days, N, and an integerK representing the day with which it starts. ie- 1 for Monday, 2 for Tuesday and so on.Find the number of times each day(Monday, Tuesday, ..., Sunday) appears in the month.
Examples:
Input:
N =
31 ,
K =
1
Output:
5 5 5 4 4 4 4
Explanation:
The month starts from Monday.
There will be 4 days of each day
(Sunday , Monday , etc) upto 28th of the
Month. Then, The successive 3 days will
have a extra day each. So, Monday, Tuesday
and Wednesday will have 5 days while the
others will have 4 days each.
Input:
N =
28,
K =
5
Output:
5 5 5 4 4 4 4
Explanation:
Each day of the month will
have 4 days each and thus the Output.
Constraints:
1 <= N <= 10**5
1 <= K <= 7
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int[] daysOfWeeks(int N , int K)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n int N = Integer.parseInt(S[0]);\n int K = Integer.parseInt(S[1]);\n\n Solution ob = new Solution();\n int[] ans = ob.daysOfWeeks(N,K);\n \n for(int i=0 ; i<7 ; i++)\n {\n System.out.print(ans[i]);\n if(i<6)\n System.out.print(' ');\n }\n System.out.println();\n }\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int[] daysOfWeeks(int N , int K) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"daysOfWeeks(self, N ,K)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, K = map(int, input().split())\n ob = Solution()\n print(*ob.daysOfWeeks(N, K))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def daysOfWeeks(self, N, K):\n # Getting number of whole weeks.\n temp = N // 7\n # Getting number of days which will have 1 more day.\n temp2 = N % 7\n\n # Setting each day as number of whole weeks.\n ans = [temp] * 7\n\n # Adding 1 to Selected Days.\n for i in range(K - 1, K - 1 + temp2):\n i %= 7\n ans[i] += 1\n\n return ans\n",
"updated_at_timestamp": 1730472832,
"user_code": "#User function Template for python3\n\nclass Solution:\n def daysOfWeeks(self, N ,K):\n # code here"
}
|
eJytVEsOgjAQdaH3mHRNDG0tNp7ERIwLZeGmsoDExGg8hB7AnceUtiAfM1MWtkMhNO/No/OG+/T5nk3cWL+qh82FHU1eFmwFjKeGA2cRsOycZ/siO+xOZdFsQtzO1NxSw64RDNFLBN3BAkfQSyJ3Z6JoLPcYtEZzi1HoMbkFgpaJQrMrCUoMgqDBZPxwgJJYDWM78FIshE6AWpVfaXr0vMLE/g1eR7dg/GOqWe2QfqpdTHaCxg3FJbQhfBBKuoLCqmpluEUk4RFrjOHF7T0s71vZv+jU7oOJI/T9RPck8UPonb0LrBuskt7HBfpcUL4KGauhcLMm2T7mH7NLkDs=
|
700,380
|
Count Palindromic Subsequences
|
Given a string str of length N,you have to find numberofpalindromic subsequence (need not necessarily be distinct) present in the string str.
Note: You have to return the answer module 10**9+7;
Examples:
Input:
Str = "abcd"
Output:
4
Explanation:
palindromic subsequence are : "a" ,"b", "c" ,"d"
Input:
Str = "aab"
Output:
4
Explanation:
palindromic subsequence are :"a", "a", "b", "aa"
Constraints:
1<=length of string str <=1000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1731585456,
"func_sign": [
"int countPS(String s)"
],
"initial_code": "import java.util.*;\n\nclass GFG {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n sc.nextLine();\n while (t > 0) {\n String str = sc.nextLine();\n // System.out.println(str.length());\n Solution ob = new Solution();\n System.out.println(ob.countPS(str));\n t--;\n }\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n int countPS(String s) {\n int N = s.length();\n\n // Create a 2D array to store the count of palindromic subsequences\n int cps[][] = new int[N + 1][N + 1];\n for (int i = 0; i < N; i++) cps[i][i] = 1;\n\n char[] sArray = s.toCharArray();\n\n // Check subsequence of length L is palindrome or not\n for (int L = 2; L <= N; L++) {\n for (int i = 0; i <= N - L; i++) {\n int k = L + i - 1;\n if (sArray[i] == sArray[k])\n cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1;\n else\n cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1];\n }\n }\n\n // Return total palindromic subsequences\n return cps[0][N - 1];\n }\n}",
"updated_at_timestamp": 1731585456,
"user_code": "/*You are required to complete below method */\n\nclass Solution {\n int countPS(String s) {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731585456,
"func_sign": [
"countPS(self,s)"
],
"initial_code": "# Initial template for Python 3\n\nimport sys\n\nsys.setrecursionlimit(2000) # Increase limit as needed\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n ob = Solution()\n print(ob.countPS(input().strip()))\n",
"solution": "# Backend complete function template for Python 3\nclass Solution:\n # Function to count the palindromic subsequences in the given string.\n def countPS(self, s):\n # Initializing a 2D array to store the results of subproblems.\n t = [[-1 for i in range(1001)] for i in range(1001)]\n # Modulus value for calculations.\n mod = 10**9 + 7\n\n # Function to solve the problem recursively.\n def solve(s, i, j, t):\n # Base cases: if the string has only one character or no characters.\n if i == j:\n return 1\n if i > j:\n return 0\n # If the result for the current subproblem has already been calculated, return it.\n if t[i][j] != -1:\n return t[i][j]\n # If the first and last characters of the string are the same.\n elif s[i] == s[j]:\n # Recursively calculate the result for the remaining string (excluding the first and last characters).\n # Add 1 to account for the current subsequence itself.\n # Take the modulus to ensure the result is within the given range.\n t[i][j] = (1 + solve(s, i+1, j, t) + solve(s, i, j-1, t)) % mod\n return t[i][j]\n # If the first and last characters of the string are different.\n else:\n # Recursively calculate the result for the remaining string (excluding the first character OR the last character).\n # Subtract the result for the subproblem where the first and last characters are both excluded.\n # Take the modulus to ensure the result is within the given range.\n t[i][j] = (solve(s, i+1, j, t) + solve(s, i, j -\n 1, t) - solve(s, i+1, j-1, t)) % mod\n return t[i][j]\n\n # Starting point of the recursive function.\n return solve(s, 0, len(s)-1, t)\n",
"updated_at_timestamp": 1731585456,
"user_code": "class Solution:\n # Your task is to complete this function\n # Function should return an integer\n def countPS(self,s):\n # Code here\n"
}
|
eJxrYJl6g58BDCIuAhnR1UqZeQWlJUpWCkqGMXmJSjoKSqkVBanJJakp8fmlJQgppVodBVTFVXCAS5eBkTE2jYlJmBCHEaaWBiYW2M1ITklNS8/IzMrOyc3LLygsKi7BYYaRAVYDEnF51hyb8qLE5NTkxCJcVlhityIpCactxliDpqKysgKEK3EFqTFW1yFCA8HCZQKO4MASJ0MF4ooUC1NDMzMDY+xxg2LCEA8A/MFgaIEjzQynEIDkaCqEw0B7hEaeN7AwMzM2N8JaloLLtqGUALAK4iqbB8jLgyU8B9wBSM6A14nosiTFHbCKg9ZxSbgqOeztjuES6cOu8AZDwkoG2oXIzqBWUoZBw5gYcFMaIYKr3WhqYmKJu4lKSlIYsVmC9u6hEiSsZKBdiOwM3HmCCDeTk29wRDKUGqpNORy9WwItPFMTUEDFTtEDACbXyiA=
|
705,047
|
Circular Prime Number
|
Find all circular primes less than given number n. A prime number is aCircular Prime Numberif all of its possible rotations itself are prime numbers.
Examples:
Input:
n = 4
Output:
[2, 3]
Explanation:
2 and 3 are the circuler prime number less than 4.
Input:
n = 7
Output:
[2, 3, 5]
Explanation:
2, 3 and 5 are the circuler prime number less than 7.
Constraints:
2 <= n <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1727981375,
"func_sign": [
"public ArrayList<Integer> isCircularPrime(int n)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n String s = br.readLine().trim();\n String[] S = s.split(\" \");\n int n = Integer.parseInt(S[0]);\n Solution ob = new Solution();\n ArrayList<Integer> v = new ArrayList<Integer>();\n v = ob.isCircularPrime(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": "GFG",
"solution": "class Solution {\n public int length(int n) {\n int x = 0;\n while (n >= 10) {\n x++;\n n /= 10;\n }\n return x;\n }\n\n public int rotate(int n) {\n int x = n % 10;\n int len = length(n);\n for (int i = 0; i < len; i++) x *= 10;\n n = x + n / 10;\n return n;\n }\n\n public ArrayList<Integer> isCircularPrime(int n) {\n if (n < 2) return new ArrayList<>();\n boolean[] prime = new boolean[100000];\n for (int i = 2; i < 100000; i++) {\n prime[i] = true;\n }\n prime[0] = prime[1] = false;\n for (int i = 2; i * i <= 100000; i++) {\n if (prime[i]) {\n for (int j = i * i; j < 100000; j += i) {\n prime[j] = false;\n }\n }\n }\n ArrayList<Integer> result = new ArrayList<>();\n for (int i = 2; i < n; i++) {\n int len = length(i);\n int j, x = i;\n // check all rotations of i one by one\n for (j = 0; j < len; j++) {\n if (!prime[x]) break;\n x = rotate(x);\n }\n // If all rotations are prime\n if (j == len && prime[x]) {\n result.add(i);\n }\n }\n return result;\n }\n}\n",
"updated_at_timestamp": 1730477113,
"user_code": "// User function Template for Java\n\nclass Solution {\n public ArrayList<Integer> isCircularPrime(int n) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1727981375,
"func_sign": [
"isCircularPrime(self, n)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n = int(input())\n ob = Solution()\n ans = ob.isCircularPrime(n)\n print(*ans)\n # print(\"~\")\n",
"solution": "class Solution:\n\n def length(self, n):\n return len(str(n)) # Correct way to get the number of digits\n\n def rotate(self, n):\n x = n % 10 # Get last digit\n length = self.length(n)\n x *= 10**(length - 1) # Shift the last digit to the front\n return x + n // 10 # Rotate the number\n\n def isCircularPrime(self, n):\n prime = [True] * 100000\n prime[0] = prime[1] = False\n # Sieve of Eratosthenes to mark prime numbers\n for i in range(2, int(100000**0.5) + 1):\n if prime[i]:\n for j in range(i * i, 100000, i):\n prime[j] = False\n\n result = []\n for i in range(2, n):\n length = self.length(i)\n x = i\n is_circular = True\n\n # check all rotations of i one by one\n for _ in range(length):\n if not prime[x]:\n is_circular = False\n break\n x = self.rotate(x)\n\n # If all rotations are prime, add to the result\n if is_circular:\n result.append(i)\n\n return result\n",
"updated_at_timestamp": 1730477113,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef isCircularPrime(self, n):\n\t\t# Code here"
}
|
eJzVVctKxEAQ9ODFvyjmvEg6gwzlT3gTwYgHzcFL3EMWBBH8iN3/tToIIsxksw+XGEjoTFfX9KSayuf55vbibLjubhTcv4eXbrnqwzWCNV0dFgjt27J96tvnx9dV/51quvCxwG+sVQVwjYgrpGxNHK+BWX6rLXupDhZhCdEQE5IhRSSC2TbItDefUkpo2TwmhRBEmOgIo4ARNIcayNJ59j/QcRrQ6u7qVafsW3iqgE6kUDDR6HY6VdHLFRQE1jW7TgccHeg15MA48NPLPHReJ6Mn4EDfQS9FPeYnyF8c819NX72TxYww+HOCZZZ5rDrUbbKs7tL6hkkuYk1zXGu2E3rzuMhZYUp/yGlq/AzybE2qJMrQuKLZNTzdbrbNcnXoMD+sL78AfJQ0ug==
|
705,195
|
Longest valid Parentheses
|
Given a string str consisting of opening and closing parenthesis '(' and ')'. Find length of the longest valid parenthesis substring.
Examples:
Input:
str = ((()
Output:
2
Explanation:
The longest valid parenthesis substring is "()".
Input:
str = )()())
Output:
4
Explanation:
The longest valid parenthesis substring is "()()".
Constraints:
1 ≤ |str| ≤ 10**5
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int maxLength(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 {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while(t-- > 0){\n String S = in.readLine();\n \n Solution ob = new Solution();\n System.out.println(ob.maxLength(S));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730270502,
"user_code": "//User function Template for Java\n\nclass Solution{\n static int maxLength(String S){\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"maxLength(self, str)"
],
"initial_code": "# Initial Template for Python3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n S = input()\n\n ob = Solution()\n print(ob.maxLength(S))\n print(\"~\")\n\n# Revised to correct indentation:\n# nothing changed here because your code already looks perfect.\n# no errors in indentation were found.\n",
"solution": "# Back-end complete function Template for Python\nclass Solution:\n\n def maxLength(self, str):\n n = len(str)\n\n # Create a stack and push -1\n # as initial index to it.\n stk = []\n stk.append(-1)\n\n # Initialize result\n result = 0\n\n # Traverse all characters of given string\n for i in range(n):\n # If opening bracket, push index of it\n if str[i] == '(':\n stk.append(i)\n\n # If closing bracket, i.e., str[i] = ')'\n else:\n # Pop the previous opening bracket's index\n if len(stk) != 0:\n stk.pop()\n\n # Check if this length formed with base of\n # current valid substring is more than max\n # so far\n if len(stk) != 0:\n result = max(result, i - stk[len(stk) - 1])\n\n # If stack is empty. push current index as\n # base for next valid substring (if any)\n else:\n stk.append(i)\n\n return result\n",
"updated_at_timestamp": 1730270502,
"user_code": "# User function Template for Python3\n\nclass Solution:\n def maxLength(self, str):\n # code here"
}
|
eJy1Vs1OhDAQ9uDJpyA9zSQbw58b4sWbz2AixoNy8IJ7YBMTo/Eh9H2l0ynMLm2lLpRNCzTM9zPDsF/nP7cXZzTubvqT+3f10u72nbpO1FXdAgAi6hWBVjQH7ZhN2te75hJAbRLVvO2ap655fnzddxxtW7efdWvmiuYsF7fUxyYR2AVh6nAIBGsumAQaPn6wUkR2xi+tgqOB09GrI0Ac5Y5skB7SBoC91hN6eBWV0G+IZaVP/4FWC6p/4I0vHXXGzVkNxZ16YAQGTeWsHcUVtYIiWa6iGTzkHPrgZKlwwaRycWSUkRmSEdk0HNUGVUrzLKBTckFWUuKHEjGmoiVChwcnFTiVz1KTfFkJIBKI8u0czu0jXoWsKpfagkpzqxStexYTR+gwWOZ8CweJi2usIiX2TBYgs06+UlEjLkVuU1cgEmtqoNmcXtwz25W3WyEskfAVXC7j0i36nqvxze1SI72oDmloOolNu0ZM28gDbYMj29Acuz69pg7p+cmVgXzMNXzZf1d/fk0iPo///z4+fF/+AndIqrI=
|
700,219
|
Undirected Graph Cycle
|
Given an undirected graph with V vertices labelled from 0 to V-1 and E edges, check whether it contains any cycle or not. Graph is in the form of adjacency list where adj[i] contains all the nodes ith node is having edge with.
Examples:
Input:
V = 5, E = 5
adj = [[1], [0, 2, 4], [1, 3], [2, 4], [1, 3]]
Output:
1
Explanation:
1->2->3->4->1 is a cycle.
Input:
V = 4, E = 2
adj = [[], [2], [1, 3], [2]]
Output:
0
Explanation:
No cycle in the graph.
Constraints:
1 ≤ V, E ≤ 10**5
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public boolean isCycle(ArrayList<ArrayList<Integer>> adj)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n String[] s = br.readLine().trim().split(\" \");\n int V = Integer.parseInt(s[0]);\n int E = Integer.parseInt(s[1]);\n ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>());\n for (int i = 0; i < E; i++) {\n String[] S = br.readLine().trim().split(\" \");\n int u = Integer.parseInt(S[0]);\n int v = Integer.parseInt(S[1]);\n adj.get(u).add(v);\n adj.get(v).add(u);\n }\n Solution obj = new Solution();\n boolean ans = obj.isCycle(adj);\n if (ans)\n System.out.println(\"1\");\n else\n System.out.println(\"0\");\n\n System.out.println(\"~\");\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730273987,
"user_code": "class Solution {\n // Function to detect cycle in an undirected graph.\n public boolean isCycle(ArrayList<ArrayList<Integer>> adj) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isCycle(self, V: int, adj: List[List[int]]) -> bool"
],
"initial_code": "if __name__ == '__main__':\n T = int(input())\n for i in range(T):\n V, E = map(int, input().split())\n adj = [[] for i in range(V)]\n for _ in range(E):\n u, v = map(int, input().split())\n adj[u].append(v)\n adj[v].append(u)\n obj = Solution()\n ans = obj.isCycle(V, adj)\n if ans:\n print(\"1\")\n else:\n print(\"0\")\n",
"solution": "class Solution:\n def isCycleUtil(self, u, par, adj, vis):\n # marking the current vertex as visited.\n vis[u] = True\n\n # iterating on all the adjacent vertices.\n for v in adj[u]:\n if v == par:\n continue\n\n # if current vertex is visited, we return true else we\n # call the function recursively to detect the cycle.\n elif vis[v]:\n return True\n else:\n if self.isCycleUtil(v, u, adj, vis):\n return True\n return False\n\n # Function to detect cycle in an undirected graph.\n def isCycle(self, V, adj):\n # using a boolean list to mark all the vertices as not visited.\n vis = [False for i in range(V)]\n\n # iterating over all the vertices.\n for i in range(V):\n # if vertex is not visited, we call the function to detect cycle.\n if vis[i] == False:\n # if cycle is found, we return true.\n if self.isCycleUtil(i, -1, adj, vis):\n return True\n return False\n",
"updated_at_timestamp": 1730273987,
"user_code": "from typing import List\nclass Solution:\n #Function to detect cycle in an undirected graph.\n\tdef isCycle(self, V: int, adj: List[List[int]]) -> bool:\n\t\t#Code here"
}
|
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
|
704,603
|
Get Minimum Squares
|
Given a number n, find the minimum number of perfect squares (square of an integer) that sum up to n.
Examples:
Input:
n = 100
Output:
1
Explanation:
10 * 10 = 100
Input:
n = 6
Output:
3
Explanation =
1 * 1 + 1 * 1 + 2 * 2 = 6
Constraints:
1 <= n <= 10**4
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int MinSquares(int n)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n int n = Integer.parseInt(br.readLine().trim());\n Solution ob = new Solution();\n int ans = ob.MinSquares(n);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public static int helper(int[] dp, int rem) {\n if (rem == 0) return 0;\n if (rem < 0) return Integer.MAX_VALUE;\n int ans = dp[rem];\n // If it is calculated earlier then return\n if (ans != -1) return ans;\n ans = Integer.MAX_VALUE;\n // Go through all smaller numbers\n // to recursively find minimum\n for (int i = 1; i <= Math.sqrt(rem); i++) {\n if (rem - i * i >= 0) ans = Math.min(ans, 1 + helper(dp, rem - i * i));\n }\n return dp[rem] = ans;\n }\n\n public static int MinSquares(int n) {\n int[] dp = new int[n + 1];\n Arrays.fill(dp, -1);\n return helper(dp, n);\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int MinSquares(int n) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"MinSquares(self, n)"
],
"initial_code": "# Initial Template for Python 3\n\nfrom math import ceil, sqrt\nimport sys\nsys.setrecursionlimit(10**6)\n\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n = int(input())\n ob = Solution()\n ans = ob.MinSquares(n)\n print(ans)\n print(\"~\")\n",
"solution": "# User function Template for python3\nclass Solution:\n\n def MinSquares(self, n):\n dp = [-1] * (n + 1)\n\n # Helper function to calculate the minimum number of perfect squares that sum up to n\n def helper(rem):\n if rem == 0:\n return 0\n if rem < 0:\n return 1e18\n\n if dp[rem] != -1:\n return dp[rem]\n\n ans = 1e18\n # Iterating over all possible perfect squares less than or equal to rem\n for i in range(1, int(n**0.5) + 1):\n if rem - i * i >= 0:\n ans = min(ans, 1 + helper(rem - i * i))\n\n dp[rem] = ans\n return ans\n\n return helper(n)\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef MinSquares(self, n):\n\t\t# Code here"
}
|
eJydk0EKwjAQRV30ICXrIk3StKknEYy40Cy6iV20UBDFQ+h9TUwVuvgjcZhFIbzJ/3+ae/bss9W7tp3/2F1Y5/pxYJucceO4kKzImZ16exzs6XAeh/lQGnczjl2LfEm0vgBSAUT7SrylUYmAKgEgACBUDQgOCFkKpAohrS55IlI3GuWLvFdSoFuQe7/3P0KO3Si0TcJTTBw5QzKDs5gip6OhB4ROJXV0Cv9c5NV3SJfQCsnZ4s8BaD1fyXypg3h/SAsxin7Qn4H7x/oFJRthog==
|
704,896
|
Number of ways to find two numbers
|
Given a positive integer K. Find the number of ordered pairs of positive integers (a,b) where 1≤a<b<K such that a+b ≤ K.
Examples:
Input:
K =
2
Output:
0
Explanation:
There are no solutions for K = 2.
Input:
K =
4
Output:
2
Explanation:
There are 2 solutions:- (1,2) and (1,3).
Constraints:
1 <= K <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static Long numOfWays(int K)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n int K = Integer.parseInt(read.readLine());\n\n Solution ob = new Solution();\n System.out.println(ob.numOfWays(K));\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "//User function Template for Java\n\nclass Solution {\n static Long numOfWays(int K) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"numOfWays(self, K)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n K = int(input())\n ob = Solution()\n print(ob.numOfWays(K))\n print(\"~\")\n",
"solution": "class Solution:\n def numOfWays(self, K):\n # Checking if K is even or odd\n if K % 2 == 0:\n # Calculating the number of ways if K is even\n ans = (K // 2) * ((K - 2) // 2)\n else:\n # Calculating the number of ways if K is odd\n ans = ((K + 1) // 2) * ((K - 3) // 2) + 1\n\n # Returning the final answer\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def numOfWays(self, K):\n # code here"
}
|
eJzFk0FOwzAQRVkgcY3I6wrZ09hpehIkjFhAFmxMF6mEhEA9BFyGHTdj7HFNEnmciEXwJmmd+fP8Pf90+fl9dRHWzRe+3L6KJ3c49mJfCWWdklJsKtG9HLqHvnu8fz72cRNqLa17t068bapxkWaLDABb1frFNsM9iUsxxcpv8qhYrf0HueqtdeCZAzcnQZUmKhioG51X06gmAw9BRbQZwpa0kqdIfNb38FoOfvAniSbuCjbsfDEwNkThhtqV7gMNaJtEpWppQMGQmL8sNAj/ByoedyxaFFtpA9vk/TwG6xXQARt6mJJlXqJOkqGfYRw8j/HSgSLGcCfjCeOlKV+hwayViwn8x6CjpxqY2SaE/KCUoouHUlnHUnC9siqNbugoZXnyJ2R/IZo32iborOVr38mon/zvPE1SVYgVDj386g4ytvqFuLVSMktCZ5wkYmmw7j6ufwDOwDy/
|
714,129
|
Special Palindrome Substrings
|
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In asingle operation, we can replace any word of s1 with any character.
Examples:
Input:
s1="abaa" s2="bb"
Output:
1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Input:
s1="abbd" s2="mr"
Output:
4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Constraints:
1 ≤ |s2|≤ |s1| ≤ 1000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1677586392,
"func_sign": [
"public static int specialPalindrome(String a, String b)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n \n\tpublic static void main (String[] args)throws IOException {\n\t\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\tint t = Integer.parseInt(br.readLine());\n\t\twhile(t-->0)\n\t\t{\n\t\t String str = br.readLine();\n\t\t String s1 = str.split(\" \")[0];\n\t\t String s2 = str.split(\" \")[1];\n\t\t \n\t\t Solution obj = new Solution();\n\t\t int ans = obj.specialPalindrome(s1,s2);\n\t\t System.out.println(ans);\n\t\t \n\t\t \n\t\t \n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "GFG",
"solution": "class Solution{\n public static int specialPalindrome(String a, String b){\n //Code Here\n char s1[] = a.toCharArray(), s2[] = b.toCharArray();\n int l1 = s1.length, l2 = s2.length, ans = Integer.MAX_VALUE;\n for(int i=0 ; i<l1-l2+1 ; i++){\n char temp[]=(a.substring(0,i)+b+a.substring(i+l2)).toCharArray();\n int cost=0;\n // calculate cost to place s2\n for(int j=i ; j<i+l2 ; j++){\n if(s1[j]!=temp[j])\n cost++;\n }\n int z=0;\n for(int j=0 ; j<Math.ceil(l1/2.0) ; j++){\n \n if((j<i || j>=i+l2) && temp[j]!=temp[l1-j-1]) // if s2 is in the first half of new string\n cost++;\n else if(temp[j]!=temp[l1-j-1] && (l1-j-1<i || l1-j-1>=i+l2)) // if s2 is in the second half of new string\n cost++;\n else if(temp[j]!=temp[l1-j-1]){ // if s2 is in both halves\n z=1;\n break;\n }\n }\n if(z==0)\n ans=Math.min(ans,cost);\n }\n if(ans == Integer.MAX_VALUE){\n return -1;\n }\n return ans;\n }\n}",
"updated_at_timestamp": 1730482309,
"user_code": "//User function Template for Java\nclass Solution{\n public static int specialPalindrome(String a, String b){\n //Code Here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1677586392,
"func_sign": [
"specialPalindrome(self,s1, s2)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n s1, s2 = input().split()\n obj = Solution()\n print(obj.specialPalindrome(s1, s2))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nimport math\nINF = float(\"inf\")\n\n\nclass Solution():\n def specialPalindrome(self, s1, s2):\n # initialize the minimum cost to infinity\n ans = INF\n # iterate over the possible positions to insert s2 into s1\n for i in range(len(s1) - len(s2) + 1):\n # create a new string by inserting s2 into s1\n temp = s1[:i] + s2 + s1[i + len(s2):]\n cost = 0\n # calculate the cost of changing characters in s1 to make it equal to temp\n for j in range(i, i + len(s2)):\n if s1[j] != temp[j]:\n cost += 1\n z = 0\n # check if the resulting string is a palindrome and calculate the additional costs\n for j in range(math.ceil(len(s1) / 2)):\n if ((j < i or j >= i + len(s2)) and temp[j] != temp[len(s1) - j - 1]):\n cost += 1\n elif (temp[j] != temp[len(s1) - j - 1] and (len(s1) - j - 1 < i or len(s1) - j - 1 >= i + len(s2))):\n cost += 1\n elif (temp[j] != temp[len(s1) - j - 1]):\n z = 1\n break\n\n # update the minimum cost\n if z == 0:\n ans = min(ans, cost)\n if ans == INF: # if no valid insertion is possible, return -1\n return -1\n return ans\n",
"updated_at_timestamp": 1730482309,
"user_code": "#User function Template for python3\n\nclass Solution():\n def specialPalindrome(self,s1, s2):\n #your code goes here"
}
|
eJydlFtOwzAQRfmAfVj+LohWvMRKkChCfrV1mjhu6rRJEIhFwD74Y3s4D6qW9rottuLxj0/m3hn7/fTz++ykGQ9ffvP4QrWxuaP3hPaHhnEh1Wg80ZGOpnFiUjvL5o7ki2VRVs4H2iNUFVYJp+Rzmrvu6MCffRsa+tojm8CqLJaL3M2zmU1NEk8jPRmPlBScEc4EoPWvAY21g3Pe7RipF4RBlFZkF0gbAeMGMnidByNCCgnO3gX+7+3sAvFfWSAJl4BRlOvTMyDiFhAsi7WRWZoolaSZNDpmljRbAMKpVF7AaiXNDjBwYTkXQkqlhPAlRY2BtKw72kjwacigr6g3fl1pRGxaE/LmCnlzRK1D4sy/LuVBFdtXskM8rxF/uVsX7XjldWv73g409/meO77Ts7BpA5TMVodVbYv5iboMsXa8QPU7Bl+hlcynj4sfs04HDQ==
|
703,643
|
Encrypt the string - 2
|
You are given a string S. Every sub-string of identical letters is replaced by a single instance of that letter followed by the hexadecimal representation of the number of occurrences of that letter. Then, the string thus obtained is further encrypted by reversing it [ See the sample for more clarity ]. Print the Encrypted String.
Examples:
Input:
S = "
aaaaaaaaaaa"
Output:
ba
Explanation:
aaaaaaaaaaa
Step1: a
11
(a occurs 11 times)
Step2: a11 is ab [since 11 is b in
hexadecimal]
Step3: ba
[After reversing]
Input:
S = "
abc
"
Output:
1c1b1a
Explanation:
abc
Step1: a1b1c1
Step2: 1c1b1a
[After reversing]
Constraints
1 <= |S| <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static String encryptString(String S)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n \n String S = read.readLine();\n\n Solution ob = new Solution();\n\n System.out.println(ob.encryptString(S));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static String encryptString(String S) {\n int count = 0;\n String ans = \"\";\n char c = S.charAt(0);\n count = 1;\n for (int i = 1; i < S.length(); i++) {\n if (S.charAt(i) == S.charAt(i - 1))\n count++; // Counting number of continuous repeating Characters.\n else {\n ans += c; // appending the character\n String hx = \"\";\n // Change the value of Count to HexaDecimal value.\n while (count != 0) {\n int rem = count % 16;\n if (rem < 10) hx += (char) ('0' + rem);\n else hx += (char) ('a' + (rem - 10));\n\n count /= 16;\n }\n ans += hx; // appending the hex value of count.\n c = S.charAt(i);\n count = 1;\n }\n }\n\n ans += c;\n String hx = \"\";\n while (count != 0) {\n int rem = count % 16;\n if (rem < 10) hx += (char) ('0' + rem);\n else hx += (char) ('a' + (rem - 10));\n\n count /= 16;\n }\n ans += hx;\n String final_ans = \"\";\n for (int i = ans.length() - 1; i >= 0; i--) final_ans += ans.charAt(i); // Reversing the answer.\n return final_ans;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static String encryptString(String S){\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"encryptString(self, S)"
],
"initial_code": "if __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n S = input()\n ob = Solution()\n print(ob.encryptString(S))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def encryptString(self, S):\n ans = \"\"\n\n count = 0\n\n c = S[0]\n count = 1\n\n for i in range(1, len(S)):\n if S[i] == S[i-1]:\n count += 1 # Counting number of continuous repeating Characters\n else:\n ans += c # appending the Character.\n hx = \"\"\n # Change the Count value to Hexadecimal.\n while count:\n rem = count % 16\n if rem < 10:\n hx += chr(48 + rem)\n else:\n hx += chr(97 + rem - 10)\n count //= 16\n ans += hx # appending the hex value.\n c = S[i]\n count = 1\n\n ans += c\n hx = \"\"\n while count:\n rem = count % 16\n if rem < 10:\n hx += chr(48 + rem)\n else:\n hx += chr(97 + rem - 10)\n count //= 16\n ans += hx\n\n ans = ans[::-1] # reversing the answer.\n\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def encryptString(self, S):\n # code here"
}
|
eJylVO1Kw0AQ9Ifga5T4T4owB6L4r28hWJHc5e7y1UuaJmkaUXwIfV+vQqqV7uUwGwKBsDO7O7P7fv55dXH2HQ+X9uPxJUhM2dTB/SzA0oTBfBbIrpSiltFz0dTDr3Bp3pYmeJ3P/iRwKoM7ckQklaYSNRQkIggHRL/rtm1Tb6p1WZhVnqVJrJWMBKcbsGjCokqLrhEjQYoMOVYwKFBijQob1GjQYosOO/Tu8uMkzfKVKUqKsbS4xuLnlie1fLFXZ4tDELjhgprJIahMuqNTj0NY35fiCzkXIoqkVErrOE6SNM0ygo9lLGUJi5lmikkWMcE4G7HWQZt1tambdtvtqJmgt0p3VvHWKl9bB1TWCf9TLuTOApyex8i6FFMMV4wWfkwgHAxiAodU+w/PSZXj/cJLFMGnT4979KZ/Guvpzo721GkIL8v9XiTPPYLvHg1FCvepFpC3/di53sex8FT1hCF6pR2XDbihbtsw65M+dwDeDYBPH9df0+lyTQ==
|
704,704
|
Brain Game
|
2 players A andB taketurns alternatively to play a game in which they have N numbers on a paper. In one turn, a player can replace one of the numbers by any of its factor (except for 1 & the number itself).The player who is unable to make a move looses the game. Find the winner of the game if A starts the game and both play optimally.
Examples:
Input:
nums = [5, 7, 3]
Output:
B
Explanation:
Since all the numbers are prime,
so A will not be able to make the first move.
Input:
nums = [2, 4, 7, 11]
Outptut:
A
Explanation:
In the first move A will replace 4
by 2, so the numbers will become [2, 2, 7, 11]
now B will not be able to make a move since all
the remaining numbers can only be divided by 1
or the number itself.
Constraints
1 <= N <= 1000
1 <= nums[i] <= 1000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public boolean brainGame(int[] nums)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n int n = Integer.parseInt(br.readLine().trim());\n String s = br.readLine().trim();\n String[] S = s.split(\" \");\n int[] nums = new int[n];\n for(int i = 0; i < n; i++){\n nums[i] = Integer.parseInt(S[i]);\n }\n Solution ob = new Solution();\n boolean ans = ob.brainGame(nums);\n if(ans)\n System.out.println(\"A\");\n else \n System.out.println(\"B\"); \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730475971,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public boolean brainGame(int[] nums)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"brainGame(self, nums)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n = int(input())\n nums = list(map(int, input().split()))\n ob = Solution()\n ans = ob.brainGame(nums)\n if ans:\n print(\"A\")\n else:\n print(\"B\")\n",
"solution": "class Solution:\n def brainGame(self, nums):\n a = [0]*1005\n # Calculating the maximum number of consecutive prime factors for each number from 2 to 1000\n for i in range(2, 1001):\n for j in range(2*i, 1001, i):\n # Updating the value in the array to store the maximum number of consecutive prime factors\n a[j] = max(a[j], 1 + a[i])\n x = 0\n # XORing the maximum number of consecutive prime factors for each number in the given list\n for i in range(len(nums)):\n x = x ^ a[nums[i]]\n # If the result of XOR operation is 0, return False, otherwise return True\n if x == 0:\n return False\n return True\n",
"updated_at_timestamp": 1730475971,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef brainGame(self, nums):\n\t\t# Code here"
}
|
eJydk8FKxDAQhj3oe/zEmyySmaTtxJs+hWDFg/bgpe6hC4Is+BD6vv7ZLVKxhWZLfwjpP9MvM5PP8++ri7PDc3/JxcOHe+23u8HdwEnb81W3gevet93z0L08ve2G8etd27v9Bn/92vYpJYj3fiHsdi5MPEMRUKGBCCRAuEjQAE0l/6/avoYhE0CWyGcRQiZvkJIV08d8AO+RT57jmacknMwSoQKtoA1CceXEK5kjVVE1xTPkAgj3mVqE+1LEJISKmJQSOQ/TMLtBPVSh8UBsJXnVHwdkLBNVUxUVqUApJRTLafQZfUaf0Wf0GX1Gn9Fn9Fn5nJXOU3E7mqLBk1Nipu3Bv/7M3ajJhWL7VvRvth5H2NNZf1FXj9EyRlEjxzu6GnzJ6faPX9c/pd1xCw==
|
715,457
|
Find Kth permutation
|
Given two integersN(1<=N<=9) andK. Find the kth permutation sequence of first N natural numbers. Return the answer instringformat.
Examples:
Input:
N =
4, K = 3
Output:
1324
Explanation:
Permutations of first 4 natural numbers:
1234,1243,1324,1342,1423,1432.....
So the 3rd permutation is 1324.
Input:
N = 3, K = 5
Output:
312
Explanation:
Permutations of first 3 natural numbers:
123,132,213,231,312,321.
So the 5th permutation is 312.
Constraints:
1 <= N <= 9
1 <= K <= N!
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1685961077,
"func_sign": [
"public static String kthPermutation(int n,int k)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n//Position this line where user code will be pasted.\n\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[] a = IntArray.input(br, 2);\n \n Solution obj = new Solution();\n String res = obj.kthPermutation(a[0],a[1]);\n \n System.out.println(res);\n \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730482835,
"user_code": "class Solution {\n public static String kthPermutation(int n,int k) {\n // code here\n }\n}\n \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1685961077,
"func_sign": [
"kthPermutation(self, n : int, k : int) -> str"
],
"initial_code": "# Initial Template for Python 3\n# Position this line where user code will be pasted.\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n N, K = map(int, input().split())\n obj = Solution()\n res = obj.kthPermutation(N, K)\n print(res)\n print(\"~\")\n",
"solution": "from typing import List\n\n\nclass Solution:\n def solve(self, n, k, fact, nums):\n # base case, if n=0, return an empty string\n if n == 0:\n return \"\"\n\n # calculate the current position in the permutation\n c = k // fact[n - 1] + 1\n\n result = \"\"\n for i in range(len(nums)):\n # decrement c if nums[i] is 0\n c -= (nums[i] == 0)\n\n # if c reaches 0 and nums[i] is 0, update nums[i] to 1,\n # add the current number to the result, and break out of the loop\n if c == 0 and nums[i] == 0:\n nums[i] = 1\n result += str(i + 1)\n break\n\n # recursively call the function with n decreased by 1, k modulo fact[n-1],\n # and updated nums array to find the next number in the permutation\n return result + self.solve(n - 1, k % fact[n - 1], fact, nums)\n\n def kthPermutation(self, n: int, k: int) -> str:\n # generate the factorials of numbers from 1 to n\n fact = [1] * (n + 1)\n for i in range(1, n + 1):\n fact[i] = i * fact[i - 1]\n\n nums = [0] * n\n\n # call the solve function to find the kth permutation\n s = self.solve(n, k - 1, fact, nums)\n\n return s\n",
"updated_at_timestamp": 1730482835,
"user_code": "from typing import List\nclass Solution:\n def kthPermutation(self, n : int, k : int) -> str:\n # code here\n \n"
}
|
eJy1lEFOxDAMRVnAPaKsRyixHSeZkyBRxAK6YBNm0ZGQEGgOARdkxy1I2kKpwGlB0FWr6j//fNs5HD+/nhz1z9lLfjm/1zdpt+/0VmnbJKus3ijd3u3aq669vrzdd9PPxybph42aK6KsACTHPkRRiQwhGEEeg2dHCN8Wht7qImPQVknYJKfYNIkUUC0ABEcD4QMlWYuqL9mkoMggSO7QebAUOfSYBZM+o0y2ycqDGTwLWCZw6AfOJ+Tk/2srytkFWqUD7+H3QxAs0bpWOirfAtaWo1kjkZxFglpC42HGoIrJ5bC8xTGhsa2Ajn5RxPxzFf7LswzLnqssJL5Gyz9Vl8mpbG2kvBocpEbnCJbX1eZxxxXrOrkpd4AAKzdZNiQB5kGudVhzY+ZDoNYPdA4PvAvII/7i6fQNV2W+ow==
|
703,465
|
Delete array elements which are smaller than next or become smaller
|
Given an array arr[] and a number k. The task is to delete k elements that are smaller than the next element (i.e., we delete arr[i] if arr[i] < arr[i+1]) or become smaller than the next because the next element is deleted.
Examples:
Input:
arr[] = [20, 10, 25, 30, 40], k = 2
Output:
[25, 30, 40]
Explanation:
First we delete 10 because it follows arr[i] < arr[i+1]. Then we delete 20 because 25 is moved next to it and it also starts following the condition.
Input:
arr[] = [3, 100, 1] , k = 1
Output:
[100, 1]
Constraints:
2 ≤ arr.size() ≤ 10**6
1 ≤ k < arr.size()
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static ArrayList<Integer> deleteElement(int arr[], int k)"
],
"initial_code": "// Initial Template for Java\n\n// Initial Template for Java\n\n/*package whatever //do not write package name here */\nimport java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n\n int k = Integer.parseInt(br.readLine());\n // Create Solution object and find closest sum\n Solution ob = new Solution();\n ArrayList<Integer> ans = ob.deleteElement(arr, k);\n for (int i : ans) System.out.print(i + \" \");\n System.out.println();\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "Main",
"solution": "// User function Template for Java\nclass Solution {\n // Function for finding maximum and value pair\n public static ArrayList<Integer> deleteElement(int arr[], int k) {\n int n = arr.length;\n Stack<Integer> s = new Stack<>();\n // Push the first element into the stack\n s.push(arr[0]);\n // Counter to keep track of deletions\n int count = 0;\n // Iterating over the elements of the array\n for (int i = 1; i < n; i++) {\n // Removing elements from the stack if they are smaller than the current\n // element and the count of removed elements is less than k\n while (!s.isEmpty() && s.peek() < arr[i] && count < k) {\n s.pop();\n count++;\n }\n // Pushing the current element into the stack\n s.push(arr[i]);\n }\n // Creating an ArrayList to store the elements in the stack\n ArrayList<Integer> result = new ArrayList<>();\n while (!s.isEmpty()) {\n result.add(0, s.pop());\n }\n // Returning the result as ArrayList\n return result;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n // Function for finding maximum and value pair\n public static ArrayList<Integer> deleteElement(int arr[], int k) {\n // Complete the function\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"deleteElement(self,arr,k)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n k = int(input().strip())\n ob = Solution()\n ans = ob.deleteElement(arr, k)\n print(*ans)\n tc -= 1\n print(\"~\")\n # No extra blank line is needed here. Adjusted to 4 spaces per indentation\n",
"solution": "class Solution:\n\n def deleteElement(self, arr, k):\n stack = []\n count = 0 # Counter to keep track of deletions\n\n # Pushing the first element of the array into the stack\n stack.append(arr[0])\n\n # Iterating over the elements of the array\n for i in range(1, len(arr)):\n # Removing elements from the stack if they are smaller than the current element\n # and the count of removed elements is less than k\n while stack and stack[-1] < arr[i] and count < k:\n stack.pop()\n count += 1\n # Pushing the current element into the stack\n stack.append(arr[i])\n\n # Return the stack as the final result\n return stack\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def deleteElement(self,arr,k):\n # Code here"
}
|
eJytVEtOw0AMZYE4x9OsK2TP5DecBIkgFpAFm9BFKlVCIA4B12DH/bAnEU2rmUkq0UXVz7P9PnY+Lr9+ri7C6/ZbPty9mud+uxvMDQy3fUmwBEdgQkGoCRW1vTMbmG6/7R6H7unhZTdMBeUc9N725m2Dk36wqODgIV9sos0fINqCieAJzTQI41AXiLLMLRNdl+riw4SKRYkCtfBu1Abf9kVK/xEq3lAcsGDpWsPJuwyQX5zycJwmL9AjXLT3TI6qq4LSRlVnKJ/g4qQZHEhzARGg8kSlalVn1CEB1SnfUwXJdC2pEI1HdShBZagUlaPKI2HKiXnrqqPDvdCT9MKG1kLUhsVIbbtKqma4eCZWg9NYxLpGbWykOaWXP1mQvycmPSib6jr+H21xuILijL1R7IrFmc7n/+7HcyQjZELiNSnVJLbbyXeibEAjdgItPjT8OtV+QfYYUnXudYeS5Zhie5/zdI2lmQvNprDs/cH4+8/rXx3nwgU=
|
704,778
|
Number of Integer solutions
|
You are given a positive integer N and you have to find the number of non negative integral solutions to a+b+c=N.
Examples:
Input:
N =
10
Output:
66
Explanation:
There are 66 possible solutions.
Input:
N =
20
Output:
231
Explanation:
There are 231 possible solutions.
Constraints:
1 <= N <= 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static Long noOfIntSols(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.noOfIntSols(N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static Long noOfIntSols(Long N) {\n Long ans = ((N + 1) * (N + 2)) / 2;\n return ans;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static Long noOfIntSols(Long N) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"noOfIntSols(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\n ob = Solution()\n print(ob.noOfIntSols(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to calculate the number of integer solutions\n def noOfIntSols(self, N):\n\n # Formula to calculate the number of integer solutions\n ans = ((N + 1) * (N + 2)) // 2\n\n # Return the answer\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def noOfIntSols(self, N):\n # code here"
}
|
eJy1VMuqwjAQdSH4GyVrkWaaqb33E9y5E4y40C7cVBcVhMsVP0L/17FJtWqmTX2EQAPpOZMz5ySH7mnc6xRjMqLF9E+sss02F7+BkDqjKfqBSHebdJGny/l6m9vNSGd72vzvB/cIYBExg5BhOVgo2h/kdeHiotJE8VMOls2AS6oQb+WfOUkmTTp6DZ0BQmJokZGJvDwZgbM5RhDvgRHidAIqAr16Avb3IVY77N0kuBVJvCw1glUJuuf38xuL3kDRAUWghqyaitYtaWwCJ7FTTzUJb2pTGMqGtLH+ecZQRcOW0nT8fXGX0l4a6QOts6RirFr8fAW9StdcN44XiNW7rWxI3Xernv4dyqYDNwWBYa9rstafSbHTvod86eiVhLV/Iu1NUGhfLHve2XFwBvFILL4=
|
702,831
|
Minimum Steps
|
You are standing at the bottom of a staircase with exactly n stairs. You can take steps of size p or q at a time. Your task is to calculate the minimum number of steps required to reach exactly the n-th stair using only these step sizes. You can take any combination of steps of size p and q to achieve this.
Examples:
Input:
n = 15, p = 2, q = 3
Output:
3
Explanation:
One way to reach 15 stairs is by taking three steps of size 8, 4, and 3 (i.e.,
2 + 2 + 2 + 3 + 3 + 3
). Another way is
9, 3, 3
. Both take exactly 3 steps.
Input:
n = 19, p = 4, q = 3
Output:
2
Explanation:
To reach 19 stairs, you can take two steps: one of size 16 and one of size 3 (
4 + 4 + 4 + 4 + 3
). This totals to 19 stairs in 2 steps.
Constraints:
1 ≤ n, p, q ≤ 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int moves(int n, int p, int q)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim()); // Inputting the test cases\n while (t-- > 0) {\n StringTokenizer stt = new StringTokenizer(br.readLine());\n\n long n = Long.parseLong(stt.nextToken());\n long p = Long.parseLong(stt.nextToken());\n long q = Long.parseLong(stt.nextToken());\n\n Solution obj = new Solution();\n System.out.println(obj.moves((int)n, (int)p, (int)q));\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n // Method to calculate the minimum moves to reach the nth stair\n public int moves(int n, int p, int q) {\n // If there are no stairs, return 0 moves\n if (n == 0) return 0;\n // Array to store visited stairs\n int[] visited = new int[n + 1];\n Arrays.fill(visited, -1); // Mark all as unvisited\n Queue<int[]> qSteps = new LinkedList<>();\n qSteps.offer(new int[] {0, 0}); // Start from stair 0 with 0 moves\n visited[0] = 0;\n // BFS traversal to find the minimum moves\n while (!qSteps.isEmpty()) {\n int[] curr = qSteps.poll();\n int currStair = curr[0];\n int currSteps = curr[1];\n // Move p steps\n if (currStair + p <= n && visited[currStair + p] == -1) {\n visited[currStair + p] = currSteps + 1;\n qSteps.offer(new int[] {currStair + p, currSteps + 1});\n }\n // Move q steps\n if (currStair + q <= n && visited[currStair + q] == -1) {\n visited[currStair + q] = currSteps + 1;\n qSteps.offer(new int[] {currStair + q, currSteps + 1});\n }\n // If we reached exactly the nth stair, return the minimum moves\n if (visited[n] != -1) {\n return visited[n];\n }\n }\n // If it's not possible to reach exactly the nth stair\n return -1;\n }\n}\n",
"updated_at_timestamp": 1730468917,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Method to calculate the minimum moves to reach the nth stair\n public int moves(int n, int p, int q) {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"moves(self, n, p, q)"
],
"initial_code": "# Initial Template for Python 3\n\ndef main():\n T = int(input())\n while T > 0:\n sz = [int(x) for x in input().strip().split()]\n n, p, q = sz[0], sz[1], sz[2]\n ob = Solution()\n print(ob.moves(n, p, q))\n print(\"~\")\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "from collections import deque\n\n\nclass Solution:\n\n def moves(self, n, p, q):\n # Edge case when there are no stairs\n if n == 0:\n return 0\n\n # List to track the minimum steps required to reach each stair\n visited = [-1] * (n + 1) # Initialize all stairs as unvisited\n\n # Queue for BFS (stores stair number and steps taken to reach it)\n q_steps = deque([(0, 0)]) # Start at stair 0 with 0 steps\n visited[0] = 0 # Mark the starting point as visited\n\n # Perform BFS\n while q_steps:\n curr_stair, curr_steps = q_steps.popleft()\n\n # Try moving to the next stair using power p\n if curr_stair + p <= n and visited[curr_stair + p] == -1:\n visited[curr_stair + p] = curr_steps + 1\n q_steps.append((curr_stair + p, curr_steps + 1))\n\n # Try moving to the next stair using power q\n if curr_stair + q <= n and visited[curr_stair + q] == -1:\n visited[curr_stair + q] = curr_steps + 1\n q_steps.append((curr_stair + q, curr_steps + 1))\n\n # If we've reached exactly n stairs, return the steps taken\n if visited[n] != -1:\n return visited[n]\n\n # Return -1 if it is not possible to reach exactly n stairs\n return -1\n",
"updated_at_timestamp": 1730468917,
"user_code": "#User function Template for python3\n\nclass Solution:\n def moves(self, n, p, q):\n # Your code goes here \n \n"
}
|
eJydk00OgjAQhV3oPZqu0dCWongSEzEulIUbZAEJifHnEHpfKW1JUF75mUVpQufrzHvT1/zzXMzq2JXVZn+jlzQrcrollMUp81WQSEW9buKUeoQmZZac8uR8vBa5Ob2sjj+qv3ePtBk6WdagQO0hggOCqYITAVNFFYE7nRG9gQzUgM03n6n5XDYrRPS0oEUUzi6QiNKKADOl5v5nc2uiUlmQUMWotnRNnc3xpjJN0zUYdus+5HxNhdOnSLxvdJDs0YjZ7VQOMASuBnLYkFeglFpDJdiAZ+QE/BqOZ8npdTjZbGOzy23pDxxKDBmgk0Mm67fsH5qmhMN79QVwKpbZ
|
706,297
|
Construct list using given q XOR queries
|
Given a list s that initially contains only a single value 0. There will be q queries of the following types:
Examples:
Input:
q = 5
queries[] = {{0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5}}
Output:
1 2 3 7
Explanation:
[0] (initial value)
[0 6] (add 6 to list)
[0 6 3] (add 3 to list)
[0 6 3 2] (add 2 to list)
[4 2 7 6] (XOR each element by 4)
[1 7 2 3] (XOR each element by 5)
The sorted list after performing all the queries is [1 2 3 7].
Input:
q = 3
queries[] = {{0, 2}, {1, 3}, {0, 5}}
Output:
1 3 5
Explanation:
[0] (initial value)
[0 2] (add 2 to list)
[3 1] (XOR each element by 3)
[3 1 5] (add 5 to list)
The sorted list after performing all the queries is [1 3 5].
0
≤ x
≤10**9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1616471777,
"func_sign": [
"public static ArrayList<Integer> constructList(int q, int[][] queries)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass IntMatrix {\n public static int[][] input(BufferedReader br, int n, int m) throws IOException {\n int[][] mat = new int[n][];\n\n for (int i = 0; i < n; i++) {\n String[] s = br.readLine().trim().split(\" \");\n mat[i] = new int[s.length];\n for (int j = 0; j < s.length; j++) mat[i][j] = Integer.parseInt(s[j]);\n }\n\n return mat;\n }\n\n public static void print(int[][] m) {\n for (var a : m) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n }\n\n public static void print(ArrayList<ArrayList<Integer>> m) {\n for (var a : m) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n }\n}\n\nclass IntArray {\n public static int[] input(BufferedReader br, int n) throws IOException {\n String[] s = br.readLine().trim().split(\" \");\n int[] a = new int[n];\n for (int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]);\n\n return a;\n }\n\n public static void print(int[] a) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n\n public static void print(ArrayList<Integer> a) {\n for (int e : a) System.out.print(e + \" \");\n System.out.println();\n }\n}\n\nclass GFG {\n 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 q;\n q = Integer.parseInt(br.readLine());\n\n int[][] queries = IntMatrix.input(br, q, 2);\n\n Solution obj = new Solution();\n ArrayList<Integer> res = obj.constructList(q, queries);\n\n IntArray.print(res);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "IntArray",
"solution": "class Solution {\n public static ArrayList<Integer> constructList(int q, int[][] queries) {\n // Store cumulative Bitwise XOR\n int xor = 0;\n\n // Initialize final list to return\n ArrayList<Integer> ans = new ArrayList<>();\n\n // Perform each query\n for (int i = queries.length - 1; i >= 0; i--) {\n if (queries[i][0] == 0) {\n ans.add(queries[i][1] ^ xor);\n } else {\n xor ^= queries[i][1];\n }\n }\n\n // The initial value of 0\n ans.add(xor);\n\n // Sort the list\n Collections.sort(ans);\n\n // Return final list\n return ans;\n }\n}",
"updated_at_timestamp": 1730267587,
"user_code": "\nclass Solution {\n public static ArrayList<Integer> constructList(int q, int[][] queries) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616471777,
"func_sign": [
"constructList(self, q : int, queries : List[List[int]]) -> List[int]"
],
"initial_code": "class IntMatrix:\n\n def __init__(self) -> None:\n pass\n\n def Input(self, n, m):\n matrix = []\n # matrix input\n for _ in range(n):\n matrix.append([int(i) for i in input().strip().split()])\n return matrix\n\n def Print(self, arr):\n for i in arr:\n for j in i:\n print(j, end=\" \")\n print()\n\n\nclass IntArray:\n\n def __init__(self) -> None:\n pass\n\n def Input(self, n):\n arr = [int(i) for i in input().strip().split()] # array input\n return arr\n\n def Print(self, arr):\n for i in arr:\n print(i, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n q = int(input())\n queries = IntMatrix().Input(q, 2)\n obj = Solution()\n res = obj.constructList(q, queries)\n IntArray().Print(res)\n print(\"~\")\n",
"solution": "from typing import List\n\n\nclass Solution:\n\n def constructList(self, q: int, queries: List[List[int]]) -> List[int]:\n # Store cumulative Bitwise XOR\n xr = 0\n\n # Initialize final list to return\n ans = []\n\n # Perform each query\n for i in range(len(queries) - 1, -1, -1):\n if queries[i][0] == 0:\n ans.append(queries[i][1] ^ xr)\n else:\n xr ^= queries[i][1]\n\n # The initial value of 0\n ans.append(xr)\n\n # Sort the list\n ans.sort()\n\n # Return final list\n return ans\n",
"updated_at_timestamp": 1730267587,
"user_code": "\nfrom typing import List\n\nclass Solution:\n def constructList(self, q : int, queries : List[List[int]]) -> List[int]:\n # code here\n \n"
}
|
eJy9VLFOxDAMZWDgK5BViQ2hOE6cli9B4hAD3MBSGA4JCYH4CPhfbKehBWE4hsM9Re45dt97dvKy/3Z0sGd2dijO+WN3M97db7pT6HA1YliNAVCXqEuSv4B0YX3tLRr0Patb1Bu6Y+jWD3frq836+vL2fjOVS8DQwwCIgASYYDU+r8bu6Ri+fDNqFQzNtPDQzEKRUubSDxbpC+dEES3SzAA3M8zNjEUzA95MI9xMI6WZUW3msENmZOKSIQ6sCDkDZY6BU+nlI4iUUxiAc8gcSuLqIQWca3uSmM55FhvNj+ZH88l8Mj8FrwMSY0gCh4ClheS2oNY0RUzkKrsBqDB6+3TV2WSMZQHDMslEJOtSsiak7AArQBEUneyJ9hOYRWHm7GGMNhhVjmk+sUJOH/NY2zhNKsKwUNByplGzLEyzsmiJWGaq6E21hOSJ8pA8ScpLVUlypdVqXoOCS/aDq5/qJld6i/OEy/MkIZ9aiDTv9ernCVz43AgfK05qOfXSok1h6f9AHb9nr+lO1ted2237852IP1+KktlGRmbHHfaFxFtrrAr7Y6gAd8HCpfC3mQ/b92PXF0HZ0U2gEv/rrf7NufrtYCmH+WhdvJ68A+W6NRQ=
|
704,794
|
Compare two fractions
|
You are given a string str containing two fractions a/b and c/d, compare them and return the greater. If they are equal, then return "equal".
Examples:
Input:
str = "5/6, 11/45"
Output:
5/6
Explanation:
5/6=0.8333 and 11/45=0.2444, So 5/6 is greater fraction.
Input:
str = "8/1, 8/1"
Output:
equal
Explanation:
We can see that both the fractions are same, so we'll return a string "equal".
Input:
str = "10/17, 9/10"
Output:
9/10
Explanation:
10/17 = 0.588 & 9/10 = 0.9, so the
greater
fraction is "9/10".
Constraints:
0<=a,c<=10**3
1<=b,d<=10**3
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"String compareFrac(String str)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n\n Solution ob = new Solution();\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String str = read.readLine().trim();\n String ans = ob.compareFrac(str);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n String compareFrac(String str) {\n // Initializing variables for numerators and denominators\n int a = 0, b = 0, c = 0, d = 0;\n\n // Regular expression to match and extract numerical values from string\n Pattern pattern = Pattern.compile(\"([0-9]+)/([0-9]+), ([0-9]+)/([0-9]+)\");\n Matcher matcher = pattern.matcher(str);\n\n if (matcher.find()) {\n a = Integer.parseInt(matcher.group(1));\n b = Integer.parseInt(matcher.group(2));\n c = Integer.parseInt(matcher.group(3));\n d = Integer.parseInt(matcher.group(4));\n }\n\n // Comparing fractions and determining the result\n if (a * d > b * c) {\n return a + \"/\" + b;\n } else if (b * c > a * d) {\n return c + \"/\" + d;\n } else {\n return \"equal\";\n }\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n\n String compareFrac(String str) {\n // Code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"compareFrac(self, str)"
],
"initial_code": "# Initial Template for Python 3\nimport re\n\nif __name__ == '__main__':\n ob = Solution()\n t = int(input())\n for _ in range(t):\n str = input()\n print(ob.compareFrac(str))\n print(\"~\")\n",
"solution": "class Solution:\n\n def compareFrac(self, str):\n # Initializing variables for numerators and denominators\n a = b = c = d = 0\n\n # Regular expression to match and extract numerical values from string\n pattern = r\"([0-9]+)/([0-9]+), ([0-9]+)/([0-9]+)\"\n match = re.search(pattern, str)\n\n if match:\n a, b, c, d = int(match.group(1)), int(match.group(2)), int(\n match.group(3)), int(match.group(4))\n\n # Comparing fractions and determining the result\n if a * d > b * c:\n return \"{}/{}\".format(a, b)\n elif b * c > a * d:\n return \"{}/{}\".format(c, d)\n else:\n return \"equal\"\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def compareFrac (self, str):\n \n # code here\n \n"
}
|
eJytVMFOwzAM5YD4jijniMbdeui+BAkjhKAHJBSG1EpIaBMfAZ/JjQ/ASZMmG0maVeuhtVPnOe/Z8efl9+/VhXlufsi4/eDPajv0fMP4CpWsQDB6oYIKpJSCQdW2Lbnk6BX67cwaFReMd+/b7rHvnu5fh94CdW/DwwuqvUYxu/cBgPH4TrAgc60ja8Hqao2Kdrjcfs98phz+Sv+fCNEXVUPhjfbXlK7RKz6vswrSWhhj+9UYPQK1yaVVF7yfyBPIZwOj4JaJdOBGCkujWLoYNtiOgAwOJLcetdAsxwhCwCSLkWMApVX1AVEcXWpTxEbKPJCNLMCZrU2KTnAJ5wTOgh22Sni0xXof6TTVbplg492BRZdnKmb69kznLRDDmIA4csoSSmp+MGP/jVXE0sEas2K9UtT4FHauqZkZdaN7+lh1uCmGhZOa7+6+rv8AybT/yQ==
|
703,025
|
Rotate a Matrix
|
Given a N xN2D matrix Arr representing an image. Rotate the image by 90 degrees (anti-clockwise direction). You need to do this in place. Note that if you end up using an additional array, you will only receive the partial score.
Examples:
Input:
N = 3
Arr[][] = {{1, 2, 3}
{4, 5, 6}
{7, 8, 9}}
Output:
3 6 9
2 5 8
1 4 7
Explanation:
The given matrix is rotated
by 90 degree in anti-clockwise direction.
Input:
N = 4
Arr[][] = {{1, 2, 3, 4}
{5, 6, 7, 8}
{9, 10, 11, 12}
{13, 14, 15, 16}}
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Explanation:
The given matrix is rotated
by 90 degree in anti-clockwise direction.
Constraints:
1 ≤ N≤ 1000
1 ≤ Arr[i][j]≤ 1000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"void rotateMatrix(int arr[][], int n)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.io.*;\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n PrintWriter out = new PrintWriter(System.out);\n int tc = Integer.parseInt(br.readLine().trim());\n while (tc-- > 0) {\n String[] inputLine;\n int n = Integer.parseInt(br.readLine().trim());\n int[][] arr = new int[n][n];\n inputLine = br.readLine().trim().split(\" \");\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n arr[i][j] = Integer.parseInt(inputLine[i * n + j]);\n }\n }\n\n new Solution().rotateMatrix(arr, n);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n out.print(arr[i][j] + \" \");\n }\n }\n out.println();\n \nout.println(\"~\");\n}\n out.flush();\n }\n}",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1730272842,
"user_code": "//User function Template for Java\n\nclass Solution {\n void rotateMatrix(int arr[][], int n) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"rotateMatrix(self,arr, n)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n n = int(input())\n inputLine = list(map(int, input().strip().split()))\n arr = [[0 for j in range(n)] for i in range(n)]\n for i in range(n):\n for j in range(n):\n arr[i][j] = inputLine[i * n + j]\n ob = Solution()\n ob.rotateMatrix(arr, n)\n for i in range(n):\n for j in range(n):\n print(arr[i][j], end=\" \")\n print()\n tc -= 1\n print(\"~\")\n",
"solution": "class Solution:\n def rotateMatrix(self, arr, n):\n # Consider all squares one by one\n for x in range(n//2):\n # Consider elements in group\n # of 4 in current square\n for y in range(x, n-x-1):\n # Store current cell in\n # temp variable\n temp = arr[x][y]\n\n # Move values from right to top\n arr[x][y] = arr[y][n - 1 - x]\n\n # Move values from bottom to right\n arr[y][n - 1 - x] = arr[n - 1 - x][n - 1 - y]\n\n # Move values from left to bottom\n arr[n - 1 - x][n - 1 - y] = arr[n - 1 - y][x]\n\n # Assign temp to left\n arr[n - 1 - y][x] = temp\n",
"updated_at_timestamp": 1730272842,
"user_code": "#User function Template for python3\nclass Solution:\n \n def rotateMatrix(self,arr, n):\n # code here"
}
|
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
|
712,305
|
Postfix to Prefix Conversion
|
You are given a string that represents the postfix form of a valid mathematical expression. Convert it to its prefix form.
Examples:
Input:
ABC/-AK/L-*
Output:
*-A/BC-/AKL
Explanation:
The above output is its valid prefix form.
Input:
ab+
Output:
+ab
Explanation:
The above output is its valid prefix form.
3<=post_exp.length()<=16000
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1666246868,
"func_sign": [
"static String postToPre(String post_exp)"
],
"initial_code": "// Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.math.*;\nimport java.io.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n Scanner sc = new Scanner(System.in);\n int T = sc.nextInt();\n while (T-- > 0) {\n sc.nextLine();\n String s = sc.next();\n Solution obj = new Solution();\n String ans = obj.postToPre(s);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\n\nclass Solution {\n static boolean isOperator(char x) {\n\n switch (x) {\n case '+':\n case '-':\n case '/':\n case '*':\n return true;\n }\n return false;\n }\n static String postToPre(String post_exp) {\n // code here\n Stack<String> s = new Stack<String>();\n\n // length of expression\n int length = post_exp.length();\n\n // reading from right to left\n for (int i = 0; i < length; i++) {\n\n // check if symbol is operator\n if (isOperator(post_exp.charAt(i))) {\n\n // pop two operands from stack\n String op1 = s.peek();\n s.pop();\n String op2 = s.peek();\n s.pop();\n\n // concat the operands and operator\n String temp = post_exp.charAt(i) + op2 + op1;\n\n // Push String temp back to stack\n s.push(temp);\n }\n\n // if symbol is an operand\n else {\n\n // push the operand to the stack\n s.push(post_exp.charAt(i) + \"\");\n }\n }\n\n // concatenate all strings in stack and return the\n // answer\n String ans = \"\";\n for (String i : s) ans += i;\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n static String postToPre(String post_exp) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1667286244,
"func_sign": [
"postToPre(self, post_exp)"
],
"initial_code": "# Initial Template for Python 3\n# Position this line where user code will be pasted.\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n postfix = input()\n ob = Solution()\n res = ob.postToPre(postfix)\n print(res)\n print(\"~\")\n",
"solution": "#Back-end complete function Template for Python 3\n\nfrom collections import deque\nclass Solution:\n # Convert prefix to Postfix expression\n def postToPre(self, post_exp):\n def isOperator(x):\n return x in '+-/*'\n \n stack = deque()\n # length of expression\n length = len(post_exp)\n # reading from right to left\n for i in range(length):\n # check if symbol is operator\n if isOperator(post_exp[i]):\n # pop two operands from stack\n op1 = stack.pop()\n op2 = stack.pop()\n # concat the operands and operator\n temp = post_exp[i] + op2 + op1 \n # Push string temp back to stack\n stack.append(temp)\n # if symbol is an operand\n else:\n # push the operand to the stack\n stack.append(post_exp[i])\n # stack contains only the Postfix expression\n return stack.pop()\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def postToPre(self, post_exp):\n # Code here"
}
|
eJydlMlOAkEQhj0Yn4PMyVTRVrh6g1lAWdXZiCNmNrbDyAGSAaPxIfR97VFECNQwYU6ddNfXVf//93ycf9HF2c/nXsrF46sySWaLuXJdUipe4gcYQkRKuaTE6SwO53H0/LKYrw8QoB+EkZe8e4nyVi7t1qbLVbZPgqkWmMJyRX7A1FdrKmk6oFFv0ICFUL0x4AEa6QbIehTIALAmSNUQdEOSckC6bOPmttlqd7q9u/sHEwmEZTuuRHOtWWiT4zJMP4AwoniIYjQGtjlBYYTxEEZjrrVqDWV3KECVamnA66SqoGkMJZuITMsGdFzRJ7YdNMGySThun50qGwqGOBqLyRSQTQ6CnGw9/WSaozugVJ6E1J6a0KI2Sv15Mzui2ysCO9Tq5gLMuaHC02OxZ+vx+LE86ev2GyriMcf6dTcpYG9yxN7/nNj5pEKUPIBJ8nVxgB1xTtNk1/1tpXNzB5hykT45GXKvcviQbpySQ+2Ps/cL3IBz3kGW/+Pxf/q8+gaMm9+8
|
701,242
|
Number of pairs
|
Given two positive integer arrays arr and brr, find the number of pairs such thatx**y > y**x(raised to power of) where x is an element from arr and y is an element from brr.Examples :
Examples:
Input:
arr[] = [2, 1, 6], brr[] = [1, 5]
Output:
3
Explanation:
The pairs which follow x
**y
> y
**x
are: 2
**1
> 1
**2
, 2
**5
> 5
**2
and 6
**1
> 1
**6 .
Input:
arr[] = [2 3 4 5], brr[] = [1 2 3]
Output:
5
Explanation:
The pairs which follow x
**y
> y
**x
are:
2
**1
> 1
**2
, 3
**1
> 1
**3
, 3
**2
> 2
**3
, 4
**1
> 1
**4
, 5
**1
> 1
**5
.
Expected Time Complexity:
O((N + M)log(N)).
Expected Auxiliary Space:
O(1).
Constraints:
1 ≤ arr.size(), brr.size() ≤ 10**5
1 ≤ brr[i], arr[i] ≤ 10**3
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1723359974,
"func_sign": [
"public long countPairs(int x[], int y[], int M, int N)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass Main {\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 x[] = new int[str.length];\n for (int i = 0; i < str.length; i++) x[i] = Integer.parseInt(str[i]);\n str = (br.readLine()).trim().split(\" \");\n int[] y = new int[str.length];\n for (int i = 0; i < str.length; i++) {\n y[i] = Integer.parseInt(str[i]);\n }\n System.out.println(new Solution().countPairs(x, y, x.length, y.length));\n }\n }\n}\n",
"script_name": "Main",
"solution": "//Back-end complete function Template for Java\nclass Solution {\n // Function to count number of pairs such that x^y is greater than y^x.\n long countPairs(int x[], int y[], int M, int N) {\n // Array to store counts of 0, 1, 2, 3 and 4 present in array y.\n int[] freq = new int[5];\n // Storing the count in array if y[i]<5.\n for (int i = 0; i < N; i++) {\n if (y[i] < 5) freq[y[i]]++;\n }\n // Sorting y[] so that we can do binary search on it later on.\n Arrays.sort(y);\n long ans = 0;\n // Taking every element of x[] and counting pairs with it.\n for (int i = 0; i < M; i++) {\n // If x[i] is 0, then there can't be any value in y[]\n // such that x[i]^y[val]>y[val]^x[i].\n if (x[i] == 0) continue;\n // If x[i] is 1, then the number of pair is equal to\n // number of zeroes in y[].\n if (x[i] == 1) {\n ans = ans + (long)freq[0];\n continue;\n }\n // We work with logic that if x<y then x^y is greater than y^x.\n // Finding number of elements in y[] with value greater than x.\n // binary() gets address of first element greater than x[i] in y[].\n int ind = binary(M, N, x[i], y);\n // Updating number of pairs.\n // If we have reached here, then x must be greater than 1.\n // Increasing number of pairs for y=0 and y=1 .\n ans = ans + (long)(N - ind) + (long)freq[0] + (long)freq[1];\n // Decreasing number of pairs for exception where x=2\n // and (y=4 or y=3).\n if (x[i] == 2) ans = ans - (long)freq[3] - (long)freq[4];\n // Increasing number of pairs for exception where x=3 and y=2.\n if (x[i] == 3) ans = ans + (long)freq[2];\n }\n // returning number of pairs.\n return ans;\n }\n\n // Function to find upper bound using binary search.\n public int binary(int M, int N, int x, int[] y) {\n int high = N - 1, low = 0;\n int ans = high + 1;\n while (high >= low) {\n int mid = (high + low) / 2;\n if (y[mid] > x) {\n ans = mid;\n high = mid - 1;\n } else\n low = mid + 1;\n }\n return ans;\n }\n}",
"updated_at_timestamp": 1727776457,
"user_code": "//Back-end complete function Template for Java\nclass Solution {\n // Function to count number of pairs such that x^y is greater than y^x.\n public long countPairs(int x[], int y[], int M, int N) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1616602787,
"func_sign": [
"countPairs(self,arr,brr)"
],
"initial_code": "# Initial Template for Python 3\n\nimport atexit\nimport io\nimport sys\nimport bisect\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 # M, N = map(int, input().strip().split())\n a = list(map(int, input().strip().split()))\n b = list(map(int, input().strip().split()))\n ob = Solution()\n print(ob.countPairs(a, b))\n # code here\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n\n def count(self, x, b, N, NoOfb):\n # If x is 0, then there can't be any value in b[]\n # such that x^b[val]>b[val]^x.\n if (not x):\n return x\n\n # If x is 1, then the number of pair is equal to number of zeroes in b[].\n if (x == 1):\n return NoOfb[0]\n\n # We work with logic that if x<y then x^y is greater than y^x.\n # Finding number of elements in b[] with value greater than x.\n\n # bisect.bisect_right() gets address of first\n # element greater than x in b[].\n index = bisect.bisect_right(b, x)\n ans = 0\n if (index < N and b[index] > x):\n # Updating number of pairs.\n ans += N - index\n\n # If we have reached here, then x must be greater than 1.\n # Increasing number of pairs for b=0 and b=1 .\n ans += (NoOfb[0] + NoOfb[1])\n\n # Decreasing number of pairs for exception where x=2 and (b=4 or b=3).\n if (x == 2):\n ans -= NoOfb[3] + NoOfb[4]\n\n # Increasing number of pairs for exception where x=3 and b=2.\n if (x == 3):\n ans += NoOfb[2]\n\n # returning number of pairs.\n return ans\n\n # Function to count number of pairs such that x^y is greater than y^x.\n def countPairs(self, arr, brr):\n M = len(arr)\n N = len(brr)\n # Array to store counts of 0, 1, 2, 3 and 4 present in array b.\n NoOfb = [0, 0, 0, 0, 0]\n # Storing the count in array if b[i]<5.\n for i in range(N):\n if (brr[i] < 5):\n NoOfb[brr[i]] += 1\n\n # Sorting b[] so that we can do binary search on it later on.\n brr.sort()\n\n total_pairs = 0\n\n # Taking every element of a[] and counting pairs with it.\n for i in range(M):\n total_pairs += self.count(arr[i], brr, N, NoOfb)\n\n # returning number of pairs.\n return total_pairs\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to count number of pairs such that x^y is greater than y^x. \n def countPairs(self,arr,brr):\n #code here"
}
|
eJy1VMtOwzAQ7IHHb4xyrpB3/eZLkAjiAD1wCT20EhJC4iPgdxHr1FFa1W4bVGrVctLueHd2Zz4vvi+vZ/3n7udqNrt/b1665XrV3KKhtiOlFGKM8g27T80czeJtuXhaLZ4fX9erHKPbrvmYYxfFSlgfqxHBvu3Snt9UcHwJhwXAwMLBIwgUqQQV5MnJWyO/MqiWmCshEk5a6eqTVuVyVavGSu4kF2iQHIQWKSFCE7SHIRip18PK/yIcwXl4gtfwUrVGkEb4VIOR+jd8gIQBA7IgBwpgBSawZGbAFuwS8RyghXm5X0MLaxbaVRJnZYu0Ses2+5SCCWNctU90sE1D8P42jfm8to5T4pMEcinIM1njryIHnqqH4vQOQH5ESgP0F2mdUQgUJxOajYUGo0m7HEPVZkx9KmuTUB6sYSAnznFSa17/S1cx623nwInWweHM5jG6xxGHr3oLH/GWWvOLnCQtjIn0itiTROLnUKMfvm5+AdUnwRw=
|
704,946
|
Rectangle Number
|
We are given a N*M grid, print the number of rectangles in it modulo (10**9+7).
Examples:
Input:
N =
2,
M =
2
Output:
9
Explanation:
There are 4 rectangles of size 1 x 1
There are 2 rectangles of size 1 x 2
There are 2 rectangles of size 2 x 1
There is 1 rectangle of size 2 X 2.
Input:
N =
5,
M =
4
Output:
150
Explanation:
There are a total of 150 rectangles.
Constraints:
1 <= N,M <= 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static long rectNum(long N, long M)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n \n long N = Long.parseLong(S[0]);\n long M = Long.parseLong(S[1]);\n\n Solution ob = new Solution();\n System.out.println(ob.rectNum(N,M));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // Function to calculate the number of rectangles\n static long rectNum(long N, long M) {\n // Formula to calculate the number of rectangles\n long ans = ((M * N * (N + 1) * (M + 1)) / 4) % 1000000007;\n // Returning the calculated answer\n return ans;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution {\n static long rectNum(long N, long M) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"rectNum(self, N, M)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, M = map(int, input().split())\n\n ob = Solution()\n print(ob.rectNum(N, M))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find the number of rectangles.\n def rectNum(self, N, M):\n # calculating the number of rectangles using the formula.\n ans = ((M * N * (N + 1) * (M + 1)) // 4) % 1000000007\n # returning the answer.\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def rectNum(self, N, M):\n # code here"
}
|
eJytVMtOxDAM5AD/EeW8QoljxzFfgsQiDtADl7KHroRAIPgH+F/ch3hJNguLD1Fax5OZsdunw9fno4MpTu90c3Yfr/vNdognIeZ1n5NGmNZ1H1chdreb7nLori5utsNyjFEqjflHPfKwCt8QoGCgys2sxwQa1USQxjUQFjARAKRRrtIsBI3QNGwEBhK9Ay0VP7pAQIANSvU4ZNsETVOyXQxj/Z+rpy6SSz817VSVbECAVgcmFwETZ0ELAUcO1eOgKjI1cwwWAz+LcXu6oynWVFMtjETiyUFXj7TKhSSxx2Caq/nBtlY/MQZxleR3oLlLDlwBFgCf1le45e1HcjRu7zv2lZ7+0cP5FyHePFFJOuDYdvftNw6dvxy/AQYqmdo=
|
700,274
|
Find kth element of spiral matrix
|
Given a matrix with n rows and m columns. Your task is to find the kth element which is obtained while traversing the matrix spirally. You need to complete the method findKwhich takes four arguments the first argument is the matrix A and the next two arguments will be n and m denoting the size of the matrix A and then the forth argument is an integer k. The function will return the kth element obtained while traversing the matrix spirally.
Examples:
Input:
n = 4, m = 4, k = 10
A[][] = {{1 2 3 4},
{5 6 7 8},
{9 10 11 12},
{13 14 15 16}}
Output:
13
Explanation:
The spiral order of matrix will look like 1->2->3->4->8->12->16->15->14->13->9->5->6->7->11->10. So the 10th element in this order is 13.
Input:
n = 3, m = 3, k = 4
A[][] = {{1 2 3},
{4 5 6},
{7 8 9}}
Output:
6
Explanation:
The spiral order of matrix will look like 1->2->3->6->9->8->7->4->5. So the 4th element in this order is 6.
Constraints:
1<=n,m<=10**3
1<=k<=n*m
-10**9
<= A[i][j] <= 10**9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int findK(int A[][], int n, int m, int k)"
],
"initial_code": "import java.util.*;\n\nclass Find_Given_Element_Of_Spiral_Matrix \n{\n\tpublic static void main(String args[])\n\t{\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();\n\t\twhile(t > 0)\n\t\t{\n\t\t\tint n = sc.nextInt();\n\t\t\tint m = sc.nextInt();\n\t\t\tint k = sc.nextInt();\n\t\t\tint arr[][] = new int[1000][1000];\n\t\t\tfor(int i=0; i<n; i++)\n\t\t\t{\n\t\t\t\tfor(int j=0; j<m; j++ )\n\t\t\t\t{\n\t\t\t\t\tarr[i][j] = sc.nextInt();\n\t\t\t\t}\n\t\t\t}\n\t\t\tSystem.out.println(new Solution().findK(arr, n, m, k));\n\t\tt--;\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "Find_Given_Element_Of_Spiral_Matrix",
"solution": "None",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution\n{\n /*You are required to complete this method*/\n int findK(int A[][], int n, int m, int k)\n {\n\t// Your code here\t\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1687514176,
"func_sign": [
"findK(self, a, n, m, k)"
],
"initial_code": "# Initial Template for Python 3\n\nfor _ in range(int(input())):\n n, m, k = map(int, input().split())\n a = [\n list(map(int, input().split()))\n for _ in range(n)\n ]\n ob = Solution()\n print(ob.findK(a, n, m, k))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def findK(self, a, n, m, k):\n top = 0 # initialize top index to 0\n left = 0 # initialize left index to 0\n right = m - 1 # initialize right index to m - 1\n bottom = n - 1 # initialize bottom index to n - 1\n # initialize direction to 0 (0: from left to right, 1: from top to bottom, 2: from right to left, 3: from bottom to top)\n direction = 0\n count = 0 # initialize count to 0\n\n AA = [] # initialize an empty list to store the elements in the spiral order\n while top <= bottom and left <= right: # iterate until top index is less than or equal to bottom index and left index is less than or equal to right index\n if direction == 0: # if direction is 0 (from left to right)\n # iterate from left index to right index (inclusive)\n for i in range(left, right + 1):\n # append the element at the current position to the AA list\n AA.append(a[top][i])\n top += 1 # increment top index by 1\n direction = 1 # change direction to 1 for the next iteration\n\n if direction == 1: # if direction is 1 (from top to bottom)\n # iterate from top index to bottom index (inclusive)\n for i in range(top, bottom + 1):\n # append the element at the current position to the AA list\n AA.append(a[i][right])\n right -= 1 # decrement right index by 1\n direction = 2 # change direction to 2 for the next iteration\n\n if direction == 2: # if direction is 2 (from right to left)\n # iterate from right index to left index (inclusive, with step -1)\n for i in range(right, left - 1, -1):\n # append the element at the current position to the AA list\n AA.append(a[bottom][i])\n bottom -= 1 # decrement bottom index by 1\n direction = 3 # change direction to 3 for the next iteration\n\n if direction == 3: # if direction is 3 (from bottom to top)\n # iterate from bottom index to top index (inclusive, with step -1)\n for i in range(bottom, top - 1, -1):\n # append the element at the current position to the AA list\n AA.append(a[i][left])\n left += 1 # increment left index by 1\n direction = 0 # change direction to 0 for the next iteration\n\n # return the kth element in the AA list (0-based indexing)\n return AA[k-1]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findK(self, a, n, m, k):\n # Write Your Code here"
}
|
eJztmMFuHUUQRVnwFaxKXmfQVFX3dF9WfAYSQSzACzYmC0dCQiA+Av6XU6OwsP0meZZt7ChJbMl6U9N+7557q2r815f/fPvVF/u/78QP3/9+8cvVm7fXF9/Yhb++8tX46is/WVhas26bDZsmLvCqm4d5mjfzbr6ZD/NpLgsuB3eFRVo0i26xWQyLaSFLLqdbcmpaNstuuVkOy2kpa1xubi2s8VubtW5tszasTWva31F362E9rfOuuvXN+rA+rcs2Lm9uW9iWtjXbeNebbcO2aZtscHm4jbCRNpqNboNPNWxMG7LJ5ek2w2babDa7zc0mn3ralInLclOY0tRM3bSZhglVShauX7yyi8vf3lz+dH3584+/vr1+p+jQ66s/ufrHK7ulc9/lWw+Etps6U3RDaHuIznZTZmS/obM9RGa7qTKq35DZHqQy36iyIsuKLivCrKXMijQr2qyIs1K4q0dh6VcCloKldUlYGpaIqOjlV4/SmUKkdLR0xHTUdOR09HQE9eRAFPUsINQhqmf9ZnR1hHWUdaR1tHXEddT1VugoxMeOwI7CjsSOxr7HC5kdnR2hvRfkcgSFiO2o7cjtGweityO4o7gjuW+7GyhEdkd3R3hHeUd6R3tHfEd9x+Q+yjbUAcAh4OV0B4JDwcHgcHBAOCR8lsEoBIaLA6Hh4HB4OEBc9Zth4kBxlRXLi5gRLAGWAEuAJVYcCZWASkAloBK+dwcKwRJgCbAEWAIsAZYAS5S5y927vakrg5fDox8mTHGQsDqnvs5L2P06mT2kkT1mwO7XxuxDXexEwOy58mUn4sWB5+XLzoxXRelOvuy54mUn0lVGPitedma6OPBuvPimsBxeFgdKACWAElkhoA4oAZQASgAlgBJAiYISQAmgRKu4UAiUAEoAJYASQAmgBFACKAGU6JUr6oASQAmgBFCioARQAigBlABKbJVACoESQAmgBFACKAGUAEoAJYASo6JKHVACKFFQAigBlABKACWAEkCJWaGmECgBlABKACWAEkAJoARQAiihSn/FvyYsUBIoCZQESgIlgZJASaAkUNKrUVAHlARKAiWBkkBJoCRQEihZUDKqpVAIlARKAiWBkkBJoGQ1nuo81Xr23kNddZ9qP9V/qgFVBwJKFpQESgIlW3UpCoGSQEmgJFASKAmUBEoCJYGSvdoZdUBJoCRQEihZUBIoCZQESgIlt2p8FAIlgZJASaAkUBIoCZQESgIlR3VI6oCSQMmCkkBJoCRQEigJlARKzuqlFAIlgZJASaAkUBIoCZQESgIlVU23uu7xEkavOJgRNMi92d8aECwiJycEhad3MAx2ekTwIY9mxMGbrVF3ep7Ve9zfKodaOzygHW2c+2b/buO88/8jf/GI/Hu1iH17ZIERBtI+BpmGNRRrNtaIrElZA1PcI9ZX4VjhWOFY4VjhWOFYzRqjHDDZ94W/hc+F3zVqxFJEDkQeRC5EPlRPJGK9E6ESoRKhEqHSVmOZmwiVCJW2OpEIiiiKSIpoioiq1wjnJqIrIqxaKsUGKnIvcq9WY54ici9yL3Ivcq9WJ2JC4UVhSeFMYVDhU2FXZa0IHFJPEsLoilobeBGvi9YkzC7cLuwu/K6oEwmFyIaIiGhwIjEiOCI/IkYiTaolUCU43VN0T9E9RfcU3VN0T9E9RffUquOFbz1Kc1Elwf3zI9Wn+Uh11AT86CG8ltsd7oESt3ff+vPHWUqUChR+WIn6xGdtv7X5niXFe2Q4mgw4aw/EUjIsGGPBHws2WXDLgmkWceuChxastOCoham8YLAFny1zcBHbLbhvwYQLXlyw5IIzl3nMhXteZpA/J/lxk+xPHWU8e3DDS12DXtQe9NxiPMmL9xSDrnaehfDaPNNty/mufMoHET32k8j/Nzb3w1/w5DxSYtxbC/tPjI9lifjh76//BXJLeSc=
|
704,854
|
Stepping Numbers
|
A number is called a stepping number if all adjacent digits have an absolute difference of 1, e.g. '321' is a Stepping Number while 421 is not. Given two integers nand m, find the count of all the stepping numbers in the range [n, m].Example 1:
Examples:
Input:
n = 0, m = 21
Output:
13
Explanation:
Stepping no's are 0 1 2 3 4 5
6 7 8 9 10 12 21
Input:
n = 10, m = 15
Output:
2
Explanation:
Stepping no's are 10, 12
Constraints:
0 ≤ N < M ≤ 10**7
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int steppingNumbers(int n, int m)"
],
"initial_code": "//Initial Template for Java\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n \n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0)\n {\n String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n int N = Integer.parseInt(input_line[0]);\n int M = Integer.parseInt(input_line[1]);\n \n Solution ob = new Solution();\n int ans = ob.steppingNumbers(N, M);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n // Function to perform breadth-first search to count stepping numbers\n int bfs(int n, int m, int num) {\n int cnt = 0;\n // Create a queue for BFS\n Queue<Integer> q = new LinkedList<>();\n // Add the first stepping number to the queue\n q.add(num);\n // Perform BFS\n while (!q.isEmpty()) {\n int stepNum = q.poll();\n // If the stepping number is within the range [n, m], increment the count\n if (stepNum <= m && stepNum >= n)\n cnt++;\n // If the current stepping number is 0 or exceeds m, continue to the next iteration\n if (num == 0 || stepNum > m)\n continue;\n // Calculate the next possible stepping numbers by adding or subtracting 1 from the last digit\n int lastDigit = stepNum % 10;\n int stepNumA = stepNum * 10 + (lastDigit - 1);\n int stepNumB = stepNum * 10 + (lastDigit + 1);\n\n // Add the next possible stepping numbers to the queue\n if (lastDigit != 9)\n q.add(stepNumB);\n if (lastDigit != 0)\n q.add(stepNumA);\n }\n // Return the count of stepping numbers within the range [n, m]\n return cnt;\n }\n\n // Function to count the number of stepping numbers within the range [n, m]\n int steppingNumbers(int n, int m) {\n int ans = 0;\n // Perform BFS for each digit from 0 to 9 to count the total number of stepping numbers\n for (int i = 0; i <= 9; i++) {\n ans += bfs(n, m, i);\n }\n // Return the total count of stepping numbers within the range [n, m]\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n int steppingNumbers(int n, int m){\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"steppingNumbers(self, n, m)"
],
"initial_code": "# Initial Template for Python 3\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n ob = Solution()\n N, M = map(int, input().split())\n ans = ob.steppingNumbers(N, M)\n print(ans)\n print(\"~\")\n",
"solution": "from collections import deque\n\n# Function to perform BFS and count stepping numbers\n\n\ndef bfs(n, m, num):\n cnt = 0\n q = deque()\n q.append(num)\n\n # Perform BFS until the queue is empty\n while q:\n stepNum = q.popleft()\n\n # If the current number is within the range [n, m], increment the count\n if stepNum >= n and stepNum <= m:\n cnt += 1\n\n # If the number is 0 or greater than m, continue to the next iteration\n if num == 0 or stepNum > m:\n continue\n\n # Calculate the next stepping numbers by adding or subtracting 1 to the last digit\n lastDigit = stepNum % 10\n stepNumA = stepNum * 10 + (lastDigit - 1)\n stepNumB = stepNum * 10 + (lastDigit + 1)\n\n # If the last digit is not 9, append stepNumB to the queue\n if lastDigit != 9:\n q.append(stepNumB)\n\n # If the last digit is not 0, append stepNumA to the queue\n if lastDigit != 0:\n q.append(stepNumA)\n\n return cnt\n\n\nclass Solution:\n # Function to count the stepping numbers between n and m\n def steppingNumbers(self, n, m):\n ans = 0\n # Iterate through all possible starting digits\n for i in range(10):\n # Accumulate the count of stepping numbers for each starting digit\n ans += bfs(n, m, i)\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def steppingNumbers(self, n, m):\n # code here\n pass\n\n"
}
|
eJydk00KwjAQhV30ICHrIknaJI0nEay40C7c1C5aEETxEHpIdx7B6Y9gxZdQAwMh7TczvDdzje7PaNad5YMuqxPfl1VT8wXjMi+lEIxC5CWPGS+OVbGti93m0NTDP4nKywt9PcdsTGqimPGhGSAVgYmHSwEnVZIyCj25os2cYBS4pgZkr44HVIlB7XYsBKUFnHOtsq49EBao5tCuz5VMIkeNZYakwiI57IwOWIM6fhcdzSLde7uRdgalsy5oNUKVCMxlQPSv6r6RQdPWKSB7BdA+wu340cW/baBU+eh9emL7kQ1ZC/di1FWw9Po2fwHV130v
|
703,327
|
Element with left side smaller and right side greater
|
Given an unsorted array of arr. Find the first element in an array such that all of its left elements are smaller and all right elements of its are greater than it.
Examples:
Input:
arr = [4, 2, 5, 7]
Output:
5
Explanation:
Elements on left of 5 are smaller than 5 and on right of it are greater than 5.
Input:
arr = [11, 9, 12]
Output:
-1
Explanation:
As no element here which we can say smaller in left & greater in right.
Constraints:
3 <= arr.size() <= 10**6
1 <= arr
i
<= 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1619000649,
"func_sign": [
"public int findElement(List<Integer> arr)"
],
"initial_code": "// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n List<Integer> arr = new ArrayList<>();\n String input = br.readLine();\n StringTokenizer st = new StringTokenizer(input);\n while (st.hasMoreTokens()) {\n arr.add(Integer.parseInt(st.nextToken()));\n }\n Solution ob = new Solution();\n int ans = ob.findElement(arr);\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\n\nclass Solution {\n public int findElement(List<Integer> arr) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1619000649,
"func_sign": [
"findElement(self, arr)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n import sys\n input = sys.stdin.read\n data = input().strip().split('\\n')\n t = int(data[0])\n index = 1\n for _ in range(t):\n arr = list(map(int, data[index].split()))\n index += 1\n ob = Solution()\n ans = ob.findElement(arr)\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n\n def findElement(self, arr):\n n = len(arr)\n if n <= 2:\n return -1\n\n # leftMax[i] stores maximum of arr[0..i-1]\n leftMax = [0] * n\n rightMin = [0] * n\n\n leftMax[0] = arr[0]\n # Initialize minimum from right\n rightMin[n - 1] = arr[n - 1]\n\n # Fill leftMax[1..n-1]\n for i in range(1, n):\n leftMax[i] = max(leftMax[i - 1], arr[i])\n\n # Fill rightMin[1..n-1]\n for i in range(n - 2, -1, -1):\n rightMin[i] = min(rightMin[i + 1], arr[i])\n\n # Traverse array from right\n for i in range(1, n - 1):\n # Check if we found a required element\n if leftMax[i - 1] <= arr[i] and rightMin[i + 1] >= arr[i]:\n return arr[i]\n\n # If there was no element matching criteria\n return -1\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findElement(self, arr):\n # code here"
}
|
eJy1U0EKwjAQ9KD/WHKu0k3ag75EsOpBc/ASe2ihIIqP0P+6qbEQ6KY24oZsWpaZZGeS+/SpZ5M21jv62FzEyZR1JVYgsDAIEpRIQOim1IdKH/fnunJlWZhbYcQ1AR+jCIMMZo4MKAcaDChnMJgCgktj98O0DVi2Af5vDBlIm5RNmU05JU44KnEydHjVcSLPNNge06ZbGVZXZajJXFA0M5qcY/y54DPke+WO8A0+iqDXKhWSI2CXx9bXnt0hYGv8RcHx0o+/RFHuUreeQ78Y1Csp/kvTACr00HDoPXXg7WPxAgacgXw=
|
703,098
|
Rotate Bits
|
Given an integer N and an integer D, rotate the binary representation of the integer N by D digits to the left as well as right and return the results in their decimalrepresentation after each of the rotation.Note: Integer N is stored using 16 bits. i.e. 12 will be stored as 0000000000001100.
Examples:
Input:
N = 28, D = 2
Output:
112
7
Explanation:
28 in Binary is: 0000000000011100
Rotating left by 2 positions, it becomes 0000000001110000 = 112 (in decimal).
Rotating right by 2 positions, it becomes 0000000000000111 = 7 (in decimal).
Input:
N = 29, D = 2
Output:
116
16391
Explanation:
29 in Binary is: 0000000000011101
Rotating left by 2 positions, it becomes 0000000001110100 = 116 (in decimal).
Rotating right by 2 positions, it becomes 010000000000111 = 16391 (in decimal).
Constraints:
1 <= N < 2**16
1 <= D <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"ArrayList<Integer> rotate(int N, int D)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while(t-- > 0)\n {\n int n = sc.nextInt();\n int d = sc.nextInt();\n \n Solution ob = new Solution();\n \n ArrayList<Integer> res = ob.rotate (n, d);\n System.out.println(res.get(0));\n System.out.println(res.get(1));\n \n \n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730272840,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n \n ArrayList<Integer> rotate(int N, int D)\n {\n // your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"rotate(self, N, D)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n n, d = input().strip().split(\" \")\n n, d = int(n), int(d)\n\n ob = Solution()\n ans = ob.rotate(n, d)\n\n print(ans[0])\n print(ans[1])\n print(\"~\")\n",
"solution": "class Solution:\n def rotate(self, n, d):\n # Rotation of 16 is the same as rotation of 0\n # Rotation of 17 is the same as rotation of 1\n # and so on.\n d = d % 16\n res = [0, 0]\n\n # Storing n in a temporary variable\n temp = n\n\n # Picking up the leftmost d bits\n mask = (1 << d) - 1\n shift = temp & mask\n temp = temp >> d # Moving the remaining bits to their new location\n temp += shift << (16 - d) # Adding removed bits at the rightmost end\n res[1] = temp # Storing the new number\n\n temp = n\n # Picking the rightmost d bits\n mask = ~((1 << (16 - d)) - 1)\n shift = temp & mask\n temp = temp << d # Moving the remaining bits to their new location\n temp += shift >> (16 - d) # Adding removed bits at the leftmost end\n res[0] = temp # Storing the new number\n\n mask = (1 << 16) - 1\n res[0] = res[0] & mask\n\n return res\n",
"updated_at_timestamp": 1730272840,
"user_code": "#User function Template for python3\n\nclass Solution:\n def rotate(self, N, D):\n # code here"
}
|
eJylk7FOxDAMhhngPazMJ2QnthOzsvEESBQxwA0s5YaehIRAPAS8L0nbO8Hg3ECGqlLsz/bvP5/n3zcXZ/O5va4/d2/hedztp3AFgYZRRZIASdhA2L7uto/T9unhZT+tEfP1GjWMH8MY3jfwl0AYGQjRIZCmwpXATnqKWQt49UmXAl7tmFjA2nEAqRjjMEZWQwcinCIBOQBOhLkGmcXSGSEDqddCu16jHEIhi0C5LyGjqadDi6hLiMlBtAKr1g6i0UGws8dWxkmOIuB1n6K2Dahg9CzU+qKOgiqc8yHMtyH2fFh3bE1Ey8X6RiB/EWylysiUxJOx64TZAL4L2nxz+mGj/qOkOgOZKtIplg9hPOHKoyUWefvequp7mrQA+g1yBa7d5MrKKXcf21GkFf5PrTR3zZeb55bvnH7/dfkD8AaNPg==
|
701,167
|
Gray to Binary equivalent
|
Given an integer number n, which is a decimal representation of Gray Code. Find the binary equivalent of the Gray Code & return the decimal representation of the binary equivalent.
Examples:
Input:
n = 4
Output:
7
Explanation:
Given 4, its gray code = 110.
Binary equivalent of the gray code 110 is 100.
Return 7 representing gray code 100.
Input:
n = 15
Output:
10
Explanation:
Given 15 representing gray code 1000.
Binary equivalent of gray code 1000 is 1111.
Return 10 representing gray code 1111
ie binary 1010.
Constraints:
0 <= n <= 10**9
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public static int grayToBinary(int n)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n\n\tpublic static void main (String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();//testcases\n\t\twhile(t-->0){\n\t\t int n = sc.nextInt();//initializing n\n\t\t \n\t\t Solution obj = new Solution();\n\t\t \n\t\t //calling grayToBinary() function\n\t\t System.out.println(obj.grayToBinary(n));\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}\n",
"script_name": "GFG",
"solution": "//Back-end complete function Template for Java\n\nclass Solution{\n // function to convert a given Gray equivalent n to Binary equivalent.\n public static int grayToBinary(int n) {\n int b=0;\n \n //We use a loop and Right shift n everytime until it becomes 0.\n for(n=n;n>0;n=n>>1)\n //We use XOR operation which stores the result of conversion in b.\n b^=n;\n \n //returning the Binary equivalent.\n return b;\n }\n \n}",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n \n // function to convert a given Gray equivalent n to Binary equivalent.\n public static int grayToBinary(int n) {\n \n // Your code here\n \n }\n \n}\n\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"grayToBinary(self,n)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\n\ndef main():\n T = int(input())\n\n while T > 0:\n n = int(input())\n ob = Solution()\n print(ob.grayToBinary(n))\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # function to convert a given Gray equivalent n to Binary equivalent.\n def grayToBinary(self, n):\n b = 0\n\n # We use a loop and Right shift n everytime until it becomes 0.\n for i in iter(int, 1):\n if (n > 0):\n b = (b ^ n)\n n = n >> 1\n else:\n break\n\n # returning the Binary equivalent.\n return b\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution: \n ##Complete this function\n # function to convert a given Gray equivalent n to Binary equivalent.\n def grayToBinary(self,n):\n ##Your code here"
}
|
eJydVEtKxUAQdKH3CFk/ZHqmv27deQLBiAvNwk18izx4IIqH0PsaYyJEqESc1UDTVdVVPfN2+nF1djKe68vhcvNcP3b7Q19fVDU1HaXMTVfvqro97tv7vn24ezr0Uz0ntqZ7Heovu+p3H7uYrrSGkRDoDjcVLplgv7EFWfKA/PPBEKKZQwJBSFG3FJQhAiUrxuS5AIiszkVYsA8zCXKCCmcyy46dnDgEIKhRclec4kyBoixFhIcwIMDEgEwgtQGdsAcTAbLgq7z0cl2NJEJSsAZG4rdXGelWXbg/XrqVHCw2HFzDxOqInB06Mg233LS/jZ3Fc0DgMVQUEUegdSX+5oVPjkI1wW9nzHj70Wzt2s/P94+lu30//wRhaZPE
|
704,350
|
Smallest number
|
Given two integers s and d. The task is to find the smallest number such that the sum of its digits is s and the number of digits in the number are d. Returna string that is the smallest possible number. If it is not possible then return -1.
Examples:
Input:
s = 9, d = 2
Output:
18
Explanation:
18 is the smallest number
possible with the sum of digits = 9
and total digits = 2.
Input:
s = 20, d = 3
Output:
299
Explanation:
299 is the smallest number
possible with the sum of digits = 20
and total digits = 3.
Constraints:
1 ≤ s ≤ 100
1 ≤ d ≤ 6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1720509346,
"func_sign": [
"public String smallestNumber(int s, int d)"
],
"initial_code": "import java.util.*;\n\nclass GFG {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n int tc = sc.nextInt();\n\n while (tc-- > 0) {\n int s = sc.nextInt();\n int d = sc.nextInt();\n\n Solution obj = new Solution();\n String res = obj.smallestNumber(s, d);\n\n System.out.println(res);\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n public String smallestNumber(int s, int d) {\n if (d * 9 < s) return \"-1\";\n\n int n = (int)Math.pow(10, d - 1);\n int sum = s - 1;\n char temp[] = Integer.toString(n).toCharArray();\n\n int i = d - 1;\n while (i >= 0 && sum > 0) {\n if (sum > 9) {\n temp[i] = '9';\n sum = sum - 9;\n } else {\n int val = temp[i] - '0';\n val = val + sum;\n temp[i] = (char)((int)'0' + val);\n sum = 0;\n }\n i--;\n }\n return new String(temp);\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "\nclass Solution {\n public String smallestNumber(int s, int d) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1720019379,
"func_sign": [
"smallestNumber(self, s, d)"
],
"initial_code": "# Initial Template for Python 3\n\nimport sys\nimport math\ninput = sys.stdin.read\ndata = input().split()\n\nt = int(data[0])\nindex = 1\n\nfor _ in range(t):\n s = int(data[index])\n d = int(data[index + 1])\n index += 2\n ob = Solution()\n print(ob.smallestNumber(s, d))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n\n def smallestNumber(self, s, d):\n # code here\n # declare 10^D as initial number\n # start changing last digit and subtracting from the total sum\n if d * 9 < s:\n return \"-1\"\n\n n = 10**(d - 1)\n sum = s - 1\n temp = list(str(n))\n\n i = d - 1\n while i >= 0 and sum > 0:\n if sum > 9:\n temp[i] = '9'\n sum -= 9\n else:\n val = int(temp[i])\n val += sum\n temp[i] = str(val)\n sum = 0\n i -= 1\n\n return ''.join(temp)\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def smallestNumber(self, s, d):\n # code here\n \n"
}
|
eJxrYJlay8IABhFlQEZ0tVJmXkFpiZKVgpJhTJ6hgqGSjoJSakVBanJJakp8fmkJQrIuJk+pVkcBXYcZLh0GIIBDm6kJTn2WYIBDnyVOB+LSYWigYITLhbj0GJkrGON2HW6L8AYFLn0GpIe5AW6rdHFpsrQkQ48RGZqAroNEFMk6TU3wpww8VpIXJApAwozkBIVPEyTRkwVwpkZosJAcKAqQGMSZKLHqUyA/b4ItJMbG2Cl6ALcwXAI=
|
707,442
|
Find number of closed islands
|
Given a binary matrix mat[][] of dimensions NxM such that 1 denotes land and 0 denotes water. Find the number of closed islands in the given matrix.An island is a 4-directional(up,right,down and left) connected part of 1's.
Examples:
Input:
N = 5, M = 8
mat[][] =
{{0, 0, 0, 0, 0, 0, 0, 1},
{0, 1, 1, 1, 1, 0, 0, 1},
{0, 1, 0, 1, 0, 0, 0, 1},
{0, 1, 1, 1, 1, 0, 1, 0},
{1, 0, 0, 0, 0, 1, 0, 1}}
Output:
2
Explanation:
mat[][] ={{0, 0, 0, 0, 0, 0, 0, 1},
{0,
1, 1, 1, 1,
0, 0, 1},
{0,
1
, 0,
1
, 0, 0, 0, 1},
{0,
1, 1, 1, 1,
0,
1
, 0},
{1, 0, 0, 0, 0, 1, 0, 1}}
There are 2 closed islands. The islands in dark are closed because they are completely surrounded by 0s (water). There are two more islands in the last column of the matrix, but they are not completely surrounded by 0s. Hence they are not closed islands.
Input:
N = 3, M = 3
mat[][] = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}}
Output:
1
Explanation:
mat[][] = {{1, 0, 0},
{0,
1
, 0},
{0, 0, 1}}
There is just a one closed island.
Constraints:
1 ≤ N,M ≤ 500
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1620929709,
"func_sign": [
"public int closedIslands(int[][] matrix, int N, int M)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String[] str = br.readLine().trim().split(\" \");\n int N = Integer.parseInt(str[0]);\n int M = Integer.parseInt(str[1]);\n int[][] matrix = new int[N][M];\n for(int i=0; i<N; i++)\n {\n String[] s = br.readLine().trim().split(\" \");\n for(int j=0; j<M; j++)\n matrix[i][j] = Integer.parseInt(s[j]);\n }\n \n Solution obj = new Solution();\n System.out.println(obj.closedIslands(matrix, N, M));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730268552,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public int closedIslands(int[][] matrix, int N, int M)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1620929709,
"func_sign": [
"closedIslands(self, matrix, N, M)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n N, M = map(int, input().split())\n matrix = []\n for i in range(N):\n nums = list(map(int, input().split()))\n matrix.append(nums)\n obj = Solution()\n print(obj.closedIslands(matrix, N, M))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # DFS Traversal to find the count of\n # island surrounded by water\n def dfs(self, matrix, visited, x, y, n, m, hasCornerCell):\n # If the land is already visited\n # or there is no land or the\n # coordinates gone out of matrix\n # break function as there\n # will be no islands\n if (x < 0 or y < 0 or x >= n or y >= m or visited[x][y] == True or matrix[x][y] == 0):\n return\n\n if (x == 0 or y == 0 or x == n - 1 or y == m - 1):\n if (matrix[x][y] == 1):\n hasCornerCell[0] = True\n\n # Mark land as visited\n visited[x][y] = True\n\n # Traverse to all adjacent elements\n self.dfs(matrix, visited, x + 1, y, n, m, hasCornerCell)\n self.dfs(matrix, visited, x, y + 1, n, m, hasCornerCell)\n self.dfs(matrix, visited, x - 1, y, n, m, hasCornerCell)\n self.dfs(matrix, visited, x, y - 1, n, m, hasCornerCell)\n\n def closedIslands(self, matrix, n, m):\n # Create boolean 2D visited matrix\n # to keep track of visited cell\n\n # Initially all elements are\n # unvisited.\n visited = [[False for i in range(m)] for j in range(n)]\n result = 0\n\n # Mark visited all lands\n # that are reachable from edge\n for i in range(n):\n for j in range(m):\n if ((i != 0 and j != 0 and i != n - 1 and j != m - 1) and matrix[i][j] == 1 and visited[i][j] == False):\n # Determine if the island is closed\n hasCornerCell = [False]\n\n # hasCornerCell will be updated to\n # true while DFS traversal if there\n # is a cell with value '1' on the corner\n self.dfs(matrix, visited, i, j, n, m, hasCornerCell)\n\n # If the island is closed\n if (not hasCornerCell[0]):\n result = result + 1\n\n # Return the final count\n return result\n",
"updated_at_timestamp": 1730268552,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef closedIslands(self, matrix, N, M):\n\t\t#Code here"
}
|
eJztWsFu1EAM5cCHjPbAqULjwNKKL0GiiAP0wGXpoZWQEIiPgC/lxontZie2n58zWSFRrZRGbboTzxvb79nJRPvj6a8/z54cft783v/z9uvm0+72/m7zumzkeie1SN2fyv68/334O573g+OQlHZRClgef9WyWss64jS8EVOM5RF7tBS79gNmWFtdcr6iS4fz5qJsbr7c3ny4u/n4/vP9XQv46nr3/Xq3+XZRIA1DkUFdVu8mD0U/6mLqEOTKpkQMmMuqhlttvsLiYma4xQkX9oIUcGK8YFkRvaD+mIisV25GkuBXWX63RbYNTOOxwU5ZdoP6OabUJspkg4ZiQ7cBHSf42dXMn4SHYjYLWIowhuoDc8r34F5IjgJwx+qgVY8Pz9SmXRGKDHOOKFXBMXuHsUQEw2WmgtZswkHpUR2b0rOqnyKN9PUHyXSyEHEpHFkakixclSvsGyEpobNA44B6qBGjkuLFHpNVcZ3vkiQFGYcJjwmXCZ8Jp0TnnQsJVLJ44m4SID1OVMaxS/rloeaigIMIwqDKxt8BaJfEudAlbRZDl8TueFqXJA6pLw087ZLBHasGmxag2zObdMnYH8xh1wZlzIngRaKCoZaBd0l2ZKJcWIULqzIGRkuLoKEhosxUMaDMGVZmxA0XIRKN9KNODZP8oeFsDtWww0oz7PK8BDFw/UjqWXRkD/3zdebl01ZGKZDW6MVkuqDvX+Iv6zq2o0Ev9KP4BCjFZ42QlOtt8jEK0f+to48ezy9vplp9sIKsahixasCTlnD0yWbyOI7biupwzVQUOxIpiogoyL0LJtIozuspjzUiAI1uMxzjNmHiroHpkqqH4QOFiCoeO6mzl9ljzbAtwxYlxwQHMcS3BZ5oAZiQPkZ3WNk/WHA5wkR8sI5tI9RgiyU6xlMNus4F4VbyCs/U6Cz03YY39klwNl71PBYg0zZF9B0qoE20AodkwrjolCgXpjDzSXlB4RASMckZdpgWN+lcLGYyexxmCTDsYMaYO0Au5wW5d1f8exhWJ8HFmOSYXlIv9iIao/pMj80qkdza4+st/Czgrrkj8lZBYJJ+eUlflj1EnkxAy4Vme4+XWa57D1Q2q6TT9x4A24XE+kkMabjRMEkgGs4mUQ07tDTDLtFLEOuUvXX38U+7D9/IjhfW7YcYbCyhdftB4jZhnsv2o9blN79TXr+KVwOQjFFMDJ7/+9dKOkSLbIbn9QXsY9/EPGOsZoMhoMwZVmZkDQG2C0lE0g87NUwSiIazSVTDDi3NsEv0EsQ6Ze8cHoKyZps9Bf2/r5+YRgH9jX7/pGAjF+uU8xadOpxP/QLK2nMAde053nBpz+kyvQTyvJpOp+e8+/n8L/04O14=
|
714,246
|
Shortest XY distance in Grid
|
Given a N*M grid of characters 'O', 'X', and 'Y'. Find the minimumManhattandistance between aX and aY.ManhattanDistance :| row_index_x - row_index_y | + | column_index_x - column_index_y |
Examples:
Input:
N = 4, M = 4
grid = {{X, O, O, O}
{O, Y, O, Y}
{X, X, O, O}
{O, Y, O, O}}
Output:
1
Explanation:
{{X, O, O, O}
{O, Y, O, Y}
{X,
X
, O, O}
{O,
Y
, O, O}}
The shortest X-Y distance in the grid is 1.
One possible such X and Y are marked in bold
in the above grid.
Input:
N = 3, M = 3
grid = {{X, X, O}
{O, O, Y}
{Y, O, O}}
Output:
2
Explanation:
{{X,
X
, O}
{O, O,
Y
}
{Y, O, O}}
The shortest X-Y distance in the grid is 2.
One possible such X and Y are marked in bold
in the above grid.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1678795965,
"func_sign": [
"static int shortestXYDist(ArrayList<ArrayList<Character>> grid, int N,\n int M)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n\n int N = Integer.parseInt(S[0]);\n int M = Integer.parseInt(S[1]);\n\n ArrayList<ArrayList<Character>> grid = new ArrayList<>();\n\n for (int i = 0; i < N; i++) {\n ArrayList<Character> col = new ArrayList<>();\n String S1[] = read.readLine().split(\" \");\n for (int j = 0; j < M; j++) {\n col.add(S1[j].charAt(0));\n }\n grid.add(col);\n }\n\n Solution ob = new Solution();\n System.out.println(ob.shortestXYDist(grid, N, M));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\n\nclass Solution {\n static int shortestXYDist(ArrayList<ArrayList<Character>> grid, int N,\n int M) {\n int[][] dist = new int[N][M];\n\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n dist[i][j] = 1000000000;\n }\n }\n\n // check top and left\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n if (grid.get(i).get(j) == 'X')\n dist[i][j] = 0;\n else {\n if (i > 0)\n dist[i][j] = Math.min(dist[i][j], dist[i - 1][j] + 1);\n if (j > 0)\n dist[i][j] = Math.min(dist[i][j], dist[i][j - 1] + 1);\n }\n }\n }\n\n // check bottom and right\n for (int i = N - 1; i >= 0; i--) {\n for (int j = M - 1; j >= 0; j--) {\n if (grid.get(i).get(j) == 'X')\n dist[i][j] = 0;\n else {\n if (i < N - 1)\n dist[i][j] = Math.min(dist[i][j], dist[i + 1][j] + 1);\n if (j < M - 1)\n dist[i][j] = Math.min(dist[i][j], dist[i][j + 1] + 1);\n }\n }\n }\n\n int ans = 1000000000;\n\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n if (grid.get(i).get(j) == 'Y') ans = Math.min(ans, dist[i][j]);\n }\n }\n\n return ans;\n }\n};",
"updated_at_timestamp": 1730482463,
"user_code": "// User function Template for Java\n\nclass Solution {\n static int shortestXYDist(ArrayList<ArrayList<Character>> grid, int N,\n int M) {\n //code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1678795965,
"func_sign": [
"shortestXYDist(self, grid, N, M)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, M = map(int, input().split())\n grid = []\n for i in range(N):\n ch = list(map(str, input().split()))\n grid.append(ch)\n\n ob = Solution()\n print(ob.shortestXYDist(grid, N, M))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def shortestXYDist(self, grid, N, M):\n dist = [[float('inf')] * M for _ in range(N)]\n\n # check top and left\n for y in range(N):\n for x in range(M):\n if grid[y][x] == 'X':\n dist[y][x] = 0\n else:\n if y > 0:\n dist[y][x] = min(dist[y][x], dist[y - 1][x] + 1)\n if x > 0:\n dist[y][x] = min(dist[y][x], dist[y][x - 1] + 1)\n\n # check bottom and right\n for y in range(N - 1, -1, -1):\n for x in range(M - 1, -1, -1):\n if grid[y][x] == 'X':\n dist[y][x] = 0\n else:\n if y < N - 1:\n dist[y][x] = min(dist[y][x], dist[y + 1][x] + 1)\n if x < M - 1:\n dist[y][x] = min(dist[y][x], dist[y][x + 1] + 1)\n\n # return mininum distance\n ans = 1e9\n\n for i in range(N):\n for j in range(M):\n if grid[i][j] == 'Y':\n ans = min(ans, dist[i][j])\n\n return ans\n",
"updated_at_timestamp": 1730482463,
"user_code": "#User function Template for python3\n\nclass Solution:\n def shortestXYDist(self, grid, N, M):\n # code here "
}
|
eJzVVktuwjAQ7YJNbzHyGqE4bgD1Emxt1RWLNotuXBZBqlSBeoj2YN1xHAJ2rPgzTkIqRBMp8mfmzfh5nuOvyc/h/u788N+68fRJ3tRmW5FHIFSqAgqpOKz0K5VpgGiaXI8K16AeJVMg5cemfKnK1/X7tjKYuVR7qchuCm6gOcy1Mw9CtTt2xpoJfyYdnyHxaQY0ay01hpoc9NNsWwaonZgRyj1L0QsTYeEBYWEJSx+GB7gOzdHIQX4IRnTv0pkXSOYLWLgQ3KPTC9B0RTS8U1bB7EBSKdQfjjjRrHlmWcpfXO6fQ34qbC1ZDCbla0obWwImaQbMEKc10JwZA1MYo0y7x/9fmnYX5amT2soBFSHpeDAGV5bfsKrqyYa49iqSkupFe5wHe+B0nhwpYFYjqZHCjVTZmGPQwN3WX+pvJHS+Za06rln8onvW8/fsCE+vt3E=
|
703,172
|
Length of the longest substring
|
Given a string S, find the length of the longest substring without repeating characters.
Examples:
Input:
S = "geeksforgeeks"
Output:
7
Explanation:
Longest substring is
"eksforg".
Input:
S = "abdefgabef"
Output:
6
Explanation:
Longest substring are
"abdefg" , "bdefga" and "defgab".
Expected Time Complexity:
O(|S|).
Expected Auxiliary Space:
O(K)where K is constant.
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int longestUniqueSubsttr(String S)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n public static void main(String args[])throws IOException\n {\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while(t-- > 0)\n {\n String s = read.readLine().trim();\n\n Solution ob = new Solution();\n System.out.println(ob.longestUniqueSubsttr(s));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n public int longestUniqueSubstring(String s) {\n int n = s.length();\n int cur_len = 1; // lenght of current subsing\n int max_len = 1; // result\n int prev_index; // previous index\n int i;\n int visited[] = new int[26];\n for (i = 0; i < 26; i++) visited[i] = -1;\n\n visited[s.charAt(0) - 'a'] = 0;\n for (i = 1; i < n; i++) {\n prev_index = visited[s.charAt(i) - 'a'];\n if (prev_index == -1 || i - cur_len > prev_index) cur_len++;\n else {\n if (cur_len > max_len) max_len = cur_len;\n\n cur_len = i - prev_index;\n }\n\n visited[s.charAt(i) - 'a'] = i;\n }\n if (cur_len > max_len) max_len = cur_len;\n return max_len;\n }\n}\n",
"updated_at_timestamp": 1731265183,
"user_code": "//User function Template for Java\nclass Solution{\n int longestUniqueSubsttr(String S){\n \n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"longestUniqueSubsttr(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().strip()\n\n ob = Solution()\n print(ob.longestUniqueSubsttr(s))\n print(\"~\")\n",
"solution": "class Solution:\n # Function to find the length of the longest substring with unique characters.\n def longestUniqueSubsttr(self, S):\n # Getting the length of the input string.\n n = len(S)\n\n # Variable to store the current length of unique substring.\n cur_len = 1\n\n # Variable to store the maximum length of unique substring.\n max_len = 1\n\n # Variable to store the previous index of each character in the string.\n prev_index = -1\n\n # Dictionary to store the visited characters and their indices.\n visited = {}\n\n # Initializing the dictionary with -1 for all characters.\n for i in S:\n visited[i] = -1\n\n # Storing the index of the first character in the visited dictionary.\n visited[S[0]] = 0\n\n # Iterating through the string starting from the second character.\n for i in range(1, n):\n # Getting the previous index of the current character.\n prev_index = visited[S[i]]\n\n # Checking if the current character has not appeared before or\n # if the previous occurrence of the current character is not part of the currently considered substring.\n if prev_index == -1 or i - cur_len > prev_index:\n # Increasing the length of the current substring.\n cur_len += 1\n # If the previous occurrence of the current character is part of the currently considered substring.\n else:\n # Checking if the current length of the substring is greater than the maximum length.\n if cur_len > max_len:\n # Updating the maximum length of the substring.\n max_len = cur_len\n\n # Calculating the length of the new substring considering the previous occurrence of the current character.\n cur_len = i - prev_index\n\n # Storing the index of the current character in the visited dictionary.\n visited[S[i]] = i\n\n # Checking if the current length of the substring is greater than the maximum length.\n if cur_len > max_len:\n # Updating the maximum length of the substring.\n max_len = cur_len\n\n # Returning the maximum length of the unique substring.\n return max_len\n",
"updated_at_timestamp": 1731265183,
"user_code": "#User function Template for python3\n\nclass Solution:\n def longestUniqueSubsttr(self, S):\n # code here"
}
|
eJy9VMlOwzAU5ID4C6TI4lgh0iW03Nj3fSsQhOzEJKGt49pOnRaB+hHlf7HogU0vJRFg5WDLmXmTN5M3nH6Zm5l6W81Zs7l5RBHjiUJLFrJdhlHJQjTl1FPUv4sT9X717DL0VLK+vE88n1LfIxCwBgPNQwgAqwAwQkAIKBFDiDKA4Fq3qM6prB2zgEolEyKViFigIxUalKCcYmXOXogFNlxCAsSNrBbfB2H00Gp3WMy7Qqqkp9P+APosB2DqaipUP4lijqVvGA3hIPV6hHXGN3n5YGXLK6tr6xubW9s7u3v7B4dHxyenZ+cXl82r6wW7XKnWnMV6A6jmQK5MMiYzoh9VjjPxG1rt+k9qFqKuQjlzXehXgxqH8wn6C1Mhad8TmbfTpMhEyEjEp5n2H/GYQAFOhQKm5nXrdjT/CnUADk0=
|
710,136
|
Maximum trains for which stoppage can be provided
|
Youare given n-platform and two main running railway tracks for both directions. Trains that need to stop at your station must occupy one platform for their stoppage and the trains which need not stop at your station will run away through either of the main track without stopping. Now, each train has three values first arrival time, second departure time, and the third required platform number. We are given m such trains you have to tell the maximum number of trains for which you can provide stoppage at your station.
Examples:
Input:
n = 3, m = 6
Train no.| Arrival Time |Dept. Time | Platform No.
1 | 10:00 | 10:30 | 1
2 | 10:10 | 10:30 | 1
3 | 10:00 | 10:20 | 2
4 | 10:30 | 12:30 | 2
5 | 12:00 | 12:30 | 3
6 | 09:00 | 10:05 | 1
Output:
Maximum Stopped Trains = 5
Explanation
:If train no. 1 will left
to go without stoppage then 2 and 6 can
easily be accommodated on platform 1.
And 3 and 4 on platform 2 and 5 on platform 3.
1 <= N <= 100
1 <= M <= 10**4
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1655116246,
"func_sign": [
"int maxStop(int n, int m, ArrayList<ArrayList<Integer>> trains)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while(t-- > 0){\n \tString [] str = br.readLine().trim().split(\" \");\n \tint n = Integer.parseInt(str[0]);\n \tint m = Integer.parseInt(str[1]);\n \tArrayList<ArrayList<Integer>> trains = new ArrayList<>();\n \tfor(int i = 0; i < m; i++) {\n \t\tstr = br.readLine().trim().split(\" \");\n \t\tArrayList<Integer> arr = new ArrayList<>();\n \t\tfor(int j = 0; j < 3; j++)\n \t\t\tarr.add(Integer.parseInt(str[j]));\n \t\ttrains.add(arr);\n \t}\n \tSolution obj = new Solution();\n \tint res = obj.maxStop(n, m, trains);\n \tSystem.out.println(res);\n }\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution{\n\tint maxStop(int n, int m, ArrayList<ArrayList<Integer>> trains) {\n \n Collections.sort(trains,(a,b)->a.get(1)-b.get(1));\n \n int dep[]=new int[n+1];\n int ans=0;\n \n for(int i=0;i<m;i++){\n int at=trains.get(i).get(0);\n int dt=trains.get(i).get(1);\n int p=trains.get(i).get(2);\n \n if(dep[p]<=at){\n ans++;\n dep[p]=dt;\n }\n }\n return ans;\n }\n}",
"updated_at_timestamp": 1730481078,
"user_code": "//User function Template for Java\n\nclass Solution{\n\tint maxStop(int n, int m, ArrayList<ArrayList<Integer>> trains) {\n // Write your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1647417203,
"func_sign": [
"maxStop(self, n, m, trains)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n n, m = map(int, input().split())\n trains = []\n for i in range(m):\n trains.append([int(i) for i in input().split()])\n print(Solution().maxStop(n, m, trains))\n print(\"~\")\n",
"solution": "class Solution():\n # Function to find maximum number of stops\n def maxStop(self, n, m, trains):\n # Creating a list of platforms\n platforms = [[] for i in range(n)]\n # Sorting trains based on their platforms\n for i in range(m):\n platforms[trains[i][2]-1].append(trains[i])\n ans = 0\n # Iterating over each platform\n for platform in platforms:\n # Sorting trains on each platform based on their departure time\n platform.sort(key=lambda x: x[1])\n prevStart = -1\n # Checking if the train can stop at the platform\n for train in platform:\n if train[0] >= prevStart:\n ans += 1\n prevStart = train[1]\n return ans\n",
"updated_at_timestamp": 1730481078,
"user_code": "class Solution():\n def maxStop(self, n, m, trains):\n #your code goes here"
}
|
eJzFlLFOwzAQhhmQeI2T5wrZ57uU9hHYuiEBYoAMLKVDKiFVRTwEfV/sS+y0VS8RSSQy2JYTf//vP2d/Xx9WN1fyPNyHwePOvK8328oswbintYPQWHA29mYGpvzclK9V+fbysa3az77Cy/0MTtciYFzLcSl3I1BF+IwgKCKwh+QVkoei3cgCUHrHgFy79DZKhddk44RnII4zigypMtTKhBaFhonvha+717F8jnUJm+xjwg9xfYQPAUsmWSanlLeh4FnFz1X3dXnVglknJC/h9/2FuSIYa6RH0bZbxJMkXSoElEHes/SkHwKreCG4axaLMc8dBppip6bKST5w3CGrJXCh3OE/630Qt5j+IF24UGjwjdJ7aOy4U9MRgR2TgeOzFMbEcJwojIw0OpvQ2pTXAP/1Hnj+uf0Fb0QGOg==
|
701,222
|
Floor in a Sorted Array
|
Given a sorted array arr[] of size n without duplicates, and given a value x. Floor of x is defined as the largest element k in arr[] such that k is smaller than or equal to x. Find the index of k(0-based indexing).
Examples:
Input:
n = 7, x = 0 arr[] = {1,2,8,10,11,12,19}
Output:
-1
Explanation:
No element less than 0 is found. So output is "
-1
".
Input:
n = 7, x = 5 arr[] = {1,2,8,10,11,12,19}
Output:
1
Explanation:
Largest Number less than 5 is
2 (i.e k = 2)
, whose index is
1
(0-based indexing).
Constraints:
1 ≤ n ≤ 10**7
1 ≤ arr[i] ≤ 10**18
0 ≤ x ≤**
arr[n-1]
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1730214554,
"func_sign": [
"static int findFloor(int[] arr, int k)"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.util.*;\nimport java.util.HashMap;\n\n//Position this line where user code will be pasted.\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n\n int k = Integer.parseInt(br.readLine());\n // Create Solution object and find closest sum\n Solution ob = new Solution();\n int ans = ob.findFloor(arr, k);\n\n System.out.print(ans);\n\n System.out.println(); // New line after printing the results\n }\n }\n}\n",
"script_name": "Main",
"solution": "class Solution {\n\n // Function to find floor of x in sorted array arr\n // Returns index of floor element or -1 if it doesn't exist\n static int findFloor(int[] arr, int x) {\n int n = arr.length;\n\n int low = 0, high = n - 1;\n int ans = -1;\n\n while (low <= high) {\n int mid = low + (high - low) / 2;\n\n if (arr[mid] <= x) {\n ans = mid; // Potential floor found\n low = mid + 1; // Search in the right half\n } else {\n high = mid - 1; // Search in the left half\n }\n }\n\n return ans; // Index of largest element <= x, or -1 if no floor\n }\n}",
"updated_at_timestamp": 1730465940,
"user_code": "class Solution {\n\n static int findFloor(int[] arr, int k) {\n // write code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1730214554,
"func_sign": [
"findFloor(self,arr,k)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n arr = list(map(int, input().strip().split()))\n k = int(input().strip())\n ob = Solution()\n ans = ob.findFloor(arr, k)\n print(ans)\n tc -= 1\n",
"solution": "class Solution:\n # Function to find floor of k in sorted array arr\n # Returns index of floor element or -1 if it doesn't exist\n def findFloor(self, arr, k):\n n = len(arr)\n\n # Edge case: if k is smaller than the smallest element\n if arr[0] > k:\n return -1\n\n low, high = 0, n - 1\n ans = -1\n\n while low <= high:\n mid = low + (high - low) // 2\n\n if arr[mid] == k:\n return mid # Exact match found\n elif arr[mid] < k:\n ans = mid # Potential floor found\n low = mid + 1 # Search in the right half\n else:\n high = mid - 1 # Search in the left half\n\n return ans # Index of largest element <= k, or -1 if no floor\n",
"updated_at_timestamp": 1730465940,
"user_code": "class Solution:\n #User function Template for python3\n \n #Complete this function\n def findFloor(self,arr,k):\n #Your code here\n "
}
|
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
|
701,420
|
Egg Dropping Puzzle
|
You are given N identical eggs and you have access to a K-floored building from1toK.
Examples:
Input:
N
= 1
, K
= 2
Output:
2
Explanation:
1. Drop the egg from floor 1. If it
breaks, we know that f = 0.
2. Otherwise, drop the egg from floor 2.
If it breaks, we know that f = 1.
3. If it does not break, then we know f = 2.
4. Hence, we need at minimum 2 moves to
determine with certainty what the value of f is.
Input:
N = 2, K = 10
Output:
4
Constraints:
1<=N<=200
1<=K<=200
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1731014139,
"func_sign": [
"static int eggDrop(int n, int k)"
],
"initial_code": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GfG {\n\n public static void main(String[] args) throws IOException {\n\n // Reading input using BufferedReader class\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n // Reading total test cases\n int t = Integer.parseInt(br.readLine().trim());\n while (t-- > 0) {\n\n // Reading number of eggs from a separate line\n int n = Integer.parseInt(br.readLine().trim());\n\n // Reading number of floors from a separate line\n int k = Integer.parseInt(br.readLine().trim());\n\n // Calling eggDrop() method of class Solution\n System.out.println(new Solution().eggDrop(n, k));\n }\n }\n}\n",
"script_name": "GfG",
"solution": "class Solution {\n // Function to find minimum number of attempts needed in\n // order to find the critical floor.\n static int eggDrop(int n, int k) {\n // creating a 2D table where entry eggFloor[i][j] will represent\n // minimum number of trials needed for i eggs and j floors.\n int eggFloor[][] = new int[n + 1][k + 1];\n int res;\n int i, j, x;\n\n // we need one trial for one floor and 0 trials for 0 floors.\n for (i = 1; i <= n; i++) {\n eggFloor[i][1] = 1;\n eggFloor[i][0] = 0;\n }\n\n // we always need j trials for one egg and j floors.\n for (j = 1; j <= k; j++) eggFloor[1][j] = j;\n\n // filling rest entries in table using optimal substructure property.\n for (i = 2; i <= n; i++) {\n for (j = 2; j <= k; j++) {\n eggFloor[i][j] = Integer.MAX_VALUE;\n for (x = 1; x <= j; x++) {\n res = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);\n if (res < eggFloor[i][j]) eggFloor[i][j] = res;\n }\n }\n }\n\n // returning the result in eggFloor[n][k].\n return eggFloor[n][k];\n }\n}",
"updated_at_timestamp": 1731014139,
"user_code": "class Solution {\n // Function to find minimum number of attempts needed in\n // order to find the critical floor.\n static int eggDrop(int n, int k) {\n // Your code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1731014139,
"func_sign": [
"eggDrop(self,n, k)"
],
"initial_code": "# Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n\n# Contributed by : gokul\n\nif __name__ == '__main__':\n test_cases = int(input().strip())\n for cases in range(test_cases):\n # Reading the number of eggs from a separate line\n n = int(input().strip())\n\n # Reading the number of floors from a separate line\n k = int(input().strip())\n\n # Creating an instance of Solution and calling eggDrop method\n ob = Solution()\n print(ob.eggDrop(n, k))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to find minimum number of attempts needed in\n # order to find the critical floor.\n def eggDrop(self, n, k):\n dp = []\n for i in range(n+1):\n temp = [-1]*(k+1)\n dp.append(temp)\n\n def solve(n, k):\n if n == 0 or k == 0:\n return 0\n if n == 1:\n return k\n if k == 1:\n return 1\n\n if dp[n][k] != -1:\n return dp[n][k]\n\n mn = float(\"inf\")\n for i in range(1, k+1):\n tmp = max(solve(n-1, i-1), solve(n, k-i))\n if tmp < mn:\n mn = tmp\n dp[n][k] = mn + 1\n\n return dp[n][k]\n\n return solve(n, k)\n",
"updated_at_timestamp": 1731326151,
"user_code": "#User function Template for python3\n\nclass Solution:\n \n #Function to find minimum number of attempts needed in \n #order to find the critical floor.\n def eggDrop(self,n, k):\n # code here"
}
|
eJydU7sOwjAMZOiHVJkrZEeEIr4EiSAG6MASOhQJCYH4CPhFNv6B1lBSHldIM0QZcue7s32MzteoJ2dyKR/TnVq5fFOocazYOiayzpBKYpVt82xRZMv5elM8PgytO1in9kn8itIVqrwAbNQGYwBiADKdSnEFY2gMKjQlKjWhxcQX1JgCWGq6hxhcjDvlIeE34oRlDSAgTQ3NrcqxYS+frCUhAhwD5P67kr/tCRYx19uA45UfuC1+gjAFqt+wpcWW/rnVKOj7PPqV80TBY/MRzHvQgS4lpmf7oLO6/bNT/wZvQ4R0
|
704,114
|
Minimum Points To Reach Destination
|
Given a m*n grid with each cell consisting of a positive, negative, or zero integer. We can move across a cell only if we have positive points. Whenever we pass through a cell, points in that cell are added to our overall points, the task is to find minimum initial points to reach cell (m-1, n-1) from (0, 0) by following these certain set of rules :1. From a cell (i, j) we can move to (i + 1, j) or (i, j + 1).2. We cannot move from (i, j) if your overall points at (i, j) are <= 0.3. We have to reach at (n-1, m-1) with minimum positive points i.e., > 0.
Examples:
Input:
m = 3, n = 3
points = {{-2,-3,3},
{-5,-10,1},
{10,30,-5}}
Output:
7
Explanation:
7 is the minimum value to reach the destination with positive throughout the path. Below is the path. (0,0) -> (0,1) -> (0,2) -> (1, 2) -> (2, 2) We start from (0, 0) with 7, we reach (0, 1) with 5, (0, 2) with 2, (1, 2) with 5, (2, 2) with and finally we have 1 point (we needed greater than 0 points at the end).
Input:
m = 3, n = 2
points = {{2,3},
{5,10},
{10,30}}
Output:
1
Explanation:
Take any path, all of them are positive. So, required one point at the start
Your Task:
You don't need to read input or print anything. Complete the function
minPoints
()
which takes 2 integers
m
and
n
and 2-d
vector
points
as input parameters and returns an integer denoting the
minimum initial points
to reach cell
(m-1, n-1)
from
(0, 0).
Expected Time Complexity:
O(n*m)
Expected Auxiliary Space:
O(n*m)
Constraints:
1 ≤ m ≤ 10**3
1 ≤ n ≤ 10**3
-10**3≤ points[i][j] ≤ 10**3
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int minPoints(int points[][], int m, int n)"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\nclass GfG {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while (t-- > 0) {\n int m = sc.nextInt();\n int n = sc.nextInt();\n int points[][] = new int[m][n];\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++) points[i][j] = sc.nextInt();\n Solution ob = new Solution();\n System.out.println(ob.minPoints(points, m, n));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GfG",
"solution": "class Solution {\n public int minPoints(int points[][], int m, int n) {\n // Create a 2D array to store minimum points needed at each cell\n int dp[][] = new int[m][n];\n\n // Initialize the bottom-right cell with minimum points needed\n dp[m - 1][n - 1] =\n points[m - 1][n - 1] > 0 ? 1 : Math.abs(points[m - 1][n - 1]) + 1;\n\n // Calculate minimum points needed for cells in the last row\n for (int i = m - 2; i >= 0; i--)\n dp[i][n - 1] = Math.max(dp[i + 1][n - 1] - points[i][n - 1], 1);\n\n // Calculate minimum points needed for cells in the last column\n for (int j = n - 2; j >= 0; j--)\n dp[m - 1][j] = Math.max(dp[m - 1][j + 1] - points[m - 1][j], 1);\n\n // Calculate minimum points needed for remaining cells\n for (int i = m - 2; i >= 0; i--) {\n for (int j = n - 2; j >= 0; j--) {\n int minPointsOnExit = Math.min(dp[i + 1][j], dp[i][j + 1]);\n dp[i][j] = Math.max(minPointsOnExit - points[i][j], 1);\n }\n }\n\n // Return minimum points needed at the starting cell\n return dp[0][0];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int minPoints(int points[][], int m, int n) {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"minPoints(self, m, n, points)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n m, n = input().split()\n m, n = int(m), int(n)\n points = []\n for _ in range(m):\n temp = [int(x) for x in input().split()]\n points.append(temp)\n ob = Solution()\n ans = ob.minPoints(m, n, points)\n print(ans)\n",
"solution": "class Solution:\n def minPoints(self, M, N, points):\n k = max(M, N)\n dp = [[-1] * (k + 1) for i in range(k + 1)]\n return self.helperFunction(points, M, N, 0, 0, dp)\n\n def helperFunction(self, points, M, N, x, y, dp):\n # Base cases\n if x == M - 1 and y == N - 1:\n if points[x][y] <= 0:\n return 1 + abs(points[x][y])\n else:\n return 1\n\n if x == M or y == N:\n return float('inf')\n\n if dp[x][y] != -1:\n return dp[x][y]\n\n # Choices\n down = self.helperFunction(points, M, N, x + 1, y, dp)\n left = self.helperFunction(points, M, N, x, y + 1, dp)\n res = min(down, left) - points[x][y]\n if res <= 0:\n dp[x][y] = 1\n else:\n dp[x][y] = res\n\n return dp[x][y]\n",
"updated_at_timestamp": 1727776457,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef minPoints(self, m, n, points):\n\t\t# code here"
}
|
eJztWsFu2zAM3WEfQvhcDaIky+6+ZMA87LDlsIvXQwoMKAbsI7b/HR8pO1lqZ0ubtSmgpoltiXx8fKSi1M2P17/umlf6824rJ+/vmi/jze22eUsNDyN7Yj+MTo6upUhBHolcTy5TS2KQZdBdE5PrZEps5MiUhlGsWEZkAr5BrDM5DA4jLlwESqcekXr4xmGM8IVhwFRCCIkk8VsxiOaWYcvgMoydxc7gBATS+L049FQugkIqyYDQyahHUkwxQDqSKLw1hZ6QEyvn5oqazbebzaft5vPHr7fbSRhJovl+RX9qFTwFjxwcYnp5OAimaQREVRqYUaE6RAEjpxnDVAkXZmz+RY0I/wD7djJWob2BwiGDc4JuBSqQsPEWUyxSAVV+kMCxyRatDDIousEzGd0IBrCZQ2qAOCcA1aIlVvhamZy5sJGMJriIX4gVzp0WLlhfFclmJRjM05wKwJTORC9budhiRchS6OUdQZ4CZRuJmgtriXZ6KMVgemTlUDqdVXMkmSdf7SdvrZVM8aDxSo0jaIepJtn6NBltv59vh0uw1gxzSV7h41SaPBUHky06Jdoaao13oDjF7ZQEz/rpivFky6moVbwSGQ5btRLKOGebEEkl1BVoa0cJeyso8psD817fJg2WVR7MdbrSS5hUVLOSm7rJloLVLdrKnElmBY2TyH66RCkTOLTaEIHmIrQmdFsoWKywtn6Xli9r053iEUwPXWWnO7L3WF/yWs7xcgpKhGxY26xa3z9bActLYC06zO043X99pukjqvTeL1fSNi1992JrM7Zzr/rsj+0OqtvSFJCWxw2QDg4KtORyRiAYHTxO6vWSr5wdO6xAhiO7n+72Z3rymfFcBayAFbACVsD/CMh4437Y79oWdv3yt/nuWfb5uilXwMcAdpdPsQJWwAr4V0A++64clv/4vuy7oH29DVpvg9bboPUjYwWsHxkr4IOefPkUK+A5APlJPjPqf99X7A9NtfX+0bY7AVT/ITd6oe7XNsvV+08q1xN8NyI8+ssRz/ftCH+sxB9+vvkNs2edDg==
|
710,026
|
Largest rectangular sub-matrix whose sum is 0
|
Given a matrixmat[][] of sizeNxM.The task is tofind the largest rectangular sub-matrix by areawhose sum is 0.
Examples:
Input:
N = 3, M = 3
mat[][] = 1, 2, 3
-3,-2,-1
1, 7, 5
Output:
1, 2, 3
-3,-2,-1
Explanation:
This is the largest sub-matrix,
whose sum is 0.
Input:
N = 4, M = 4
mat[][] = 9, 7, 16, 5
1,-6,-7, 3
1, 8, 7, 9
7, -2, 0, 10
Output:
-6,-7
8, 7
-2, 0
Constraints
:
1 <= N, M <= 100
-1000 <= mat[][] <= 1000
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1651219902,
"func_sign": [
"public static ArrayList<ArrayList<Integer>> sumZeroMatrix(int[][] a)"
],
"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}\nclass IntMatrix\n{\n public static int[][] input(BufferedReader br, int n, int m) throws IOException\n {\n int[][] mat = new int[n][];\n \n for(int i = 0; i < n; i++)\n {\n String[] s = br.readLine().trim().split(\" \");\n mat[i] = new int[s.length];\n for(int j = 0; j < s.length; j++)\n mat[i][j] = Integer.parseInt(s[j]);\n }\n \n return mat;\n }\n \n public static void print(int[][] m)\n {\n for(var a : m)\n {\n for(int e : a)\n System.out.print(e + \" \");\n System.out.println();\n }\n }\n \n public static void print(ArrayList<ArrayList<Integer>> m)\n {\n for(var a : m)\n {\n for(int e : a)\n System.out.print(e + \" \");\n System.out.println();\n }\n }\n}\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while(t-- > 0){\n \n int[] nm = IntArray.input(br, 2);\n \n \n int[][] a = IntMatrix.input(br, nm[0], nm[1]);\n \n Solution obj = new Solution();\n ArrayList<ArrayList<Integer>> res = obj.sumZeroMatrix(a);\n \n if(res.size() == 0) {\n System.out.println(-1);\n \n } else {\n \n IntMatrix.print(res);\n } \n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "IntMatrix",
"solution": null,
"updated_at_timestamp": 1730269803,
"user_code": "\nclass Solution {\n public static ArrayList<ArrayList<Integer>> sumZeroMatrix(int[][] a) {\n // code here\n }\n}\n \n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1651219902,
"func_sign": [
"sumZeroMatrix(self, a : List[List[int]]) -> List[List[int]]"
],
"initial_code": "class IntArray:\n def __init__(self) -> None:\n pass\n\n def Input(self, n):\n arr = [int(i) for i in input().strip().split()] # array input\n return arr\n\n def Print(self, arr):\n for i in arr:\n print(i, end=\" \")\n print()\n\n\nclass IntMatrix:\n def __init__(self) -> None:\n pass\n\n def Input(self, n, m):\n matrix = []\n # matrix input\n for _ in range(n):\n matrix.append([int(i) for i in input().strip().split()])\n return matrix\n\n def Print(self, arr):\n for i in arr:\n for j in i:\n print(j, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n nm = IntArray().Input(2)\n\n a = IntMatrix().Input(nm[0], nm[1])\n\n obj = Solution()\n res = obj.sumZeroMatrix(a)\n if len(res) == 0:\n print(-1)\n else:\n IntMatrix().Print(res)\n\n print(\"~\")\n",
"solution": "from typing import List\n\n\nclass Solution:\n\n def sumZero(self, temp, starti, endj, n):\n presum = {}\n sum_val = 0\n max_length = 0\n for i in range(n):\n sum_val += temp[i]\n\n if temp[i] == 0 and max_length == 0:\n starti[0] = i\n endj[0] = i\n max_length = 1\n\n if sum_val == 0:\n if max_length < i + 1:\n starti[0] = 0\n endj[0] = i\n max_length = i + 1\n\n if sum_val in presum:\n old = max_length\n max_length = max(max_length, i - presum[sum_val])\n if old < max_length:\n endj[0] = i\n starti[0] = presum[sum_val] + 1\n else:\n presum[sum_val] = i\n\n return max_length != 0\n\n def sumZeroMatrix(self, a: List[List[int]]) -> List[List[int]]:\n row = len(a)\n col = len(a[0])\n temp = [0] * row\n\n fup, fdown, fleft, fright = 0, 0, 0, 0\n maxl = float('-inf')\n\n for left in range(col):\n temp = [0] * row\n for right in range(left, col):\n for i in range(row):\n temp[i] += a[i][right]\n\n starti = [0]\n endj = [0]\n is_sum = self.sumZero(temp, starti, endj, row)\n ele = (endj[0] - starti[0] + 1) * (right - left + 1)\n\n if is_sum and ele > maxl:\n fup = starti[0]\n fdown = endj[0]\n fleft = left\n fright = right\n maxl = ele\n\n ans = []\n\n if fup == fdown == fleft == fright == 0 and a[0][0] != 0:\n return ans\n\n for j in range(fup, fdown + 1):\n cnt = []\n for i in range(fleft, fright + 1):\n cnt.append(a[j][i])\n ans.append(cnt)\n\n return ans\n",
"updated_at_timestamp": 1730269803,
"user_code": "from typing import List\nfrom typing import List\nclass Solution:\n def sumZeroMatrix(self, a : List[List[int]]) -> List[List[int]]:\n # code here\n \n"
}
|
eJztWU2P0zAQ5cAPecp5jfLddvkjSARxgB64hD10JSTEih8B/5eZiZM6zkzIFq12Vbxpk9Seee/N2HXj2Z+vf7/NXsnfu5pu3n/PvvR396fsFlnR9Q0aOQ1H17sGwavrixyO3tOFLMKPfAn8sxtkx293x0+n4+ePX+9PnmfqR0yAJQMUCmp76Prsxw3m6lu0DCA2bBvdvKQ+IzW2A9bQnqlTHYQdduSGEhVqGuKWP7odXCtDXMNVcCUhsGVLBjUZlih4mKWjEqNGHLYiFQgOK7UBkIYz16PJmYvRMUIlRoL22Hf9Ae6APdweBMLEjqYuoQmeIApm1fUlA5OWAvlwdL2/GVq5v+srtq7ZT75HA55AC8lE5xu5f7BkH+8+YzKyqOiGKhyKcijSoWqHKh6qemjyreT7VcuvI+oonIHnsJp4tuj6SPuk3A+zSsar1SyKiYwnUZCz9UH2WOc8xWR6yhjJXIKs1MDOjTqyYmJnB2vpgZ0fWAkyppKHs1NkTCsvf30a+cVQlsWtt8nv//Szf/MvAMOlKpLj1TiqS1OZo8x5aeWFNHjAAvstn7B4/aN10Plfxce5JZpEk2heLI35DP9YblxAjkuCTESJKBE9G9FaVU1g6eHC0buiS8XFv2q4L4eecVc07MaIadgey0ZqavSbyGDzSgKkkjKUENa3pTMB0BUgloBYA2IRiFVYyWikuuWfwaYtaFiTmfq4uJmDXv7iDeeBjI0sKjj9rTyoFFTGLo1WY12QGhEfcBhLulOZNqz/jm3eJKgDy946PpHHslHqFEE6x7TMkzKe/GjGJ54Mi8ZzfSY+rRan40itOPUg9RiXEeoB6uHp0emxmXO3CUbyaav7bnt5f6nV7QzshR3lf6Mpl+82mu63mzKqrAfb7LfCcq1vm2na8CUahebKwvknmisLJ235ElEiSkRPtuWT/1s6+7nqw683fwCW17KW
|
700,405
|
Print matrix in diagonal pattern
|
Given a square matrix mat[][] of n*n size, the task is to determine the diagonal pattern which is a linear arrangement of the elements of the matrix as depicted in the following example:
Examples:
Input:
n = 3
mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output:
{
1, 2, 4, 7, 5, 3, 6, 8, 9}
Explanation:
Starting from (0, 0): 1,
Move to the right to (0, 1): 2,
Move diagonally down to (1, 0): 4,
Move diagonally down to (2, 0): 7,
Move diagonally up to (1, 1): 5,
Move diagonally up to (0, 2): 3,
Move to the right to (1, 2): 6,
Move diagonally up to (2, 1): 8,
Move diagonally up to (2, 2): 9
There for the output is {1, 2, 4, 7, 5, 3, 6, 8, 9}.
Input:
n = 2
mat[][] = {{1, 2},
{3, 4}}
Output:
{1, 2, 3, 4}
Explanation:
Starting from (0, 0): 1,
Move to the right to (0, 1): 2,
Move diagonally down to (1, 0): 3,
Move to the right to (1, 1): 4
There for the output is {1, 2, 3, 4}.
Constraints:
1 <= n <= 100
-100 <= elements of matrix <= 100
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1617209242,
"func_sign": [
"public int[] matrixDiagonally(int[][] mat)"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n int n = Integer.parseInt(br.readLine().trim());\n int[][] mat = new int[n][n];\n String[] S = br.readLine().trim().split(\" \");\n int i = 0;\n int j = 0;\n for(int k = 0; k < S.length; k++){\n mat[i][j] = Integer.parseInt(S[k]);\n j++;\n if(j == n){\n i++;\n j = 0;\n }\n }\n Solution obj = new Solution();\n int[] ans = obj.matrixDiagonally(mat);\n for(int it = 0; it < ans.length; it++){\n System.out.print(ans[it] + \" \");\n }\n System.out.println();\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n public int[] matrixDiagonally(int[][] arr) {\n Map<Integer, List<Integer>> m = new HashMap<>();\n \n // Store elements in the map based on diagonal index\n for (int i = 0; i < arr.length; i++) {\n for (int j = 0; j < arr.length; j++) {\n int diagonalIndex = i + j;\n if (!m.containsKey(diagonalIndex)) {\n m.put(diagonalIndex, new ArrayList<>());\n }\n m.get(diagonalIndex).add(arr[i][j]);\n }\n }\n \n List<Integer> result = new ArrayList<>();\n int k = 0;\n \n // Traverse the map and append elements to result list\n for (Map.Entry<Integer, List<Integer>> entry : m.entrySet()) {\n if (k % 2 == 0 && k > 0) {\n Collections.reverse(entry.getValue());\n }\n result.addAll(entry.getValue());\n k++;\n }\n \n // Convert List<Integer> to int[]\n int[] res = new int[result.size()];\n for (int i = 0; i < result.size(); i++) {\n res[i] = result.get(i);\n }\n \n return res;\n \n }\n}",
"updated_at_timestamp": 1730272206,
"user_code": "class Solution {\n public int[] matrixDiagonally(int[][] mat) {\n \n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617209242,
"func_sign": [
"matrixDiagonally(self,mat)"
],
"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[0])] for j in range(n[0])]\n k = 0\n for i in range(n[0]):\n for j in range(n[0]):\n matrix[i][j] = arr[k]\n k += 1\n a = Solution().matrixDiagonally(matrix)\n for x in a:\n print(x, end=' ')\n print('')\n print(\"~\")\n# Contributed by: Harshit Sidhwa\n",
"solution": "\nclass Solution:\n def matrixDiagonally(self, mat):\n # Check for an empty matrix\n if not mat or not mat[0]:\n return []\n\n # The dimensions of the matrix\n N, M = len(mat), len(mat[0])\n\n # Incides that will help us progress through\n # the matrix, one element at a time.\n row, column = 0, 0\n\n # As explained in the article, this is the variable\n # that helps us keep track of what direction we are\n # processing the current diaonal\n direction = 1\n\n # Final result array that will contain all the elements\n # of the matrix\n result = []\n\n # The uber while loop which will help us iterate over all\n # the elements in the array.\n while row < N and column < M:\n # First and foremost, add the current element to\n # the result matrix.\n result.append(mat[row][column])\n\n # Move along in the current diagonal depending upon\n # the current direction.[i, j] -> [i - 1, j + 1] if\n # going up and [i, j] -> [i + 1][j - 1] if going down.\n new_row = row + (-1 if direction == 1 else 1)\n new_column = column + (1 if direction == 1 else -1)\n\n # Checking if the next element in the diagonal is within the\n # bounds of the matrix or not. If it's not within the bounds,\n # we have to find the next head.\n if new_row < 0 or new_row == N or new_column < 0 or new_column == M:\n # If the current diagonal was going in the upwards\n # direction.\n if direction:\n # For an upwards going diagonal having [i, j] as its tail\n # If [i, j + 1] is within bounds, then it becomes\n # the next head. Otherwise, the element directly below\n # i.e. the element [i + 1, j] becomes the next head\n row += (column == M - 1)\n column += (column < M - 1)\n else:\n # For a downwards going diagonal having [i, j] as its tail\n # if [i + 1, j] is within bounds, then it becomes\n # the next head. Otherwise, the element directly below\n # i.e. the element [i, j + 1] becomes the next head\n column += (row == N - 1)\n row += (row < N - 1)\n\n # Flip the direction\n direction = 1 - direction\n else:\n row = new_row\n column = new_column\n\n return result\n",
"updated_at_timestamp": 1730272206,
"user_code": "# Your task is to complete this function\n\nclass Solution:\n def matrixDiagonally(self,mat):\n # code here"
}
|
eJydVN1OgzAU9sL4HF+43jGc0sLmk5iI8UK58KbuApIlRuND6Pt62gKRsIOwsZGVfn8tX/p1/dPdXMXPvZc/D+/Zqz92bXaHjGsfvnme7ZA1p2Pz3DYvT29dO8znOWr/WfvsY4cpr6g9hWlyOXLILQ7CLY5IFx1pkZkY8VlP0xytJIVBAQuHEhX2OAgdzGADLsAW7MClthghO6GUUaKK1ERikQoSgay5u9qHeCADKkBWVgAqQRVoDzqE5PKTeREi0SURJlEkkSQWFAuMBWcEZ4KO4IzgjFXyJjuXlMvBuOpdXFKK6iZmsClGkewGi2hre+top62Q0xtdems6U6OpHBN7h74CC/0bSqLr0AD7L/7YNL3TY4v/1HkyXA5LE/6cutiujZe641uvc5nIKfLaScAXHgW8/SwgszobVoS7MNvaQmrH0RR0fqGsnQ0zoLrFs71bC+RSSz5HqsDH79tf5A+krg==
|
707,049
|
IPL 2021 - Match Day 4
|
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:
N = 4
arr[] = {4, 8, 12, 16}
Output:
8
Explanation:
Pair (8, 12) has the
Maximum
AND
Value
8.
Input:
N = 4
arr[] = {4, 8, 16, 2}
Output:
0
Explanation:
Maximum
AND
Value
is 0.
Example 2:
|
geeksforgeeks
|
Medium
|
{
"class_name": "AND",
"created_at_timestamp": 1618213780,
"func_sign": [
"public static int maxAND(int arr[], int n)"
],
"initial_code": "//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass BitWise {\n \n\tpublic static void main (String[] args) throws IOException {\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\tint t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases\n\t\twhile(t-->0){\n\t\t \n\t\t //input size of array\n\t\t int n = Integer.parseInt(br.readLine());\n\t\t String inputLine[] = br.readLine().trim().split(\" \");\n\t\t int arr[] = new int[n];\n\t\t \n\t\t //inserting elements in the array\n\t\t for(int i=0; i<n; i++){\n\t\t arr[i]=Integer.parseInt(inputLine[i]);\n\t\t }\n\t\t \n\t\t AND obj = new AND();\n\t\t \n\t\t //calling maxAND() method of class AND\n\t\t System.out.println(obj.maxAND(arr, n));\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}\n",
"script_name": "BitWise",
"solution": "// Back-end complete function Template for Java\nclass AND {\n // Function to check number of elements in an array\n // having set MSB as of pattern.\n public static int checkBit(int pattern, int arr[], int n) {\n int count = 0;\n // iterating over all elements in array.\n for (int i = 0; i < n; i++) {\n // incrementing counter if element has set MSB as of pattern.\n if ((pattern & arr[i]) == pattern) {\n count++;\n }\n }\n // returning the number of element having set MSB as of pattern.\n return count;\n }\n\n // Function for finding maximum AND value.\n public static int maxAND(int arr[], int n) {\n int res = 0, count;\n // iterating over total of 16 bits from MSB to LSB.\n for (int bit = 16; bit >= 0; bit--) {\n // finding the count of element in the array\n // having set MSB as of [res | (1 << bit)].\n count = checkBit(res | (1 << bit), arr, n);\n // if count >= 2 setting particular bit in result.\n if (count >= 2) {\n res |= (1 << bit);\n }\n }\n // returning the final maximum AND value.\n return res;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass AND{\n \n // Function for finding maximum AND value.\n public static int maxAND (int arr[], int n) {\n \n // Your code here\n // You can add extra function (if required)\n \n \n }\n \n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618213780,
"func_sign": [
"maxAND(self, arr,n)"
],
"initial_code": "# Initial Template for Python 3\n\nimport math\n\n\ndef main():\n T = int(input())\n\n while T > 0:\n n = int(input())\n arr = [int(x) for x in input().strip().split()]\n obj = Solution()\n print(obj.maxAND(arr, n))\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # function to check number of elements in an array\n # having set MSB as of pattern.\n def checkBit(self, pattern, arr, n):\n count = 0\n\n # iterating over all elements in array.\n for i in range(0, n):\n # incrementing counter if element has set MSB as of pattern.\n if (pattern & arr[i]) == pattern:\n count += 1\n\n # returning the number of element having set MSB as of pattern.\n return count\n\n # Function for finding maximum AND value.\n def maxAND(self, arr, n):\n res = 0\n\n # iterating over total of 16 bits from MSB to LSB.\n for bit in range(16, -1, -1):\n # finding the count of element in the array\n # having set MSB as of [res | (1 << bit)].\n count = self.checkBit(res | (1 << bit), arr, n)\n\n # if count >= 2 setting particular bit in result.\n if count >= 2:\n res |= (1 << bit)\n\n # returning the final maximum AND value.\n return res\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n #Complete this function\n # Function for finding maximum AND value.\n def maxAND(self, arr,n):\n #Your code here"
}
|
eJytlM1KxDAUhV3oe1yyHiT3Jz+dR3DnTjDiQrtwU2fRgQFx8CH0fU0TyghjUlLtIhRyz+Xce7724/Lr9uoiPXc38eX+Tb0Mu/2otqAwDBQGBFQbUP1h1z+N/fPj63483R/DoN43cCbSoAsiXRBxEjXLTDSoiSEeAqTFg+jOgseOGjtJ9EDOOrDGsAFk1A6BLKFwaQGppryFqZ+H6ewKHVJF3ZBPhmw2RNmQNM6WYow6J56tuMY8UzR/0MdB0LIXyONIh4byUCu2kjnJsfwbLbqMy1SwTIw1PDMzCRa4SarfmpbmqdClObkvAVYhYqYzW11D6AmMFVRUsmjxV8nnpz1e8Uc4/3AohCU/c7OHz+tvoSSJ8Q==
|
705,605
|
Break Numbers[Duplicate problem]
|
Given a large number N, write a program to count the ways tobreak it into threewhole numbers such that they sum up to the original number.
Examples:
Input:
N = 3
Output:
10
Explanation:
The ways are
0 + 0 + 3 = 3
0 + 3 + 0 = 3
3 + 0 + 0 = 3
0 + 1 + 2 = 3
0 + 2 + 1 = 3
1 + 0 + 2 = 3
1 + 2 + 0 = 3
2 + 0 + 1 = 3
2 + 1 + 0 = 3
1 + 1 + 1 = 3
Input:
N = 1
Output:
3
Explanation:
The ways are:
1 + 0 + 0 = 1
0 + 1 + 0 = 1
0 + 0 + 1 = 1
Constraints:
1 ≤ N ≤ 10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static long countWays(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 {\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(in.readLine());\n while(t-- > 0){\n long N = Long.parseLong(in.readLine());\n \n Solution ob = new Solution();\n System.out.println(ob.countWays(N));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n // function to count the number of ways\n static long countWays(long N) {\n // initialize the counter\n long counter = 0;\n // calculate the number of ways using the formula\n counter = ((N + 1) * (N + 2)) / 2;\n // return the counter\n return counter;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "//User function Template for Java\n\nclass Solution{\n static long countWays(long N){\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"countWays(self, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n\n for _ in range(t):\n N = int(input())\n\n ob = Solution()\n print(ob.countWays(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n # Function to count the number of ways to reach N.\n def countWays(self, N):\n # Calculating the count using the formula\n counter = (N + 1) * (N + 2) // 2\n return counter\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def countWays(self, N):\n # code here"
}
|
eJylk0EKwjAQRV3oPUrWRZLUWOtJBCsutAs3sYsWBFE8hJ7NnWcxtImtpb8TNGQRSPL+zPyZ2/jxmoyqtXqaw/rMDjovC7YMmEi12SwMWHbKs12R7bfHsrCXUaqv5vISBp0f3C34VdkH4nMALAkRc/AjcYsU56qJsxelyDyEtG9iNZxHhBFIXQwX0JQOic2wmIJiuNCo0sLH5NphFKmwGBtBqjEtXlCGezjeWA6r/t2/HnByDDpIeipcU3GEVpZa7XaIdLdWHQtDTkD2HKcvcQN3afU8/8/0Y/dX/1fdBkYrEwZbe5EJUdtTD7MHBaWbms19+gY5M7lN
|
704,426
|
Sum of Digit Modified
|
Given a number N. Check whether it is a magic number or not.
Note:- A number is said to be a magic number, if the sum of its digits are calculated till a single digit recursively by adding the sum of the digits after every addition andthe single digit comes out to be 1.
Examples:
Input:
N = 1234
Output:
1
Explanation:
1 + 2 + 3 + 4 = 10,
Again 1 + 0 = 1. Thus, 1234 is a magic
number.
Input:
N = 1235
Output:
0
Explanation:
1 + 2 + 3 + 5 = 11. Again,
1 + 1 = 2. Thus, 1235 is not a magic number.
Constraints:
1<=N<=10**9
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"int isMagic(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.isMagic(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 a magic number\n int isMagic(int N) {\n int sum = 0;\n // Calculate the digit sum repeatedly until it becomes a single digit\n while (N / 10 > 0) {\n sum = 0;\n // Calculate the sum of the digits of the number\n while (N > 0) {\n sum += N % 10;\n N /= 10;\n }\n // Update N with the calculated sum\n N = sum;\n }\n // If N is equal to 1, it is a magic number\n return (N == 1 ? 1 : 0);\n }\n}\n",
"updated_at_timestamp": 1730474923,
"user_code": "// User function Template for Java\n\nclass Solution {\n int isMagic(int N) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isMagic(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.isMagic(N))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def isMagic(self, N):\n # calculating digit sum repeatedly until it becomes single digit\n while N//10 > 0:\n sum = 0\n while N > 0:\n sum += N % 10\n N //= 10\n N = sum\n return 1 if N == 1 else 0\n",
"updated_at_timestamp": 1730474923,
"user_code": "#User function Template for python3\n\nclass Solution:\n def isMagic(self,N):\n #code here"
}
|
eJxrYJmazcIABhEpQEZ0tVJmXkFpiZKVgpJhTJ4lDCjpKCilVhSkJpekpsTnl5ZAlRjE5NXF5CnV6iig6jM0gAEcGg1xaLS0MDczNTE2MiTVQiNjE1MzcwuSHQoDJOozhQES9VlAAYnBYmgAhaQ6ExSUuOIAlyYy4xzqMwpca0goNggFDzkeJTVEjUgOUpyZAHfQIwciLhfizEJIZsABuebhzsFYYoG4sImdogcAzShWJw==
|
703,550
|
Tom and String
|
Given a list S consistingof stringsseparated by a space.Hash the list using the hash rule and a long string Xgiven belowand return the hash value.String X: "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ".Hash Rule:Hash is the summation of all the character values in the input:(currentIndex + (position of the character In the string initial) ).And then this hash is multiplied by the number of strings in the list.
Examples:
Input:
S = aA1 b
Output:
132
Explanation:
List is [
"aA1", "b"
]
a: 0 + 0 = 0
A: 1 + 36 = 37
1: 2 + 26 = 28
b: 0 + 1 = 1
So, 2*(0+1+37+28) = 2*(66) = 132
Input:
S = aa BB cc DD
Output:
640
Explanation:
List is [
"aa", "BB","cc","DD"
]
a: 0 + 0 = 0
a: 1 + 0 = 1
B: 0 + 37 = 37
B: 1 + 37 = 38
c: 0 + 2 = 2
c: 1 + 2 = 3
D: 0 + 39 = 39
D: 1 + 39 = 40
So, 4*(0+1+37+38+2+3+39+40)= 4*(160)=640
Constraints:
1 ≤ Length of a string ≤ 30
1 ≤ Number of strings in a list ≤ 20
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static long hashString(String s)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n//Position this line where user code will be pasted.\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().trim();\n Solution ob = new Solution();\n System.out.println(ob.hashString(s));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static long hashString(String S) {\n // Split the string into array of strings.\n String arr[] = S.split(\" \");\n long ssum = 0;\n String initial = \"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n long m[] = new long[200];\n // Map all the characters in initial string to their position into m;\n for (int i = 0; i < initial.length(); i++) {\n m[(int) initial.charAt(i)] = i;\n }\n // Perform brute force\n for (int i = 0; i < arr.length; i++) {\n String astring = arr[i];\n long sum = 0;\n for (int j = 0; j < astring.length(); j++) {\n char ch = astring.charAt(j);\n sum = sum + j + m[(int) ch];\n }\n ssum = ssum + sum;\n }\n long ans = ssum * arr.length;\n return ans;\n }\n}\n;\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution {\n static long hashString(String s) {\n\n // Code Here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"hashString(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 print(ob.hashString(s))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\nclass Solution:\n def hashString(self, S):\n m = {}\n initial = \"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n # Map all the characters in initial string to their position into m;\n for i in range(len(initial)):\n m[initial[i]] = i\n # Split the string into array of strings.\n S = S.strip().split()\n hash = 0\n # Perform brute force\n for s in S:\n for i in range(len(s)):\n hash += m[s[i]] + i\n ans = hash * len(S)\n return ans\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution:\n def hashString(self, S):\n # code here \n"
}
|
eJy1VNtOwkAQNcbE+BeTPhOzu93efKNcvYsXLHWNaUsBbwsqaMFo/Aj9XzeFEI0MASJNNjt9mDkzZ87Zj7WvjfWV9PNWVXDxql3LTq+rbYGmCxlkKfg1T0gSUHCjHCQeFdL3fRio4w98IbUMaHHSiaNuXL9q97qjZO6YQr4LaZlGelNu2GmgvWXgBwgTMutSBrm8zqFQNFQWDVgIesTrYMRmA6lPmUnSeiZlk+qqNgllOjdMy3YgCKN63Gi2rm9u7+5lu/Pw+NTtPb8k/QFk3Vy+UCyVt3d29/YPDo8qxyenZ9Vzr4bPZlmTZ+FCJtCHgZAe1EDlJ+pW/yqiwEBHCzI6JMvg5BdpjOvIbNkA3BByEeTrUIih2IBSE8otHMEeQfwtFaBJBAMHxSyEbohv30bRlKL+8eADm4Sg/aMrnyaUsZrI3MKY0TOYRxbTcmVGMTsOZiDFL0WyHD63AdTzsYgHON7enLKVKLQ1o1jTIstSLOU6KlgkRZ/osvGTOvlBnb5YSvhwtRbBeF/YPlWlYHuqgWzi0OWghlNh6Zj6y8/Nb+XAMWU=
|
705,651
|
Find the string in grid
|
Given a 2D gridof n*m of characters and a word, find all occurrences of given word in grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match in this direction (not in zig-zag form). The 8 directions are, horizontally left, horizontally right, vertically up, vertically down, and 4 diagonal directions.Note: The returning list should be lexicographically smallest. If the word can be found in multiple directions starting from the same coordinates, the list should contain the coordinates only once.
Examples:
Input:
grid = {{a,b,c},{d,r,f},{g,h,i}},
word = "abc"
Output:
{{0,0}}
Explanation:
From (0,0) we can find "abc" in horizontally right direction.
Input:
grid = {{a,b,a,b},{a,b,e,b},{e,b,e,b}}
word = "abe"
Output:
{{0,0},{0,2},{1,0}}
Explanation:
From (0,0) we can find "abe" in right-down diagonal.
From (0,2) we can find "abe" in left-down diagonal.
From (1,0) we can find "abe" in horizontally right direction.
Constraints:
1 <= n <= m <= 50
1 <= |word| <= 15
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int[][] searchWord(char[][] grid, String word)"
],
"initial_code": "//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n String[] s1 = br.readLine().trim().split(\" \");\n int n = Integer.parseInt(s1[0]);\n int m = Integer.parseInt(s1[1]);\n char[][] grid = new char[n][m];\n for(int i = 0; i < n; i++){\n String S = br.readLine().trim();\n for(int j = 0; j < m; j++){\n grid[i][j] = S.charAt(j);\n }\n }\n String word = br.readLine().trim();\n Solution obj = new Solution();\n int[][] ans = obj.searchWord(grid, word);\n for(int i = 0; i < ans.length; i++){\n for(int j = 0; j < ans[i].length; j++){\n System.out.print(ans[i][j] + \" \");\n }\n System.out.println();\n }\n if(ans.length==0)\n {\n System.out.println(\"-1\");\n }\n\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution\n{\n public int[][] searchWord(char[][] grid, String word)\n {\n // Code here\n int row = grid.length;\n\t\tint col = grid[0].length;\n\t\tint x[] = { -1, -1, -1, 0, 0, 1, 1, 1 };\n\t\tint y[] = { -1, 0, 1, -1, 1, -1, 0, 1 };\n\t\tArrayList<int[]> A=new ArrayList<>();\n\t\tfor(int i = 0; i < row; i++){\n\t\t\tfor(int j = 0; j < col; j++){\n\t\t\t\tif(search2D(grid, i, j, word.toCharArray(), x, y)){\n\t\t\t\t\tA.add(new int[]{i,j});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint ans[][]=new int[A.size()][];\n\t\tint in=0;\n\t\tfor(var i:A){\n\t\t ans[in++]=i;\n\t\t}\n\t\treturn ans;\n }\n public boolean search2D(char grid[][], int row, int col, char word[], int x[], int y[])\n\t{\n\t\tint R = grid.length;\n\t\tint C = grid[0].length;\n\t // If first character of word doesn't match with\n\t // given starting point in grid.\n\t if (grid[row][col] != word[0])\n\t return false;\n\t \n\t int len = word.length;\n\t \n\t // Search word in all 8 directions starting from (row,col)\n\t for (int dir = 0; dir < 8; dir++)\n\t {\n\t // Initialize starting point for current direction\n\t int k, rd = row + x[dir], cd = col + y[dir];\n\t \n\t // First character is already checked, match remaining\n\t // characters\n\t for (k = 1; k < len; k++)\n\t {\n\t // If out of bound break\n\t if (rd >= R || rd < 0 || cd >= C || cd < 0)\n\t break;\n\t \n\t // If not matched, break\n\t if (grid[rd][cd] != word[k])\n\t break;\n\t \n\t // Moving in particular direction\n\t rd += x[dir];\n\t cd += y[dir];\n\t }\n\t \n\t // If all character matched, then value of must\n\t // be equal to length of word\n\t if (k == len)\n\t return true;\n\t }\n\t return false;\n\t}\n}",
"updated_at_timestamp": 1730268752,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n public int[][] searchWord(char[][] grid, String word)\n {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"searchWord(self, grid, word)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n, m = input().split()\n n = int(n)\n m = int(m)\n grid = []\n for _ in range(n):\n cur = input()\n temp = []\n for __ in cur:\n temp.append(__)\n grid.append(temp)\n word = input()\n obj = Solution()\n ans = obj.searchWord(grid, word)\n for _ in ans:\n for __ in _:\n print(__, end=\" \")\n print()\n if len(ans) == 0:\n print(-1)\n print(\"~\")\n",
"solution": "class Solution:\n def search2D(self, grid, row, col, word, x, y):\n R = len(grid)\n C = len(grid[0])\n\n # If first character of word doesn't match with\n # given starting point in grid.\n if grid[row][col] != word[0]:\n return False\n\n length = len(word)\n\n # Search word in all 8 directions starting from (row, col)\n for direction in range(8):\n # Initialize starting point for current direction\n k, rd, cd = 1, row + x[direction], col + y[direction]\n\n # First character is already checked, match remaining characters\n while k < length:\n # If out of bounds, break\n if rd >= R or rd < 0 or cd >= C or cd < 0:\n break\n\n # If not matched, break\n if grid[rd][cd] != word[k]:\n break\n\n # Moving in a particular direction\n rd += x[direction]\n cd += y[direction]\n k += 1\n\n # If all characters matched, then value of k\n # must be equal to the length of the word\n if k == length:\n return True\n\n return False\n\n def searchWord(self, grid, word):\n row = len(grid)\n col = len(grid[0])\n x = [-1, -1, -1, 0, 0, 1, 1, 1]\n y = [-1, 0, 1, -1, 1, -1, 0, 1]\n ans = []\n\n for i in range(row):\n for j in range(col):\n if self.search2D(grid, i, j, word, x, y):\n ans.append([i, j])\n\n return ans\n",
"updated_at_timestamp": 1731586329,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef searchWord(self, grid, word):\n\t\t# Code here"
}
|
eJzlVttu00AQ5YF3fuHIzwVlc9lYfAkSi1AdO7EN3SRt0iYgUD8C/pfZM5Hl1HGVGy0XjzxO5visZ2dnZ+f+5c/7Vy94vVvLj/dfo8LPlovoLSLj/AAD5y+RYIQUmfNjTJCjQOn8J3zGFTymzs8wxzVusHB+iVvcYYW10JJRGl0gylazbLTI0o/T5WIz8msZ+rvz0bcLbH/PwobvVeJ8gkqcH6ES51NU4nyGSoKXlagb2bjFkQ46cL6DLnWf2lLH1CbAOz0dYuj8F5npSGacSByunJ/L1DOJxAJrLJ0vMMVMZnEjLoojIXIlQtiEFuay4Unw7sIENjyJLkO64YWACzcvDw1ljNj5Fbbk+Qyr1SkrIA/FTXjBkGJIMVCLpY6pjcJGcVK6pHRJ6UItljqmNgobxUnpkdIjpQe1WOqY2ihsFCelT0qflD7UYqljaqOwUZyUASkDUgZQi6WOqY3CRnFSLCmWFAu1WOqY2ihsFCdlSMqQlCHUYqljaqOwUZyUnTnFclAlfS3ha8leS3TnQ4FgdXB+OpsfVQ2WqOQcf3idkot7rVj7jqwVt0aBaxS5RqFrFLtGwdOiN8GWOJ9jS8QPXoeuiGR1dR4EPzblqaivt+SBQOPJoWObEODaaYPaYVPKI5e/YzGnAichcn/NmzyBJnlxXA1/8CE11O6wuA++mNOj6t4xxs7pPD5ocnnwcf60GZ8x2dMq52/PlPT7HfXlM571e21L547cmC3z/4N6nd/cjJWBeKKL/1x1K04vb61pe32G46Q5+Fk3RdUKhcfTtEMxO4xztOMnDCLl9T/r6o9o0dv77bZO+8OPN78AyJKIkQ==
|
702,868
|
At least two greater elements
|
Given an array arr of distinct elements, the task is to return an array of all elements except the two greatest elements in sorted order.
Examples:
Input:
arr[] = [2, 8, 7, 1, 5]
Output:
[1, 2, 5]
Explanation:
Here we return an array contains 1 , 2, 5 and we leave two greatest elements 7 & 8.
Input:
arr[] = [7, -2, 3, 4, 9, -1]
Output:
[-2, -1, 3, 4]
Explanation:
Here we return an array contains -2 , -1, 3, 4 and we leave two greatest elements 7 & 9.
Constraints:
3 ≤ arr.size ≤ 10**5
-10**6≤ arr[i] ≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public long[] findElements(long arr[])"
],
"initial_code": "// Initial Template for Java\n\n// Initial Template for Java\n\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine().trim());\n while (t-- > 0) {\n String inputLine[] = br.readLine().trim().split(\" \");\n long n = inputLine.length;\n long arr[] = new long[(int)(n)];\n\n for (int i = 0; i < n; i++) {\n arr[i] = Long.parseLong(inputLine[i]);\n }\n\n Solution obj = new Solution();\n long answer[] = obj.findElements(arr);\n long sz = answer.length;\n\n StringBuilder output = new StringBuilder();\n for (int i = 0; i < sz; i++) output.append(answer[i] + \" \");\n System.out.println(output);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n // Method to find the first n-2 elements after sorting the input array\n public long[] findElements(long arr[]) {\n int n = arr.length;\n // Creating a new array to store the result\n long[] ans = new long[(int)n - 2];\n\n // Sorting the input array\n Arrays.sort(arr);\n\n // Copying the first n-2 elements to the result array\n for (int i = 0; i < (int)n - 2; i++) {\n ans[i] = arr[i];\n }\n\n // Returning the result array\n return ans;\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public long[] findElements(long arr[]) {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"findElements(self,arr)"
],
"initial_code": "# Initial Template for Python 3\ndef main():\n T = int(input())\n\n while T > 0:\n arr = [int(x) for x in input().strip().split()]\n ob = Solution()\n print(*ob.findElements(arr))\n\n T -= 1\n print(\"~\")\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n # Function to find all elements except the last two\n def findElements(self, arr):\n # sorting the array\n arr.sort()\n # returning all elements except the last two\n return arr[:-2]\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def findElements(self,arr):\n # Your code goes here\n \n"
}
|
eJy1VUtOAzEMZYHENaxZd9B48pkZToJEEQvogk1h0UpICMQh4IrsuAMviVO103FoVRHJctX4vdjOc+bj/Ovn4iyu62/8uHmtHpfP61V1RRXPl9zERUNcVGef/2+IqSVDllw1o2rx8ry4Xy0e7p7WKyHZhGbsFmS+fJ8vq7cZjQ+lgXrqyJNDmEE4K+wbKsR21CuELvIEpsAFtgIfxwgTWa2aYEMtzMAszME8rIP1oVuwULZ2SBmuHLrXyOR78Z14L96Jt+KN+Fa81oFTjym0DGTgAQXQAAKDrJCQmsvAcdvEUBdhAGu3zDFrFrnGfEgSx6kpc8BT6r5UfsLWAo5AT8kCgSqz1DibnEmuTY7zvEh/qZaNWuLqBNPSsqPojN7w8s5xKUxr1O7QYNgwcQzpYzIMsSV2xJ64I+6JB3AeNn1FooIuHNJ2AeTBxqgJZVKt3pCP22FSDRCAtX88JP2xLwkqmWLMo6EwTBanxBYVNJLQnoa2rv9g3bRZJ2OlWFUp8gAcU20acT59xif7PzHjTRzy7j+mXE8hi6osJkVEqYjwhRjM/nvIBzVr5zUMoMnr03V6+3n5Cws99Nk=
|
706,276
|
Binary Search in forest
|
There are n trees in a forest. The heights of the trees is stored in array tree[],where tree[i]denotes the height of thei**thtree in theforest. If thei**thtree is cut at a height H, then thewood collected is tree[i] - H, providedtree[i] > H. If the total woods that needs to be collected is exactly equal tok,find the heightH at which every tree should be cut (all trees have to be cut at the same height).If it is not possible then return-1else return H.
Examples:
Input:
n = 5, k = 4
tree[] = {2, 3, 6, 2, 4}
Output:
3
Explanation:
Wood collected by cutting trees
at height 3 = 0 + 0 + (6-3) + 0 + (4-3) = 4
hence 3 is to be subtracted from all numbers.
Since 2 is lesser than 3, nothing gets
subtracted from it.
Input:
n = 6, k = 8
tree[] = {1, 7, 6, 3, 4, 7}
Output:
4
Explanation:
Wood collected by cutting trees
at height 4 = 0+(7-4)+(6-4)+0+0+(7-4) = 8
Constraints:
1 <= n <= 10**4
1 <= tree[i] <= 10**3
1 <= k <= 10**7
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1618941710,
"func_sign": [
"static int find_height(int tree[], int n, int k)"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GfG\n{\n public static void main (String[] args)\n\t{\n Scanner in = new Scanner(System.in);\n \n int t = in.nextInt();\n while(t-->0)\n {\n int n = in.nextInt();\n \n int tree[]= new int[n];\n for(int i=0; i<n; i++)\n tree[i] = in.nextInt();\n int k = in.nextInt();\n \n Solution x = new Solution();\n System.out.println( x.find_height(tree,n,k) );\n \nSystem.out.println(\"~\");\n}\n\t}\n}",
"script_name": "GfG",
"solution": "class Solution {\n static int wood_collected(int tree[], int n, int h) {\n int ret = 0;\n // counting the amount of wood that gets collected\n // if we cut trees at height h\n for (int i = 0; i < n; i++) if (tree[i] > h) ret += tree[i] - h;\n return ret;\n }\n\n static int find_height(int tree[], int n, int k) {\n // l is lower limit of binary search\n // h is upper limit\n int l = 0, h = 0;\n for (int i = 0; i < n; i++) if (tree[i] > h) h = tree[i];\n while (l <= h) {\n int mid = (l + h) / 2;\n int val = wood_collected(tree, n, mid);\n if (val == k) return mid;\n if (val > k) l = mid + 1;\n // if wood collected is too much, we increase lower limit\n else h = mid - 1;\n // if wood collected is too less, we decrease uppwer limit\n }\n return -1;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution\n{\n static int find_height(int tree[], int n, int k)\n {\n \n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1618941710,
"func_sign": [
"find_height(self,tree,n,k)"
],
"initial_code": "t = int(input())\n\nfor _ in range(t):\n n = int(input())\n tree = [int(x) for x in input().strip().split()]\n k = int(input())\n\n ob = Solution()\n print(ob.find_height(tree, n, k))\n print(\"~\")\n",
"solution": "class Solution:\n def wood_collected(self, tree, n, h):\n ret = 0\n\n # counting the amount of wood that gets collected\n # if we cut trees at height h\n for i in range(n):\n if tree[i] > h:\n ret += tree[i] - h\n\n return ret\n\n def find_height(self, tree, n, k):\n l = 0\n h = 0\n # l is lower limit of binary search\n # h is upper limit\n for i in range(n):\n h = max(h, tree[i])\n\n while l <= h:\n mid = (l + h) // 2\n val = self.wood_collected(tree, n, mid)\n\n if val == k:\n return mid\n\n if val > k:\n # if wood collected is too much, we increase lower limit\n l = mid + 1\n else:\n # if wood collected is too less, we decrease upper limit\n h = mid - 1\n\n return -1\n",
"updated_at_timestamp": 1730267067,
"user_code": "class Solution:\n def find_height(self,tree,n,k):\n # code here"
}
|
eJzNVUFOwzAQ5MCNT1g5F2R7d5OYlyARxAF64BI4tBISAvEI+Bk3PsOsbdoe6qhR00KlrRJn5Jldz67fTz+/z07i7+oLD9cv1UP/tFxUl6ZyXe+shrUmhIBoEQ2iRgiCEYTwCKBFrK1mppo/P83vFvP728flIu91js9vXV+9zswWBuMNGTZiatMYkJi4KoW9ZGArKDA7RNeXhMaPZaVaizF/Xc/loqBeJS6JXMYjCMFZeo1oEK0eyYpHkU6hTrFOwS7m0ZS5yZfK6OOJSNxc94kivCQhJEkMskq1lCSqliQMjFFcK0lgkHQoo30hsdrgBi0YTeQBBXbHxkmbi2lr1pp01OoAckA5wFzI2nUf4DxwnlMuHjgPnAfOh5wbcKSEwBGnXAk4Ao6Ao5BzB46BY1XGqRYMHAPHwHHIHhsofzFvv+q4fMxNPnbJNqBsCxfXtDQUywRRgh4i9JIbdJ0rOly5g2xaWN8mWhm0QVN0I6mmbKhf1x/pWcnLiou9u62KVNutRQp+c5HDROXEtA7Dc0yH93ro7jJ1obU5Xq8ev1nLDcO2ZM6/SPx/ZD7VqICo8fZmlrDX1WkPeneup3crhxjgrWVb7O4Rlmx39yTeJrCltyOcWdthb1IbmsGbbJ9bVM2ww0GIpT37wx6+QW4+Ln4AUjm9CQ==
|
713,969
|
Unique Paths in a Grid
|
You are given a matrix grid ofn x m size consisting of values 0 and 1. A value of 1 means that you can enter that cell and 0 implies that entry to that cell is not allowed.
Examples:
Input:
n = 3, m = 3
grid[][] = {{1, 1, 1};
{1, 0, 1};
{1, 1, 1}}
Output:
2
Explanation:
1
1 1
1
0 1
1 1 1
This is one possible path.
1
1 1
1 0
1
1
1
1
This is another possible path.
Input:
n = 1, m = 3
grid = {{1, 0, 1}}
Output:
0
Explanation:
There is no possible path to reach the end.
Constraints:
1 ≤ n*m ≤ 10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1675768528,
"func_sign": [
"static int uniquePaths(int n, int m, int[][] grid)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n \n int n = Integer.parseInt(S[0]);\n int m = Integer.parseInt(S[1]);\n \n int [][] grid = new int[n][m];\n for(int i=0; i<n; i++)\n {\n String S1[] = read.readLine().split(\" \");\n for(int j=0; j<m; j++)\n {\n grid[i][j] = Integer.parseInt(S1[j]);\n }\n }\n\n Solution ob = new Solution();\n System.out.println(ob.uniquePaths(n,m,grid));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "//Back-end function Template for Java\n\nclass Solution {\n static int uniquePaths(int n, int m, int[][] grid) {\n \n int mod = 1000000007;\n \n // create a 2D-matrix and initializing\n // with value 0\n int[][] paths = new int[n][m];\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < m; j++)\n {\n paths[i][j] = 0;\n }\n }\n \n // Initializing the left corner if\n // no obstacle there\n if (grid[0][0] == 1)\n paths[0][0] = 1;\n \n // Initializing first column of\n // the 2D matrix\n for(int i = 1; i < n; i++)\n {\n // If not obstacle\n if (grid[i][0] == 1)\n paths[i][0] = paths[i - 1][0];\n } \n \n // Initializing first row of the 2D matrix\n for(int j = 1; j < m; j++)\n {\n \n // If not obstacle\n if (grid[0][j] == 1)\n paths[0][j] = paths[0][j - 1];\n } \n \n for(int i = 1; i < n; i++)\n {\n for(int j = 1; j < m; j++)\n {\n \n // If current cell is not obstacle \n if (grid[i][j] == 1)\n paths[i][j] = (paths[i - 1][j] % mod + paths[i][j - 1] % mod) % mod; \n } \n }\n \n // Returning the corner value \n // of the matrix\n return paths[n - 1][m - 1];\n }\n};",
"updated_at_timestamp": 1730482010,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int uniquePaths(int n, int m, int[][] grid) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1675768528,
"func_sign": [
"uniquePaths(self, n, m, grid)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n, m = map(int, input().split())\n\n grid = []\n for i in range(n):\n col = list(map(int, input().split()))\n grid.append(col)\n\n ob = Solution()\n print(ob.uniquePaths(n, m, grid))\n print(\"~\")\n",
"solution": "# Back-end function Template for python3\n\nclass Solution:\n def uniquePaths(self, n, m, grid):\n\n mod = 1000000007\n # create a 2D-matrix and initializing with value 0\n paths = [[0]*m for i in range(n)]\n\n # initializing the left corner if no obstacle there\n if grid[0][0] == 1:\n paths[0][0] = 1\n\n # initializing first column of the 2D matrix\n for i in range(1, n):\n # If not obstacle\n if grid[i][0] == 1:\n paths[i][0] = paths[i-1][0]\n\n # initializing first row of the 2D matrix\n for j in range(1, m):\n # If not obstacle\n if grid[0][j] == 1:\n paths[0][j] = paths[0][j-1]\n\n for i in range(1, n):\n for j in range(1, m):\n # If current cell is not obstacle\n if grid[i][j] == 1:\n paths[i][j] = (paths[i-1][j] + paths[i][j-1]) % mod\n\n # returning the corner value of the matrix\n return paths[-1][-1]\n",
"updated_at_timestamp": 1730482010,
"user_code": "#User function Template for python3\n\nclass Solution:\n def uniquePaths(self, n, m, grid):\n # code here "
}
|
eJxrYJm6gZUBDCJWAhnR1UqZeQWlJUpWCkqGMXmGCiAiJk9JR0EptaIgNbkkNSU+v7QEoaIOKFmro4BFmwFObQY4tBkpGIH0AqUNFHBbSkC3IX7duJyM0G2IR7cRTt3GYI0Q/eTYbwz3O9mOMIY4wgAagFBjyAhJUwVTqFaEjwwgvoKIGUBC2QChAK4Wh1UmhKxCdjDMfCgHGqQYCnBYZYHNKpAhONSjq6SvqwwMiHMWhdFiitv/uKMGM1sQ7wBwMJLgClxpEVYCGcbEQIxEz+d4zMSa14gPbyMF8ksUUMySYhGpxUfsFD0AjjikZA==
|
704,156
|
Minimum Time
|
Youare given time for insertion, deletion and copying, the task is to calculate the minimum time to write N characters on the screen using these operations. Each time youcan insert a character, delete the last character and copy and paste all written characters i.e. after copy operation count of total written character will become twice.
Examples:
Input:
N = 9
, I = 1, D = 2, C = 1
Output:
5
Explanation:
N characters can be written
on screen in 5 time units as shown below,
insert a character
characters = 1, total time = 1
again insert character
characters = 2, total time = 2
copy characters
characters = 4, total time = 3
copy characters
characters = 8, total time = 4
insert character
characters = 9, total time = 5
Input:
N = 1, I = 10, D = 1, C = 5
Output:
10
Explanation:
Insert one character
Your Task:
You don't need to read input or print anything. Complete the function
minTimeForWritingChars
()
which takes
N, I, D
and
C
as input parameters and returns the integer value
Expected Time Complexity:
O(
N
)
Expected Auxiliary Space:
O(
N
)
Constraints:
1 ≤
N≤ 10**6
|
geeksforgeeks
|
Medium
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int minTimeForWritingChars(int N, int I, int D, int C)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nclass GfG\n{\n public static void main(String args[])\n {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while(t-->0)\n {\n int n = sc.nextInt();\n int i = sc.nextInt();\n int d = sc.nextInt();\n int c = sc.nextInt();\n \n Solution ob = new Solution();\n System.out.println(ob.minTimeForWritingChars(n, i, d, c));\n }\n }\n} ",
"script_name": "GfG",
"solution": "None",
"updated_at_timestamp": 1730436740,
"user_code": "//User function Template for Java\n\nclass Solution\n{\n\tpublic int minTimeForWritingChars(int N, int I, int D, int C) \n\t{ \n\t // Your code goes here\n\t} \n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"minTimeForWritingChars(self, N, I, D, C)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n N, I, D, C = input().split()\n N, I, D, C = int(N), int(I), int(D), int(C)\n ob = Solution()\n ans = ob.minTimeForWritingChars(N, I, D, C)\n print(ans)\n",
"solution": "# We define a solution class for finding the minimum time required to write N characters\nclass Solution:\n # We define a function that takes in N, I, D, C as parameters\n def minTimeForWritingChars(self, N, I, D, C):\n # create a dynamic programming table of size N+1\n dp = [0]*(N+1)\n # initialize the first element of dp table as I\n dp[1] = I\n # iterate through the dp table starting from 2nd element\n for idx in range(2, N+1):\n # if the index is even\n if idx % 2 == 0:\n # update the dp table using the minimum of two options:\n # 1. add I to the previous index\n # 2. add C to the previous index divided by 2\n dp[idx] = min(dp[idx-1]+I, dp[idx//2]+C)\n # if the index is odd\n else:\n # update the dp table using the minimum of two options:\n # 1. add I to the previous index\n # 2. add C and D to the (index+1) divided by 2\n dp[idx] = min(dp[idx-1]+I, dp[(idx+1)//2]+C+D)\n # return the last element of the dp table, which represents the minimum time required to write N characters\n return dp[-1]\n",
"updated_at_timestamp": 1727721989,
"user_code": "#User function Template for python3\nclass Solution:\n\tdef minTimeForWritingChars(self, N, I, D, C):\n\t\t# code here"
}
|
eJyVlE1qAzEMhbvIQYTXoejHtjw9SSEpXbSz6CbNYgKBUugRskjJdeNxEmhAmqHyZhb+ePJ70vwsfk+Lh1bPh/qx+gofm+1uCE8QaL0hbAUMAhyWEPr9tn8b+vfXz91wvZbqvfC9hHsyXcAEEcQBC1pg1woIqNIOSWhqjgw2El3Q1CSWmDJofWV0yI7NZovmFKs9ybcnWuCop2V8I0Pxmi2mZpMUaMchNVngiDHVVtU3ls1uCRkFIdcws0eK2exNc0qU0Ra9pvn/OO9GiDyPbHf/JuqhombDt2BoIhlCmYlGPJsyd7OoekOI2R78uqM6t+A5z+2MN8EaTY8bOk2my8/h5fh4BgYTTp8=
|
703,694
|
Minimum product pair
|
Given an array of positive integers. The task is to print the minimum product of any two numbers of the given array.
Examples:
Input:
arr[] = [2, 7, 3, 4]
Output:
6
Explanation :
The minimum product of any two numbers will be 2 * 3 = 6.
Input:
arr[] = [198, 76, 544, 123, 154, 675]
Output :
9348
Explanation :
The minimum product of any two numbers will be 76 * 123 = 9348.
Constraints:
2<= arr.size() <=10**6
1<= arr[i] <=10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1617638860,
"func_sign": [
"public long printMinimumProduct(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 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 Solution ob = new Solution();\n System.out.println(ob.printMinimumProduct(arr));\n }\n scanner.close();\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1727947200,
"user_code": "// User function Template for Java\n\nclass Solution {\n public long printMinimumProduct(int arr[]) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1617638860,
"func_sign": [
"printMinimumProduct(self, a)"
],
"initial_code": "# Initial Template for Python 3\ndef main():\n T = int(input())\n\n while T > 0:\n # Convert input to list of integers\n a = list(map(int, input().strip().split()))\n print(Solution().printMinimumProduct(a))\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n\n def printMinimumProduct(self, arr):\n mn1 = float('inf')\n mn2 = float('inf')\n\n n = len(arr)\n\n # Iterate through the array to find the two smallest numbers\n for i in range(n):\n if arr[i] < mn1:\n mn2 = mn1\n mn1 = arr[i]\n elif arr[i] < mn2:\n mn2 = arr[i]\n\n # Return the product of the two smallest numbers\n return mn1 * mn2\n",
"updated_at_timestamp": 1727947200,
"user_code": "# User function Template for Python 3\n\nclass Solution:\n def printMinimumProduct(self, a):\n # code here\n \n \n "
}
|
eJylVE1LxDAQ9SCevXl95LzITD4bf4ngigddYS91D10QRPBH6P+1zTSHQtM27BTyApl5M5M36c/1393NVbLH237z9KWO7encqQco3rcaRu2gDp+nw2t3eHv5OHfjod+36nuHqTuDC+485x6TgSlZIVKcxKWQczGeF0IJmmAIluAInhAIDSHSwFng06Uy+ruChYNHQIOhLXBfnAYbsAU7sAcHcAOOfeIS/3ylyTDeWFobgSDgBZyAFTACWqCkTSIzA3+YT45NX43yuR/OHenck8ld2dyXq7koJ7wJWEALGAEr4AS8QBBoBGIpoUQWx2m4cOqXQvixfV8fnEtmZCpHer15byYn1WrNzHZdbZE2PXVaeeux4o+xTJOEKhGsKTWO1YV6SZW1JaxqvK3QjZPw/Hv/DzUhlls=
|
705,338
|
Sequence Fun
|
You have a sequence 2,5,16,65,........Given an integer n as input.You have to find the value at the nth position in the sequence.
Examples:
Input:
n = 4
Output:
65
Input:
n = 10
Output:
9864101
Constraints:
1 <= n <= 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int NthTerm(int n)"
],
"initial_code": "import java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n public static void main(String[] args) throws IOException\n {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while(T-->0)\n {\n int n = Integer.parseInt(br.readLine().trim());\n Solution ob = new Solution();\n int ans = ob.NthTerm(n);\n System.out.println(ans);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution\n{\n public int NthTerm(int n)\n {\n // initializing the modulo value\n long mod=(long)(1e9+7);\n\n // creating an array to store the nth terms\n long a[]=new long[n];\n\n // setting the first term as 2\n a[0]=2;\n\n // calculating the remaining terms using a loop\n for(int i=1;i<n;i++){\n // calculating the nth term based on previous term\n a[i]=((a[i-1]*(i+1))%mod+1)%mod;\n }\n\n // returning the nth term\n return (int)a[n-1];\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "class Solution\n{\n public int NthTerm(int n)\n {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"NthTerm(self, n)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n = int(input())\n ob = Solution()\n ans = ob.NthTerm(n)\n print(ans)\n print(\"~\")\n",
"solution": "class Solution:\n def NthTerm(self, n):\n ans = 1 # basically sequence is like 5 is 2*2+1.... 16 is like 5*3+1 so it\n # like previous value*(term position )+1 so we iterative till the nth position\n mod = 10**9 + 7\n for i in range(1, n+1):\n ans = (ans * i) + 1\n ans %= mod # taking mod as mentioned in question\n return ans\n",
"updated_at_timestamp": 1731586315,
"user_code": "#User function Template for python3\n\nclass Solution:\n\tdef NthTerm(self, n):\n\t\t# Code here"
}
|
eJytVctOw0AM5IDEb1Q5V2jttdc2X4JEEAfogUvooZWQEIiPgF/kxj/gJJVIWjaPlj1UUdeemXjGyvv55/fFWXOuv/zh5qV4rNbbTXG1KKCsoFguitXzenW/WT3cPW03uyssq7eyKl6Xi7364CfTYwpBAOivVscb6faKIYDYALD3j8IAJVJW02FE9ms/O7gOvHAWHZQgOGhPbJ8SjZKBoebeouFomWr+DFOCxCRM1gPv8B+CuxRAZyBOUlZqAWqVkjIMLiGycnQsRDbQGH0kHBXM/0/+aMTGMWb8RB4ZVjKSkBLKyFC4GYoXNTOJ9Q+148nbHJMys1DdkNgLAWtJZEYE0YcW0VAcCxqhaF7DmUwrYcxF2hUIi8hs3f8iHDwAoiG3Ub8OtLs1LGiCTcSYQmJOk+J1RLoQwIK4HRPTVb/XxITNcOgA/rSouV1KQaMPqCNoQE3PulbaNH5g0cje1WPycKMJO7y6PouG4ysL8+PT3GZCcHLyDCmxYK3kUPkAxATPO5+e4xcUAmhQ0jZpI1+6mYPduy7LaUIH9vb24/IH14k7Ow==
|
702,875
|
Drive the car
|
You are a car driver tasked with driving on a track divided into sub-tracks. The car can travel "k" kilometers on each sub-track. If the car can't cover a sub-track, you can add petrol, with each unit increasing the car's range by one kilometer. Return the minimum units of petrol needed for the car to cover all sub-tracks. If no extra petrol is required, return -1.
Examples:
Input:
arr[] = [2, 5, 4, 5, 2], k = 7
Output:
-1
Explanation:
No extra petrol required, as k is greater than all the elemnts in the array hence
-1
.
Input:
arr[] = [1, 6, 3, 5, 2], k = 4
Output:
2
Explanation:
You are given 5 sub-tracks with different kilometers. Your car can travel 4 km on each sub-track. So, when you come on sub-track 2nd you have to cover 6 km of distance, so you need to have 2 unit of petrol more to cover the distance, for 3rd sub-track, your car can travel 4km and you need extra 1 unit of pertrol.So if you add 2 units of petrol at each sub-track you can cover all the subtracks.
Constraints:
1 ≤ arr.size() ≤ 10**6
1 ≤ k ≤ 10**6
1 ≤ arr[i] ≤ 10**6
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"public int required(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 System.out.println(ob.required(nums, d));\n }\n }\n}\n",
"script_name": "Main",
"solution": "None",
"updated_at_timestamp": 1727947200,
"user_code": "// User function Template for Java\n\nclass Solution {\n // Function to calculate the difference between the maximum element in the array and\n // a given number k\n public int required(int[] arr, int k) {\n // Your code goes here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"required(self, arr, k)"
],
"initial_code": "def main():\n T = int(input())\n\n while T > 0:\n arr = list(map(int, input().strip().split()))\n d = int(input().strip())\n ob = Solution()\n print(ob.required(arr, d))\n T -= 1\n\n\nif __name__ == \"__main__\":\n main()\n",
"solution": "class Solution:\n # Function to calculate the difference between the maximum element in the array and a given number k\n def required(self, arr, k):\n max_element = max(arr) # Find the maximum element in the array\n\n # If k is greater than or equal to the maximum element, return -1\n if k >= max_element:\n return -1\n\n # Return the difference between the maximum element and k\n return max_element - k\n",
"updated_at_timestamp": 1727947200,
"user_code": "#User function Template for python3\n\nclass Solution:\n # Function to calculate the difference between the maximum element in the array and a given number k\n def required(self, arr, k):\n # Your code goes here\n \n"
}
|
eJxrYJmaycoABhFJQEZ0tVJmXkFpiZKVgpJhTB4IKekoKKVWFKQml6SmxOeXlkBldYFySrU6CmgaDMBAgQAdk2cKpnGYbQpVhMV8BSiMyTMizWEIq3H5yBIMsGmGuEfBBKxAAcwzJOAF/KED8wPESlKMgOhQwEPBrSEtfMjUBg9UMjQbKRhDg8IId6wY4bYWEgeG5DsAkSpxplMD/LFsYIA7rVIhUlDTC1kJxoi4LGeExyPEBBMF4YSWhnDlTpz6IcmIgnSEEcD4nIAv90AovFEcO0UPAGE/f10=
|
703,767
|
Factor OR Multiple
|
Given an array A comprising of N non-zero, positive integers and an integer X, find the bitwiseOR of all such elements in the array that are a multiple of X. The result of OR operation should be in decimal form.If no multiple of X is found, the answer should be 0.
Examples:
Input:
N =
4 ,
X =
2
A =
{3 , 4 , 3 , 9}
Output:
4
Explanation:
Only multiple of 2 in array is 4.
Hence it is printed.
Input:
N =
5 ,
X =
3
A =
{9 , 3 , 1 , 6 , 1}
Output:
15
Explanation:
Multiples of 3 in array are 9,3 and 6.
Their OR value is 15 and thus the Output.
Input:
N =
3 ,
X =
8
A =
{1,2,3}
Output:
0
Explanation:
There are no multiples of 8 in the array.
So, Output is 0.
Constraints:
1 <= N,X,A[i] <= 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int factorOrMultiple(int N,int X,int A[])"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n int N = Integer.parseInt(S[0]);\n int X = Integer.parseInt(S[1]);\n \n String arr[] = read.readLine().split(\" \");\n \n int[] A = new int[N];\n \n for(int i=0 ; i<N ; i++)\n A[i]=Integer.parseInt(arr[i]);\n\n Solution ob = new Solution();\n System.out.println(ob.factorOrMultiple(N,X,A));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "class Solution {\n static int factorOrMultiple(int N, int X, int[] A) {\n int[] temp = new int[N]; // Array to store the numbers that are divisible by X\n int k = -1;\n for (int i = 0; i < N; i++) {\n if (A[i] % X == 0) temp[++k] = A[i]; // Numbers divisible by X are stored in temp\n }\n if (k == -1) return 0; // If there's no number divisible by X, return 0.\n else if (k == 0) return temp[k]; // If there's only 1 number divisible by X, return that number.\n else {\n int s = temp[0];\n // If there are multiple numbers divisible by X, Perform Logical OR\n // among those numbers and return the result.\n for (int j = 1; j <= k; j++) s = s | temp[j];\n return s;\n }\n }\n}\n;\n",
"updated_at_timestamp": 1730473199,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int factorOrMultiple(int N,int X,int A[]) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"factorOrMultiple(self, N , X ,A)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n N, X = map(int, input().split())\n\n A = list(map(int, input().split()))\n\n ob = Solution()\n print(ob.factorOrMultiple(N, X, A))\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nclass Solution:\n def factorOrMultiple(self, N, X, A):\n\n temp = [0]*N # List to store the numbers that are divisible by X\n k = -1\n\n for i in range(N):\n if(A[i] % X == 0):\n k += 1\n temp[k] = A[i] # Numbers divisible by X are stored in temp\n\n if(k == -1):\n return 0 # If there's no number divisible by X, return 0.\n\n elif(k == 0):\n # If there's only 1 number divisible by X, return that number.\n return temp[k]\n\n else:\n s = temp[0]\n\n # If there are multiple numbers divisible by X, Perform Logical OR\n # among those numbers and return the result.\n for j in range(1, k+1):\n s = s | temp[j]\n\n return s\n",
"updated_at_timestamp": 1730473199,
"user_code": "#User function Template for python3\n\nclass Solution:\n def factorOrMultiple(self, N , X ,A):\n # code here "
}
|
eJzFlbtuFEEURAkI+IzSxBa6j7798JcgeRABbEDA4GAtWUJY/gjzv65u2zyC5jGy2E1mpdHUrXuqZvr25bfjqxfj9+YT/1x8WT5ul1fH5RyLrpsKYt0CvGrABBZwgQeSIAVC1m05w3K4vjy8Px4+vPt8dXx8Ovu63fDu1zP8qplRKJxgFaZDypDav+tUpHVLqNAMN+QE7ZKREWpTORWTiaAatF8UZnBHSohApt+CWtEab5MDTavPB1jETD/ANalClwWeB8CE7CiGqmgyZgg30sI5mXNix5yK/LAM56QRVx6MK6fNMdtEjaErbWuDU6CgZDQWggEqGWlwTiERmjdpJNeHFhixWe1loQNzOA14Ztx13pjo9Gfk2BkySb0yHPHUGjDtzk9GRgmNFIlP5tjUymwIF5Vx4cqkxoaHIEtXr9LTUZmbZ1wzgKTFDqsTCpyW2VXuU7tZJZ4RNudp6jgZeu4VIdbW3zji7Ct7esRKd4VKlXhZFmfMbvNtf4t0Wsaan7WPf5kefsSXg0vviPCn5jfp3cdD+f/Y/ib1dPFhT367bP0HX7Ow+bF41re1759OlkvSadm/HyJReIyY7T9IXOZH31PPe7VP/ZHf+5V/e/f6HmEPIOA=
|
712,224
|
Outermost Parentheses
|
A valid parentheses string is either empty"","(" + X+ ")", or X+ Y, where Xand Yare valid parentheses strings, and+represents string concatenation.
Examples:
Input:
s = "(()())(())"
Output:
"()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input:
s = "()()"
Output:
""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Constraint:
1 <= s.length <= 10**5
s[i] is either '(' or ')'
s
is a valid parentheses string.
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1664428826,
"func_sign": [
"public static String removeOuter(String s)"
],
"initial_code": "import java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int t;\n t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n\n String s;\n s = br.readLine();\n\n Solution obj = new Solution();\n String res = obj.removeOuter(s);\n\n System.out.println(res);\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1730481674,
"user_code": "class Solution {\n public static String removeOuter(String s) {\n // code here\n }\n}\n"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1665577777,
"func_sign": [
"removeOuter(self, S)"
],
"initial_code": "# Initial Template for Python 3\n# Position this line where user code will be pasted.\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n s = input()\n ob = Solution()\n res = ob.removeOuter(s)\n print(res)\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nfrom collections import deque\n\n\nclass Solution:\n # Function to remove the outermost parentheses from a given string.\n def removeOuter(self, S):\n st = deque()\n ans = ''\n\n # iterating over each character in the string.\n for ch in S:\n # if the character is ')', removing the corresponding '(' from the stack.\n if ch == ')':\n st.pop()\n # if there are still parentheses in the stack, adding the character to the answer string.\n if st:\n ans += ch\n # if the character is '(', adding it to the stack.\n if ch == '(':\n st.append(ch)\n\n return ans\n",
"updated_at_timestamp": 1730481674,
"user_code": "#User function Template for python3\n\nclass Solution:\n def removeOuter(self, S):\n # Code here"
}
|
eJy1VEEKwjAQ9CD4jZJTForQqy8RrHjQHgSJBVsQRPER+l+TJq1J293EUHMIDdnZnZls9zl/XxazZq1P8mNzY0dR1hVbJSzLBYdcsDRhxbUs9lVx2J3rytzm4iHv7mnSQ3DAMSodgpIwAtckHUdCFEdPPaAqKrhEqxB/piZWbZ6MJgK42cFUIT3hLQlo4/EK1gJnERUwDP4WWm6rWuvgdJWOu/7iRP4BGffsVeLCSC24nIh2w2l7vMF4c+oVRrrJ2wK/tltG2mYmx1TuuXL6jlrjwxJiKATqoeVoAeoIA3mZ1jcBUdsi27Oo6Rb0t/hGIOaK1UbffN3sN5KoURA6eNz00d0u/tzuQ6Uh77Z9LT+jEeS4
|
704,749
|
12 hour clock subtraction
|
Given two positive integersnum1andnum2, subtract num2 from num1 on a12 hour clock rather than a number line.Note: Assume the Clock starts from 0 hour to 11 hours.
Examples:
Input:
num1 =
7,
num2 =
5
Output:
2
Explanation:
7-5 = 2. The time in a 12 hour clock is 2.
Input:
num1 =
5,
num2 =
7
Output:
10
Explanation:
5-7 = -2. The time in a 12 hour clock is 10.
Constraints:
1 <= num1,num2 <= 10**3
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static int subClock(int num1, int num2)"
],
"initial_code": "//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n public static void main(String args[]) throws IOException {\n BufferedReader read =\n new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n String S[] = read.readLine().split(\" \");\n \n int num1 = Integer.parseInt(S[0]);\n int num2 = Integer.parseInt(S[1]);\n\n Solution ob = new Solution();\n System.out.println(ob.subClock(num1,num2));\n \nSystem.out.println(\"~\");\n}\n }\n}",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\nclass Solution {\n static int subClock(int num1, int num2) {\n int ans = num1 - num2; // Subtracting num2 from num1\n ans %= 12; // Taking modulus of ans with 12\n if (ans < 0) // Checking if ans is negative\n ans += 12; // Adding 12 to ans if it is negative\n return ans; // Returning the answer\n }\n}\n;\n",
"updated_at_timestamp": 1730476392,
"user_code": "//User function Template for Java\n\nclass Solution {\n static int subClock(int num1, int num2) {\n // code here\n }\n};"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"subClock(self, num1, num2)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n num1, num2 = map(int, input().split())\n\n ob = Solution()\n print(ob.subClock(num1, num2))\n print(\"~\")\n",
"solution": "class Solution:\n\n # Function to subtract two given clock timings.\n def subClock(self, num1, num2):\n\n ans = num1 - num2 # Subtracting num2 from num1\n ans %= 12 # Taking modulus 12 to get the remainder.\n if ans < 0: # If remainder is negative, adding 12 to make it positive.\n ans += 12\n\n return ans # Returning the difference.\n",
"updated_at_timestamp": 1730476392,
"user_code": "#User function Template for python3\n\nclass Solution:\n def subClock(self, num1, num2):\n # code here"
}
|
eJy9VL1OwzAQZkDiNU6ZK2T7fP7hSZAIYoAOLKFDKyEhEA8BKxvvyZ2dwZDYDajFw8U9p9/PnS+vp++fZydpXX7w5uqpux82u213AZ3tB01gQj8YBMc/lIJI/UAOLHUr6NaPm/Xtdn1387Dbjv/Ruh9e+JUijqnueQUFOAoe41LgY48EjK76QYHWNWhVws2CMqE2oE0/xAghJMmsOUbJI6tmFz5EcGQrJDMcWMQZPmEgka45gifeGclpI8lIiml5g5IiVaENCd2lGIro5lhtcmMJyKJhjTF4B459MbN1gXmQvFjmBYZX0ysWVmmOjjUIDwhNAs0FJSKwlrUgorCw5BDAe8+qnQM+rvUxkahJbRt1xtGxk85lz7xADCYhWYqtNRWLis7fRpsbyT0y6ZH6xZ1LW0oHLud9fi2kR7Ob0/iDlEumQacrW0NSRa2mNVGQJ0Zw2gitoSkmUSZn0Sz6vag1PS0XuagLvcRfDCQceSK/lRAOVsPlbv5gx9TtyMXcdzN142o2dR/5wzhOMf7fGC9gPRDt9dv5F/m7Q0o=
|
700,133
|
Check for Binary
|
Given a non-empty sequence of characters str, return true if sequence is Binary, else return false
Examples:
Input:
str = 101
Output:
1
Explanation:
Since string contains only 0 and 1, output is 1.
Input:
str = 75
Output:
0
Explanation:
Since string contains digits other than 0 and 1, output is 0.
Constraints:
1 <=T<= 50
1 <=Length of str<= 10000
|
geeksforgeeks
|
Easy
|
{
"class_name": "GfG",
"created_at_timestamp": 1617123105,
"func_sign": [
"boolean isBinary(String str)"
],
"initial_code": "import java.util.*;\nclass checkBinary\n{\n\tpublic static void main(String args[])\n\t{\n\t\tScanner sc = new Scanner(System.in);\n\t\tint T = sc.nextInt();\n\t\tsc.nextLine();\n\t\twhile(T>0)\n\t\t{\n\t\t\tString str = sc.nextLine();\n\t\t\tGfG g = new GfG();\n\t\t\tboolean b = g.isBinary(str);\n\t\t\tif(b== true)\n\t\t\t\tSystem.out.println(1);\n\t\t\telse\n\t\t\t System.out.println(0);\n\t\tT--;\n\t\t\nSystem.out.println(\"~\");\n}\n\t}\n}\n\n",
"script_name": "checkBinary",
"solution": "class Solution {\n // Function to check if the given string is binary or not\n boolean isBinary(String str) {\n // Traverse through each character in the string\n for (int i = 0; i < str.length(); i++) {\n // Check if the character is not '0' or '1'\n if (str.charAt(i) != '0' && str.charAt(i) != '1')\n // Return false if the character is not binary\n return false;\n }\n // Return true if all characters are binary\n return true;\n }\n}\n",
"updated_at_timestamp": 1729753320,
"user_code": "class GfG\n{\n\tboolean isBinary(String str)\n\t{\n\t //Your code here\n\t}\n}"
}
|
{
"class_name": null,
"created_at_timestamp": 1617123105,
"func_sign": [
"isBinary(str)"
],
"initial_code": "# Your code goes here\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n str = input().strip()\n if isBinary(str):\n print(1)\n else:\n print(0)\n print(\"~\")\n",
"solution": "# Code Added By Piyush Doorwar\ndef isBinary(str):\n # code here\n\n cnt = 0\n # iterating over each character in the string\n for i in str:\n # checking if the character is 0 or 1\n if i == '0' or i == '1':\n # incrementing the count if character is 0 or 1\n cnt += 1\n\n # checking if all characters in the string are either 0 or 1\n if cnt == len(str):\n return True\n\n # returning False if there are characters other than 0 and 1 in the string\n return False\n",
"updated_at_timestamp": 1729753320,
"user_code": "# Return true if str is binary, else false\ndef isBinary(str):\n #code here"
}
|
eJxrYJlqy8oABhFmQEZ0tVJmXkFpiZKVgpJhTJ5BTJ6SjoJSakVBanJJakp8fmkJQrIOKFmro4CqwxAOSNZqAAek22oAg2RohQLSHWxoZGxiamZuYYnbVgMcWkm2KzEpOSU1LT0jM4tkuwwNDYzw+A6XNgMsgNzkgMs0MoxDDXa8PsOZ0GJi0CKe5MCBRkcKMD6QQpj0IEak3ZgYcOolJ5BR/YOWkyjxXkZmRgbp6Q3JV9TxEjBoqBJJWNMOLgeTEK2xU/QA9y+a8w==
|
702,837
|
Count the triplets
|
Example 1:
Examples:
Input:
N = 4
arr[] = {1, 5, 3, 2}
Output:
2
Explanation:
There are 2 triplets:
1 + 2 = 3 and 3 +2 = 5
Input:
N = 3
arr[] = {2, 3, 4}
Output:
0
Explanation:
No such triplet exits
Your Task:
You don't need to read input or print anything. Your task is to complete the function
countTriplet()
which takes the array
arr[]
and
N
as inputs and returns the triplet count
Expected Time Complexity:
O(N**2
)
Expected Auxiliary Space:
O(1)
Constraints:
1 ≤ N ≤ 10**3
1 ≤ arr[i] ≤ 10**5
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1729253195,
"func_sign": [
"int countTriplet(int arr[])"
],
"initial_code": "// Initial Template for Java\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\n//Position this line where user code will be pasted.\n\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(br.readLine());\n while (t-- > 0) {\n String line = br.readLine();\n String[] tokens = line.split(\" \");\n\n // Create an ArrayList to store the integers\n ArrayList<Integer> array = new ArrayList<>();\n\n // Parse the tokens into integers and add to the array\n for (String token : tokens) {\n array.add(Integer.parseInt(token));\n }\n\n int[] arr = new int[array.size()];\n int idx = 0;\n for (int i : array) arr[idx++] = i;\n Solution obj = new Solution();\n int res = obj.countTriplet(arr);\n\n System.out.println(res);\n\n System.out.println(\"~\");\n }\n }\n}\n",
"script_name": "GFG",
"solution": "class Solution {\n // Function to count the number of triplets with the given condition.\n int countTriplet(int arr[]) {\n int n = arr.length;\n // Sorting the array in ascending order.\n Arrays.sort(arr);\n\n // Initializing the count of triplets as 0.\n int ans = 0;\n\n // Iterating over the array in reverse order.\n for (int i = n - 1; i >= 0; i--) {\n // Initializing two pointers, one at the beginning and one at i-1.\n int j = 0;\n int k = i - 1;\n\n // Using two-pointer approach to find the triplets.\n while (j < k) {\n // If the given condition is satisfied, increment the count and move the\n // pointers.\n if (arr[i] == arr[j] + arr[k]) {\n ans++;\n j++;\n k--;\n }\n // If the sum is less than the target, move the left pointer.\n else if (arr[i] > arr[j] + arr[k])\n j++;\n // If the sum is greater than the target, move the right pointer.\n else\n k--;\n }\n }\n // Returning the count of triplets.\n return ans;\n }\n}",
"updated_at_timestamp": 1730829083,
"user_code": "// User function Template for Java\n\nclass Solution {\n int countTriplet(int arr[]) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1729253195,
"func_sign": [
"countTriplet(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.countTriplet(arr)\n print(res)\n print(\"~\")\n t -= 1\n",
"solution": "class Solution:\n\n def countTriplet(self, arr):\n # Sorting the array in ascending order.\n n = len(arr)\n arr.sort()\n\n # Initializing the count of triplets as 0.\n ans = 0\n\n # Iterating over the array in reverse order.\n for i in range(n - 1, -1, -1):\n\n # Initializing two pointers, one at the beginning and one at i-1.\n j = 0\n k = i - 1\n\n # Using two-pointer approach to find the triplets.\n while j < k:\n # If the given condition is satisfied, increment the count and move the pointers.\n if arr[i] == arr[j] + arr[k]:\n ans += 1\n j += 1\n k -= 1\n # If the sum is less than the target, move the left pointer.\n elif arr[i] > arr[j] + arr[k]:\n j += 1\n # If the sum is greater than the target, move the right pointer.\n else:\n k -= 1\n\n # Returning the count of triplets.\n return ans\n",
"updated_at_timestamp": 1730829083,
"user_code": "# User function Template for python3\nclass Solution:\n\tdef countTriplet(self, arr):\n\t\t# code here"
}
|
eJytVMtKBDEQ9CB+gzeLOS/SnXf8EsEVD7oHL+MedkEQxY/Q/7U7EfYByeyIM0wnzJCqSlVPPs+/ry7OynV7KZO7t+F5XG83ww0GXo5MMARLcARPCIRISIRMYKJhgWH1ul49blZPDy/bze86Q8vxYzkO7wsco8ky5AyDnGCRIxxygG8AsWsDqR6VVYSIMFWm0lSt6lPhswUqpPH1YeNho0eQMcnI+jLqB98E7goWVXJpSVqilqDFa3FarBajhRsMTWtRKCpHIakslabyVKLKVKmyadCkjkEs8VkJTqxBhLC0zAi99Pj4nrthY0VCiMLPxLLespNoOIAjJ3CWvjVsDIw1TgI1YSZBNdIXU12ZH2y8tWnu6P2DigPD06TlnT+v1bO9Jfv56JvZEMXEHQ5JI1Yo/EHO7uyIpxweJwd7WrK5C/d/eHuJlyaeTj12Wy5PBSGnw2Rb3n9d/wD+zqWO
|
704,948
|
Sum Palindrome
|
Given a number, reverse it and add it to itself unless it becomes a palindrome or return -1 if the number of iterations becomes more than 5. Return that palindrome number if it becomes a palindrome else returns -1.Examples :
Examples:
Input:
n = 23
Output:
55
Explanation:
reverse(23) = 32,then 32+23 = 55 which is a palindrome.
Input:
n = 73
Output:
121
Explanation:
reverse(73) = 37,then 37+73 = 110 which is not a palindrome, again reverse(110)= 011, then 110+11 = 121 which is a palindrome.
Expected Time Complexity:
O(n)
Expected Auxiliary Space:
O(1)
Constraints:
1 <= n <= 10**4
|
geeksforgeeks
|
Easy
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"static long isSumPalindrome(long n)"
],
"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 = new BufferedReader(new InputStreamReader(System.in));\n int t = Integer.parseInt(read.readLine());\n while (t-- > 0) {\n long n = Integer.parseInt(read.readLine());\n Solution ob = new Solution();\n\n System.out.println(ob.isSumPalindrome(n));\n }\n }\n}",
"script_name": "GFG",
"solution": "None",
"updated_at_timestamp": 1727776457,
"user_code": "// User function Template for Java\nclass Solution {\n static long isSumPalindrome(long n) {\n // code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1615292571,
"func_sign": [
"isSumPalindrome(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.isSumPalindrome(n))\n print(\"~\")\n",
"solution": "class Solution:\n def isSumPalindrome(self, n):\n # Function to reverse a number\n def reverse(n):\n rev_num = 0\n while n > 0:\n rev_num = rev_num * 10 + n % 10\n n = n // 10\n return rev_num\n\n # Function to check if a number is palindrome\n def isPalindrome(n):\n return reverse(n) == n\n\n count = 0\n # Iterate until the number is a palindrome or count reaches 5\n while (isPalindrome(n) == False) and count < 5:\n k = reverse(n)\n n += k\n count += 1\n\n # Return the final number if it is palindrome, otherwise return -1\n if isPalindrome(n):\n return n\n return -1\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\n\nclass Solution:\n def isSumPalindrome (self, n):\n # code here "
}
|
eJy1VctOwzAQ5MCBz4hypaD41Th8CRJBHKAHLqaHVkJCWHwE/C9je+OmwhsCgVUlW7FnZ+yddd9OP+TZSYzrc0xuXupHt93v6quqFr3rEPWqqjfP2839bvNw97Tf0WpY6p3vXf26qkYo2TvRACobySDjso87SglUpO2dRfSuRfAKIj5t9GlvKSPohJSCk4Ml5iCdbdfI364NK0EpUqGhQpfymMCu9JBt3VoAlDaYI7FmMhtEzDaiOJrSBOrL8gNtE25aIHDZCNAiIBXB1oaKk1B+APoB6xOcYUyywoVhmwrCDM6Lg9qu+c5HhwvMZz98upg4Y3JbE9ykMIQDYgDOYOAqRzifoT6jfU7gKQfLLcjFKrFGTp7x2PYqcw1MPE/ztYjUnRO1lEKEH1NFkW/YTjl3sNCorUnCHBcpKYmNPmgpde5Vrl/LHVMw9EgUxCzrKHpDsvT55l5o7fIzylp7sbctMmg7be5oLnIY+w+ghFC/lf432qc6pvwqLH8W5rwLPzXvjB7/b39HKlAGQsuWvDVm6Njb98tPwThyPA==
|
714,002
|
Count Binary Strings With No Consecutive 1s
|
Given an integer N. Your task is to find the number of binary strings of length N having no consecutive 1s.As the number can be large, return the answer modulo10^9+7.
Examples:
Input:
N = 3
Output:
5
Explanation:
All the binary strings of length 3 having
no consecutive 1s are "000", "001", "101",
"100" and "010".
Input:
N = 2
Output:
3
Explanation:
All the binary strings of length 2 having no
consecutive 1s are "10", "00" and "01".
Constraints:
1 ≤ N≤ 10**18
|
geeksforgeeks
|
Hard
|
{
"class_name": "Solution",
"created_at_timestamp": 1676008969,
"func_sign": [
"public int countStrings(long N)"
],
"initial_code": "// Initial Template for Java\n// 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 BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int t =\n Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n while (t-- > 0) {\n\n long N = Long.parseLong(br.readLine().trim());\n\n Solution ob = new Solution();\n System.out.println(ob.countStrings(N));\n \nSystem.out.println(\"~\");\n}\n }\n}\n",
"script_name": "GFG",
"solution": "// Back-end complete function Template for Java\n\nclass Solution {\n public int mod = 1000000007;\n\n public void multiply(int[][] a, int[][] b) {\n\n int mul[][] = new int[3][3];\n\n for (int i = 0; i < 3; i++) {\n\n for (int j = 0; j < 3; j++) {\n\n for (int k = 0; k < 3; k++) {\n long temp = ((long)a[i][k] * b[k][j]) % mod;\n mul[i][j] += temp;\n mul[i][j] %= mod;\n }\n }\n }\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n a[i][j] = mul[i][j];\n }\n }\n }\n\n public int power(int[][] mat, long N) {\n int M[][] = {{1, 1, 0}, {1, 0, 0}, {0, 1, 0}};\n\n if (N == 1) {\n return (mat[0][0] + mat[0][1]) % mod;\n }\n\n power(mat, N / 2);\n\n multiply(mat, mat);\n\n if (N % 2 != 0) {\n multiply(mat, M);\n }\n\n return (mat[0][0] + mat[0][1]) % mod;\n }\n\n int countStrings(long N) {\n\n int[][] mat = {{1, 1, 0}, {1, 0, 0}, {0, 1, 0}};\n if (N == 2) return 3;\n if (N == 1) return 2;\n\n return power(mat, N);\n }\n}",
"updated_at_timestamp": 1729753320,
"user_code": "// User function Template for Java\n\nclass Solution {\n public int countStrings(long N) {\n // Code here\n }\n}"
}
|
{
"class_name": "Solution",
"created_at_timestamp": 1676008969,
"func_sign": [
"countStrings(self, N)"
],
"initial_code": "# Initial Template for Python 3\n\nif __name__ == '__main__':\n T = int(input())\n while T > 0:\n ob = Solution()\n print(ob.countStrings(int(input())))\n T -= 1\n print(\"~\")\n",
"solution": "# Back-end complete function Template for Python 3\n\nmod = 10**9+7\n\n\nclass Solution:\n # Function to perform matrix multiplication\n def multiply(self, a, b):\n mul = [[0 for j in range(3)] for j in range(3)]\n\n for i in range(3):\n for j in range(3):\n for k in range(3):\n temp = (a[i][k] * b[k][j]) % mod\n mul[i][j] += temp\n mul[i][j] %= mod\n\n for i in range(3):\n for j in range(3):\n a[i][j] = mul[i][j]\n\n # Function to calculate the power of a matrix\n def power(self, mat, N):\n M = [[1, 1, 0], [1, 0, 0], [0, 1, 0]]\n\n if (N == 1):\n return (mat[0][0] + mat[0][1]) % mod\n\n self.power(mat, N // 2)\n self.multiply(mat, mat)\n\n if (N % 2 != 0):\n self.multiply(mat, M)\n\n return (mat[0][0] + mat[0][1]) % mod\n\n # Function to count the number of possible strings\n def countStrings(self, N):\n mat = [[1, 1, 0], [1, 0, 0], [0, 1, 0]]\n\n # Base cases\n if (N == 2):\n return 3\n if (N == 1):\n return 2\n\n return self.power(mat, N-2)\n",
"updated_at_timestamp": 1729753320,
"user_code": "#User function Template for python3\nclass Solution: \n def countStrings(self, N): \n # Code here\n"
}
|
eJxrYJm6noUBDCJWABnR1UqZeQWlJUpWCkqGMXlApKSjoJRaUZCaXJKaEp9fWgKVNIrJqwNK1uoooOowwqnDGIcOY5LtMCHZDlOcOkxx6DDDqcMChw5znDoMcTnLArfXDXFoMTTA7RVcfjHCrcfM3AyXLhNw9OOOHVyeguhDNoB0M8zAWnHHGq44AIrHxJjgSSA4w9UYqhvF4bgj1MTMyMwSr1ExkECgookQoyg1CxK0FiAyBpo2yAhobKaQagZGQomB+otweomdogcAab6DIA==
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.