From fb0ec059baa107880cb396ef2cc70f5c9758ed84 Mon Sep 17 00:00:00 2001 From: Raunak Raj Date: Sun, 8 Oct 2023 12:30:35 +0530 Subject: [PATCH] Good question to practice --- .../New Approach/Solution.java | 23 +++++++++++++++++++ .../New Approach/sol.md | 16 +++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 Medium/34. First and Last Position of Element in an Array/New Approach/Solution.java create mode 100644 Medium/34. First and Last Position of Element in an Array/New Approach/sol.md diff --git a/Medium/34. First and Last Position of Element in an Array/New Approach/Solution.java b/Medium/34. First and Last Position of Element in an Array/New Approach/Solution.java new file mode 100644 index 0000000..569faef --- /dev/null +++ b/Medium/34. First and Last Position of Element in an Array/New Approach/Solution.java @@ -0,0 +1,23 @@ +public class Solution { + public int[] searchRange(int[] nums, int target) { + + int n=nums.length; + int arr[] =new int[2]; + int arr1[] =new int[]{-1,-1}; + arr[0] = -1; arr[1] = -1; + for (int i = 0; i < n; i++) { + if (target != nums[i]) + continue; + if (arr[0] == -1) + arr[0] = i; + arr[1] = i; + } + if (arr[0] != -1) { + return arr; + + } + else + return arr1; + } + +} diff --git a/Medium/34. First and Last Position of Element in an Array/New Approach/sol.md b/Medium/34. First and Last Position of Element in an Array/New Approach/sol.md new file mode 100644 index 0000000..e72915e --- /dev/null +++ b/Medium/34. First and Last Position of Element in an Array/New Approach/sol.md @@ -0,0 +1,16 @@ +### `searchRange` Function Explanation + +1. Get the length of the input array `nums`. +2. Initialize an array to store the search range. +3. Initialize an array with [-1, -1] (default return value). +4. Initialize the start index of the search range as -1. +5. Initialize the end index of the search range as -1. +6. Start iterating through the input array. +7. If the current element is not the target, continue to the next element. +8. If the current element is not the target, continue to the next iteration. +9. If the start index of the search range is -1, set it to the current index. +10. Update the end index of the search range to the current index when a match is found. +11. If the start index is not -1, return the search range. +12. Return the search range containing the start and end indices of the target. +13. If no match was found, return the default [-1, -1] array. +14. Return the default search range [-1, -1] to indicate no match. \ No newline at end of file