
Sponsored
Sponsored
This approach involves extending the Array prototype such that a method last() can be directly called on any array instance. If the array is empty, it should return -1; otherwise, it should return the last element of the array.
Time complexity is O(1) as accessing an array element by index is constant time. Space complexity is O(1) as no extra space is used.
1Array.prototype.last = function() {
2 return thisIn JavaScript, we can directly augment the Array.prototype to add a new method last(). This method checks if the array is empty and returns -1 if true, otherwise it returns the last element using this[this.length - 1].
This approach involves creating a separate utility function that operates on arrays to return the last element or -1 if the array is empty. This is useful where extending native objects is not recommended or possible.
Time complexity is O(1) since accessing the last element by index is constant time. Space complexity is O(1) as no additional space is needed.
1#include <stdbool.h>
2#include <stdio.h>
3
4int lastElement(int arr[], int length) {
5 return length == 0 ? -1 : arr[length - 1];
6}
7
8int main() {
9 int nums[] = {0, 2, 9};
10 int length = sizeof(nums)/sizeof(nums[0]);
11 printf("%d", lastElement(nums, length));
12 return 0;
13}In C, we write a utility function lastElement that takes an array and its length as arguments. It returns -1 if the length is zero, otherwise, it returns the last element using arr[length - 1]. This approach avoids trying to augment the C array prototype, which is not possible in C.