Find the nearest smaller numbers on left side in an array in O(n)

Input:  arr[] = {1, 6, 4, 10, 2, 5}
Output:         {_, 1, 1,  4, 1, 2}
First element (‘1’) has no element on left side. For 6,
there is only one smaller element on left side ‘1’.
For 10, there are three smaller elements on left side (1,
6 and 4), nearest among the three elements is 4.

Input: arr[] = {1, 3, 0, 2, 5}
Output:        {_, 1, _, 0, 2}

 

class NearestSmallerNumer
{
static void Main(string[] args)
{
int[] arr = new int[] { 1, 6, 4, 10, 2, 5 };
Stack<int> st = new Stack<int>();
for (int i = 0; i < arr.Length; ++i)
{
while (st.Count() > 0 && arr[i] <= st.Peek())
{
st.Pop();
}

if (st.Count() == 0)
{
Console.Write(“_,”);
}
else
{
Console.Write(st.Peek().ToString() + “,”);
}

st.Push(arr[i]);
}
Console.ReadKey();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s