C++ | Java | 0ms |  O(n) Time  Complexity | 100% | Simple solution | easy understanding |
Pls upvote(\uD83E\uDD7A\uD83D\uDE48\uD83D\uDE0C). If you found it useful,\nplease comment for any doubts, will be happy to reply\n\nLanguages : C++, Java\n\nSol
Pls upvote(\uD83E\uDD7A\uD83D\uDE48\uD83D\uDE0C). If you found it useful,\nplease comment for any doubts, will be happy to reply\n\nLanguages : C++, Java\n\nSolution : \nFor generating unique difference between subsequent elements we have to generate elements in a zig zag manner\n\nfor n = 6  -> 1, 6, 2, 5, 3, 4 \n\nNo we want only k < n unique difference between subsequent elements.\nFor this we generate same difference between subsqeuent elements n - k times and then generate k unique difference between subsequent elements from there on.\n\nSee the comments\nC++\n```\nclass Solution {\npublic:\n    vector<int> constructArray(int n, int k) {\n        int diff = n - k;\n        int lo = 1;\n        int hi = n;\n        vector<int> out;\n        int i = 0; \n\t\t// we generate a difference of 1 between subsequent elements for the first n-k times.\n        while(i < diff){\n            out.push_back(lo);\n            lo++;\n            i++;\n        }\n        bool flag = true;\n\t\t//Now we go zig zag to generate k unique differences, the last one will be automatically taken care\n\t\t//as the difference between last two elements will be one which we have already generated above.\n        for(int i = out.size()   ; i < n ; i++){\n           //flag to alternatively zig zag\n\t\t   if(flag){\n                out.push_back(hi);\n                hi--;\n                flag = false;\n            }\n            else{\n                out.push_back(lo);\n                lo++;\n                flag = true;\n            }\n        }\n        return out;\n    }\n};\n```\n\nJava\n\n```\nclass Solution {\n    public int[] constructArray(int n, int k) {\n        int diff = n - k;\n        int lo = 1;\n        int hi = n;\n        int[] out = new int[n];\n        int i = 0; \n\t\t// we generate a difference of 1 between subsequent elements for the first n-k times.\n        while(i < diff){\n            out[i] = lo;\n            lo++;\n            i++;\n        }\n        boolean flag = true;\n\t\t//Now we go zig zag to generate k unique differences, the last one will be automatically taken care\n\t\t//as the difference between last two elements will be one which we have already generated above.\n        for( ; i < n ; i++){\n\t\t\t//flag to alternatively zig zag\n            if(flag){\n                out[i] = hi;\n                hi--;\n                flag = false;\n            }\n            else{\n                out[i] = lo;\n                lo++;\n                flag = true;\n            }\n        }\n        return out;\n    }\n}\n```\n\n
['C', 'C++', 'Java']