From 407f463ce9006434ad9fd1386ee6d938b61c7cdf Mon Sep 17 00:00:00 2001 From: aakashdeshamne <21512493.dypit@dypvp.edu.in> Date: Tue, 10 Oct 2023 23:01:24 +0530 Subject: [PATCH] Added solution file in c++ and python --- .../sol.cpp | 25 +++++++++++++++++++ .../sol.py | 16 ++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 Hard/34. Find First and Last Position of Element in Sorted Array/sol.cpp create mode 100644 Hard/34. Find First and Last Position of Element in Sorted Array/sol.py diff --git a/Hard/34. Find First and Last Position of Element in Sorted Array/sol.cpp b/Hard/34. Find First and Last Position of Element in Sorted Array/sol.cpp new file mode 100644 index 0000000..5f4cdfe --- /dev/null +++ b/Hard/34. Find First and Last Position of Element in Sorted Array/sol.cpp @@ -0,0 +1,25 @@ +#include + +class Solution { +public: + std::vector searchRange(std::vector& N, int T) { + int Tleft = find(T, N, 0); + if (Tleft == N.size() || N[Tleft] != T) { + return {-1, -1}; + } + return {Tleft, find(T + 1, N, Tleft) - 1}; + } + + int find(int target, std::vector& arr, int left) { + int right = arr.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return left; + } +}; diff --git a/Hard/34. Find First and Last Position of Element in Sorted Array/sol.py b/Hard/34. Find First and Last Position of Element in Sorted Array/sol.py new file mode 100644 index 0000000..93c264a --- /dev/null +++ b/Hard/34. Find First and Last Position of Element in Sorted Array/sol.py @@ -0,0 +1,16 @@ +class Solution: + def searchRange(self, N, T): + Tleft = self.find(T, N, 0) + if Tleft == len(N) or N[Tleft] != T: + return [-1, -1] + return [Tleft, self.find(T + 1, N, Tleft) - 1] + + def find(self, target, arr, left): + right = len(arr) - 1 + while left <= right: + mid = (left + right) // 2 + if arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return left