Reverse a Linked List

Given a singly linked list, write a code to reverse a linked list. In this tutorial, you are going to learn how to reverse a linked list in java using iterative approach.

For example –

Input linked list.

15 -> 9 -> 8 -> 5 -> NULL

When we reverse this linked list then the output is given below.

5 -> 8 -> 9 -> 15 -> NULL

In input linked list, head points to a node whose value is 15 but when it’s reversed the head points to a node whose value is 5.

Maximum Sum Subarray of Size K

Let’s discuss a interesting problem maximum sum subarray of size k

Given an array of positive integers and a positive number K. Write a code to find the maximum sum subarray of size k.

For example:

Let’s first understand what all subarrays we can form whose size is 3.

i) First subarray is {2, 1, 5} and it’s sum is 8.

ii) Second subarray is {1, 5, 1} and it’s sum is 7.

iii) Third subarray is {5, 1,3} and it’s sum is 9.

iv) Fourth subarray is {1, 3, 2} and it’s sum is 6.

Out of all these subarrays of size three, the maximum sum subarray is {5, 1, 3} and it’s sum is 9.

Find Peak Element in Array

Given an array of integers, write a code to find peak element in array. The array may contain multiple peak elements, in that case, return anyone peak element.

Peak Element

Peak element is an element which greater than it’s neighbours. For strictly decreasing array, the first element is the peak element. And for strictly increasing array the last element is the peak element.

For example:

Example 1:

Input: {2, 3, 4, 7, 5} , Output: 7

The element 7 is greater than it’s neighbours (4 and 5).

Example 2:

Input: {8, 7, 6, 5, 4}, Output: 8

In this example, An array is strictly decreasing, so the first element is the peak element.

Example 3:

Input: {2, 3, 4, 5, 6}, Output: 6

An array is strictly increasing, so the last element is the peak element.

Example 4:

Input: {2, 2, 2, 2, 2}, Output: 2

All the array element is the same, So every element in this array is the peak element.