{"record":{"id":"b4ffe8865f82096f","repo":"TheAlgorithms/Java","slug":"k-must-be-between-1-and-the-size-of-the-array","errorCode":null,"errorMessage":"k must be between 1 and the size of the array","messagePattern":"k must be between 1 and the size of the array","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/maths/FindKthNumber.java","lineNumber":18,"sourceCode":"package com.thealgorithms.maths;\n\nimport java.util.Collections;\nimport java.util.PriorityQueue;\nimport java.util.Random;\n\n/**\n * Use a quicksort-based approach to identify the k-th largest or k-th max element within the provided array.\n */\npublic final class FindKthNumber {\n    private FindKthNumber() {\n    }\n\n    private static final Random RANDOM = new Random();\n\n    public static int findKthMax(int[] array, int k) {\n        if (k <= 0 || k > array.length) {\n            throw new IllegalArgumentException(\"k must be between 1 and the size of the array\");\n        }\n\n        // Convert k-th largest to index for QuickSelect\n        return quickSelect(array, 0, array.length - 1, array.length - k);\n    }\n\n    private static int quickSelect(int[] array, int left, int right, int kSmallest) {\n        if (left == right) {\n            return array[left];\n        }\n\n        // Randomly select a pivot index\n        int pivotIndex = left + RANDOM.nextInt(right - left + 1);\n        pivotIndex = partition(array, left, right, pivotIndex);\n\n        if (kSmallest == pivotIndex) {\n            return array[kSmallest];\n        } else if (kSmallest < pivotIndex) {","sourceCodeStart":1,"sourceCodeEnd":36,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/FindKthNumber.java#L1-L36","documentation":"Thrown by FindKthNumber.findKthMax(int[] array, int k) when k is less than 1 or greater than the array length. The method finds the k-th largest element using the QuickSelect algorithm, so k must map to a valid 1-based ranking position. The check runs before any partitioning begins.","triggerScenarios":"Calling findKthMax with k <= 0 (e.g., k=0 or k=-1), or calling with k > array.length (e.g., findKthMax(new int[]{3}, 2)). Passing k on an empty array also triggers it because array.length is 0, so any k >= 1 fails the k > array.length test.","commonSituations":"Using a user-supplied or computed k value without clamping it to the array bounds. Off-by-one errors where 0-based indices are passed to a 1-based k parameter. Passing an empty array from upstream filtering that removed all elements.","solutions":["Validate k against the array bounds before calling: ensure 1 <= k <= array.length.","If k comes from user input or external data, clamp or reject it upstream before reaching this method.","Guard against empty arrays before invoking: check array.length > 0 first."],"exampleFix":"// before\nint result = FindKthNumber.findKthMax(arr, userK);\n\n// after\nif (arr.length == 0 || userK < 1 || userK > arr.length) {\n    throw new IllegalArgumentException(\"Invalid k=\" + userK + \" for array of length \" + arr.length);\n}\nint result = FindKthNumber.findKthMax(arr, userK);","handlingStrategy":"validation","validationCode":"if (array == null || array.length == 0 || k < 1 || k > array.length) {\n    throw new IllegalArgumentException(\"k must be between 1 and \" + (array == null ? 0 : array.length));\n}\nint result = FindKthNumber.findKthMax(array, k);","typeGuard":"static boolean isValidK(int[] array, int k) {\n    return array != null && array.length > 0 && k >= 1 && k <= array.length;\n}","tryCatchPattern":"try {\n    int result = FindKthNumber.findKthMax(array, k);\n} catch (IllegalArgumentException e) {\n    // handle invalid k or empty array\n}","preventionTips":["Always check 1 <= k <= array.length before calling.","Handle empty arrays explicitly before any k-based selection.","Clamp k from user input to valid bounds."],"tags":["math","quickselect","array","argument-validation"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}