Monday, 7 May 2018

Given an array arr[], find the maximum j – i such that arr[j] > arr[i]




package test;

class FindMaximum
{
    /* Utility Functions to get max and minimum of two integers */
    int max(int x, int y) 
    {
        return x > y ? x : y;
    }

    int min(int x, int y) 
    {
        return x < y ? x : y;
    }

    /* For a given array arr[], returns the maximum j-i such that
       arr[j] > arr[i] */
    int maxIndexDiff(int arr[], int n) 
    {
        int maxDiff;
        int i, j;

        int RMax[] = new int[n];
        int LMin[] = new int[n];

        /* Construct LMin[] such that LMin[i] stores the minimum value
           from (arr[0], arr[1], ... arr[i]) */
        LMin[0] = arr[0];
        for (i = 1; i < n; ++i)
            LMin[i] = min(arr[i], LMin[i - 1]);

        /* Construct RMax[] such that RMax[j] stores the maximum value
           from (arr[j], arr[j+1], ..arr[n-1]) */
        RMax[n - 1] = arr[n - 1];
        for (j = n - 2; j >= 0; --j)
            RMax[j] = max(arr[j], RMax[j + 1]);

        /* Traverse both arrays from left to right to find optimum j - i
           This process is similar to merge() of MergeSort */
        i = 0; j = 0; maxDiff = -1;
        while (j < n && i < n) 
        {
            if (LMin[i] < RMax[j]) 
            {
                maxDiff = max(maxDiff, j - i);
                j = j + 1;
            } 
            else
                i = i + 1;
        }

        return maxDiff;
    }
    
    int maxIndexDiff1(int a[] , int n)
    {
     
    int i=0,j=n-1;
    while(i<=j)
    {
     
     
    if(a[j]>a[i])
    {
     
    return j-i;
    }
     
    if(a[j-1]>a[i])
     j--;
    else if(a[i+1]<a[j])
     i++;
    else
    {
    i++;
    j--;
    }
     
    }
     
    return -1;
     
     
    }

    /* Driver program to test the above functions */
    public static void main(String[] args) 
    {
        FindMaximum max = new FindMaximum();
        int arr[] = {6, 5, 4, 3, 2, 1};
        int n = arr.length;
        int maxDiff = max.maxIndexDiff(arr, n);
        int maxDiff1 = max.maxIndexDiff1(arr, n);
maxIndexDiff1 wont work for below two arrays.

{10,11,12,13,14,6,9,7,5,3} : expected: 4, given -1 
{6,9,7,5,3} :  expected 2, given -1
        System.out.println(n + " " + maxDiff + " " +maxDiff1);
    }
}

Tuesday, 30 January 2018

Code for remote debug

-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=7000,suspend=n

insert script for NT_Property table for R2R

Insert into nt_property (NAME,VALUE,NOTE) values ('nextLongId','8005149766','next starting id for this database owner');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextId','108218669','next starting id for this database owner');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxLongId','9999999999','the max id');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxId','0','the max id');
Insert into nt_property (NAME,VALUE,NOTE) values ('idManager',null,'IdManager for this RMOB schema.');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextNodePvid','521732848','next starting id for NODE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxNodePvid','2000000000','max id for NODE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextLinkPvid','521736970','next starting id for LINK PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxLinkPvid','2000000000','max id for LINK PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextFacePvid','521727318','next starting id for FACE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxFacePvid','2000000000','max id for FACE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextRoadLinkPvid','521755019','next starting id for ROAD_LINK PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxRoadLinkPvid','2000000000','max id for ROAD_LINK PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextCartoPvid','521727314','next starting id for CARTO PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxCartoPvid','2000000000','max id for CARTO PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextNamedPlacePvid','521727290','next starting id for NAMED_PLACE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxNamedPlacePvid','2000000000','max id for NAMED_PLACE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextMultiNavPvid','521727286','next starting id for MULTI_NAV PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxMultiNavPvid','2000000000','max id for MULTI_NAV PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextPoiPvid','521727331','next starting id for POI PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxPoiPvid','2000000000','max id for POI PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextAssocPvid','521727286','next starting id for ASSOC PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxAssocPvid','2000000000','max id for ASSOC PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextNamePvid','521727561','next starting id for NAME PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxNamePvid','2000000000','max id for NAME PVIDS ');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextValuePvid','521727286','next starting id for VALUE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxValuePvid','2000000000','max id for VALUE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextRoadPointPvid','521727286','next starting id for ROADPOINT PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxRoadPointPvid','2000000000','max id for ROADPOINT PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitCompanyPvid','521727286','next starting id for TRANSIT COMPANY PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitCompanyPvid','2000000000','max id for TRANSIT COMPANY PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitSystemPvid','521727286','next starting id for TRANSIT SYSTEM PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitSystemPvid','2000000000','max id for TRANSIT SYSTEM PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitLinePvid','521727286','next starting id for TRANSIT LINE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitLinePvid','2000000000','max id for TRANSIT LINE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitStopPvid','521727286','next starting id for TRANSIT STOP PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitStopPvid','2000000000','max id for TRANSIT STOP PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitPlatformPvid','521727286','next starting id for TRANSIT PLATFORM PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitPlatformPvid','2000000000','max id for TRANSIT PLATFORM PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitStrandPvid','521727286','next starting id for TRANSIT STRAND PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitStrandPvid','2000000000','max id for TRANSIT STRAND PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitAccessPvid','521727286','next starting id for TRANSIT ACCESS PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitAccessPvid','2000000000','max id for TRANSIT ACCESS PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitTransferPvid','521727286','next starting id for TRANSIT TRANSFER PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitTransferPvid','2000000000','max id for TRANSIT TRANSFER PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitGuidancePvid','521727286','next starting id for TRANSIT GUIDANCE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitGuidancePvid','2000000000','max id for TRANSIT GUIDANCE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitSegmentPvid','521727286','next starting id for TRANSIT SEGMENT PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitSegmentPvid','2000000000','max id for TRANSIT SEGMENT PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTransitStopAreaPvid','521727286','next starting id for TRANSIT STOP AREA PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTransitStopAreaPvid','2000000000','max id for TRANSIT STOP AREA PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextFeaturePointPvid','521727286','next starting id for FEATURE POINT PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxFeaturePointPvid','2000000000','max id for FEATURE POINT PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextMapObjectAssocPvid','521727286','next starting id for MAP OBJECT ASSOCIATION PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxMapObjectAssocPvid','2000000000','max id for MAP OBJECT ASSOCIATION PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextNavLanePvid','521727286','next starting id for NAVLANE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxNavLanePvid','2000000000','max id for NAVLANE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextLaneStrandPvid','521727286','next starting id for NAVLANE PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxLaneStrandPvid','2000000000','max id for LANESTRAND PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextTopologySegmentPvid','521727286','next starting id for Topology Segment PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxTopologySegmentPvid','2000000000','max id for Topology Segment PVIDS');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextVariableSpeedSignId','51001','next starting id for VARIABLE SPEED SIGN ID');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxVariableSpeedSignId','9999999999','max id for VARIABLE SPEED SIGN ID');
Insert into nt_property (NAME,VALUE,NOTE) values ('nextMetadataId','8999000000','next starting id for metadata');
Insert into nt_property (NAME,VALUE,NOTE) values ('maxMetadataId','2000000000','max id for metadata');
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalNamedPlacePvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalNodePvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalLinkPvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalAssocPvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalPoiPvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalRoadLinkPvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalRoadPointPvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalValuePvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalCartoPvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalFacePvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalMultiNavPvid','5861800',null);
Insert into nt_property (NAME,VALUE,NOTE) values ('lastGlobalNamePvid','5861800',null);
commit;

Wednesday, 25 October 2017

Motivational Words !!!

Without any sugar coating I will speak truth and plain. Yes it is difficult to crack civil services in the first attempt.
Everyone around us has two cents of wisdom to lend on civil services. Be it our friends, neighbours, a far flung distant relative who tried his hands on UPSC once, an unknown accidentally encountered on a road , for that matter anyone or everyone will keep littering in our ears once they know you are an aspirant.
When I started preparation I had totally wrong perception of civil services preparation. I felt it needs rigorous efforts like studying 12-14 hours a day, it will take years of preparation, I need to study lot of books, only few lucky people make through the exam and plethora of such misconceptions imbibed in my mind mainly due to those so called two cents of wisdom heard from people who themselves had no idea what UPSC is all about.
And the outcome was as expected I had a very confusing start, half hearted effort with a already inbuilt perception that failure is bound to happen. And the result was I even failed to clear prelims in my first attempt.
The point I am trying to make is simple. It is so difficult to clear in 1st attempt not because we lack capabilities or because exam is too difficult to clear in first attempt. It is mainly because of lack of proper guidance and direction to our preparation. It is due to lack of planning, strategy and consistency. It is due to lack of self confidence.. Most of us fall flat on our feet and then learn the right way and slowly and steadily make our way. On the other hand people who already come enlightened find it easy to sail through and make it in their maiden attempt.
So point is simple, if you really want to clear civil services you need to overcome the above mentioned weaknesses. For that some essential things to do include.
Clarity of goal – First be clear why do you want to be a civil servant, clear motive is very important if you want to succeed. The will to win, the desire to succeed, the urge to reach your full potential. these are the keys that will unlock the door to personal excellence. And this will happen when you know what you want and why.

Self Confidence: It is the common people who do the uncommon things when they repose a leap of faith in themselves. UPSC is no rocket science, trust me all toppers had same butterflies in their stomach when they were aspirants. What made them successful is that they held their nerves tight and believed in themselves. Always be yourself, express yourself, have faith in yourself, do not go out and look for a successful personality and duplicate it. Each one of us has our own story and we craft it with our own hands. You just need to believe that your’s is going to be a beautiful one .
Consistency and persistence for goal - Desire is the key to motivation, but it's determination and commitment to an unrelenting pursuit of your goal - a commitment to excellence - that will enable you to attain the success you seek. Keeping that in mind remember each day is new , you need to have goals and targets for each day. Its important to wake up with a clear purpose and sleep with a dream that aspires towards goal attainment.
These are the common yardsticks to ensure success in first attempt. Apart from it is important to do the following things:-
1. Having clarity about Civil services examination: what is the syllabus, is coaching needed, which optional to chose, what UPSC needs etc . I have made a small video that might help in this.
2. Understand UPSC preparation process – Booklist, timelines, how to write answers, make notes, read newspaper, how to cover books etc. UnAcademy, Insights, Mrunal will help here. Also I have written one article that will help. Link: Chandra Mohan Garg's answer to What is best way to crack the Civil Services Exam?
3. Make your plan– make your own plans – how to prepare for prelims, how to cover subjects, how to get myself evaluated, how to revise, how much time needed , daily targets , weekly targets etc.
For a fact let me tell you, it is half our fear and half our lack of understanding of what UPSC demands that make us fall in our first attempt. Just be aware, be planned and prepared and be confident .You will surely succeed and achieve what you wanted even in your first attempt.
Someone beautifully said that Success or failure depends more upon attitude than upon capacity. Successful men act as though they have accomplished or are enjoying something. Soon it becomes a reality. Act, look, feel successful, conduct yourself accordingly, and you will be amazed at the positive results.

Sunday, 27 December 2015

When to use SOAP instead of REST

With SOAP you have a contract between the two parties.
With REST you'll have to implement such contract yourself in your code.
For me SOAP is like a strongly typed language. REST is like PHP : quick to get something going.
As for performance related to the size of the message that needs to be transported: People often assume that with SOAP huge amounts of very verbose XML needs to be transported. Technically this is true but in modern days the two endpoints will most likely use gzip compression and/or FastInfoset. This greatly reduces the size of the message, possibly to the size of compressed JSON. However some people argue that JSON is still somewhat faster to parse than is XML. This is possibly true but I believe the difference in parsing speed for most use cases is negligible. I've also seen tests where FastInfoset parsing outperforms JSON parsing. All in all arguments need to be reviewed in the light of the current state of affairs, not the way the world looked in 2005.
I recently had to implement a web service where the request could become very large (several megabytes) and the reply even bigger. This works well with SOAP. Contrary with REST the conceptual idea is that you embed the request as part of URL and such approach of course only works for very small amount of request data. REST camp will say that you have two choices: (1) You embed your large data in a the body of a POST request but this is not really a 'true' REST way of doing things or you (2) change your design so that you send many questions rather than a single big question but such solution will of course create a lot more network overhead because of the roundtrip.
I stayed with SOAP for this particular service.
REST is fine and possibly the optimal choice for most scenarios but there are certainly cases where SOAP is a better fit, IMHO.



One of the major benefits of SOAP is that you have a WSDL service description. You can pretty much discover the service automatically and generate a useable client proxy from that service description (generate the service calls, the necessary data types for the methods and so forth). Note that with version 2.0, WSDL supports all HTTP verbs and can be used to document RESTful services as well, but there is a less verbose alternative in WADL (Web Application Description Language) for that purpose.
With RESTful services, message security is provided by the transport protocol (HTTPS), and is point-to-point only. It doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
One of the major benefits of RESTful API is that it is flexible for data representation, for example you could serialize your data in either XML or JSON format. RESTful APIs are cleaner or easier to understand because they add an element of using standardised URIs and gives importance to HTTP verb used (i.e. GET, POST, PUT and DELETE).
RESTful services are also lightweight, that is they don’t have a lot of extra xml markup. To invoke RESTful API all you need is a browser or HTTP stack and pretty much every device or machine connected to a network has that.

Tuesday, 22 September 2015

Find Longest common Sub-sequence in two strings in O(n) time


public class DebugTest {
public static void main(String[] args) {
char X[] = "AGGTAB".toCharArray();
char Y[] = "GXTXAYB".toCharArray();
System.out.println(findLCS_dp1(X, Y));
X = "XMJYAUZ".toCharArray();
Y = "MZJAWXU".toCharArray();
System.out.println(findLCS_dp1(X, Y));
}
public static int findLCS_dp1(char[] a, char[] b){
int m = b.length;
int n= a.length;
int[] lcs = new int[n+1];
for(int i=1;i<=n;i++){
int prevMatchedValueAtIndexJ = lcs[0];
for(int j=1; j<=m; j++){
int temp = lcs[j] ;
if(a[i-1] == b[j-1])
lcs[j] = 1 + prevMatchedValueAtIndexJ;
else
lcs[j] = Math.max(lcs[j-1], lcs[j]);
prevMatchedValueAtIndexJ = temp;
}
}
return lcs[m];
}
}

Saturday, 1 November 2014

Transpose, Rotate by +90, Rotate by -90 a matrix.

#include <stdio.h>
#include <stdlib.h>

void displayMatrix(unsigned int const *p, unsigned int row, unsigned int col);
void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col);

int main()
{
    // declarations
    unsigned int image[][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
    unsigned int *pSource;
    unsigned int *pDestination;
    unsigned int m, n;

    // setting initial values and memory allocation
    m = 3, n = 4, pSource = (unsigned int *)image;
    pDestination = (unsigned int *)malloc(sizeof(int)*m*n);

    // process each buffer
    displayMatrix(pSource, m, n);

    rotate(pSource, pDestination, m, n);

    displayMatrix(pDestination, n, m);

    free(pDestination);

    getchar();
    return 0;
}

void displayMatrix(unsigned int const *p, unsigned int r, unsigned int c)
{
    unsigned int row, col;
    printf("\n\n");

    for(row = 0; row < r; row++)
    {
        for(col = 0; col < c; col++)
        {
            printf("%d\t", *(p + row * c + col));
        }
        printf("\n");
    }

    printf("\n\n");
}

void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col)
{
    unsigned int r, c;
    for(r = 0; r < row; r++)
    {
        for(c = 0; c < col; c++)
        {
            //*(pD + (col-c-1)*row + r) = *(pS + r * col + c);    //rotate by -90
     
          // *(pD + c*row+ (row-r-1)) = *(pS + r * col + c);   //rotate by +90
       
          *(pD + c*row+ r) = *(pS + r * col + c);                  //transpose
        }
    }
}