703213. Find element at a given Index
Basic
Find Element at a Given Index
Summary
Given an array and an index, write a program to find and print the element at that specific index. This problem involves basic array manipulation and indexing concepts.
Detailed Explanation
To solve this problem, we can use a simple loop that iterates through the array until it reaches the desired index. We then return the value at that index.
Here's the step-by-step breakdown:
- Initialize a variable
indexto the given index. - Loop through the array starting from the first element (assuming 0-based indexing).
- Inside the loop, check if the current index is equal to the target index.
- If it matches, return the value at that index.
- If not, increment the index and continue looping until the end of the array or the target index is found.
Here's a pseudocode representation:
function findElement(arr, index) {
for (int i = 0; i < arr.length; i++) {
if (i == index) {
return arr[i];
}
}
// If we reach here, the element was not found
return -1; // or throw an exception
}
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only use a few extra variables.
Optimized Solutions
Java
public class Main {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5};
System.out.println(findElement(arr, 2)); // Output: 3
}
public static int findElement(int arr[], int index) {
if (index < 0 || index >= arr.length) {
return -1; // or throw an exception
}
return arr[index];
}
}