⚡ SubArray | 🚀 Beats 95% | 🔄 Sorting | 🍀Easy with comments
Intuition\nGiven a sequence of numbers, we can determine if it is arithmetic by checking if the difference between every two consecutive elements is the same. T
# Intuition\nGiven a sequence of numbers, we can determine if it is arithmetic by checking if the difference between every two consecutive elements is the same. To solve this problem for subarrays, we can iterate through each query, extract the corresponding subarray, and then check if it can be rearranged into an arithmetic sequence.\n\n# Approach\n- Iterate through each query represented by the ranges [l[i], r[i]].\n- For each query, extract the subarray from nums using the specified range.\n- Check if the subarray can be rearranged into an arithmetic sequence.\n- To check rearrangement, calculate the difference between the first two elements and then iterate through the subarray to ensure that the differences between consecutive elements match.\n- If the subarray satisfies the arithmetic condition, add true to the result list; otherwise, add false.\n\n# Complexity\n- Time complexity: O(q * n), where q is the number of queries, and n is the maximum size of the subarrays. The main loop iterates through each query, and within each query, we iterate through the subarray once.\n\n- Space complexity: O(n), where n is the maximum size of the subarrays. The space is used to store the subarray.\n\n\n# Code\n```\nclass Solution {\n  // This function checks if the given array can be rearranged into an arithmetic sequence.\n  private static boolean check(int[] arr) {\n    // Sort the array in ascending order.\n    Arrays.sort(arr);\n\n    // Calculate the common difference between consecutive elements.\n    int diff = arr[1] - arr[0];\n\n    // Check if the differences between consecutive elements are consistent.\n    for(int i = 1; i < arr.length; i++) {\n      if(arr[i] - arr[i-1] != diff) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  // This function processes queries to determine if corresponding subarrays can be rearranged into arithmetic sequences.\n  public static List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n    // Get the number of queries.\n    int q_count = l.length;\n    // Initialize a list to store the results.\n    List<Boolean> ans = new ArrayList<>();\n\n    // Iterate through each query.\n    for(int i = 0; i < q_count; i++) {\n      int left = l[i];\n      int right = r[i];\n      int length = right - left + 1;\n\n      // Extract the subarray from nums based on the current query.\n      int arr[] = new int[length];\n      for(int k = 0, m = left; k < length && m <= right; k++, m++) {\n        arr[k] = nums[m];\n      }\n\n      // Check if the subarray can be rearranged into an arithmetic sequence and add the result to the list.\n      ans.add(check(arr));\n    }\n\n    // Return the final list of results.\n    return ans;\n  }\n}\n\n```
['Array', 'Sorting', 'Java']