You are on page 1of 3

Day 1 Assignment of Data structure

Problem 1: Implement next permutation, which rearranges numbers into


the lexicographically next greater permutation of numbers.If such
arrangement is not possible, it must rearrange it as the lowest possible
order (ie, sorted in ascending order). The replacement must be in-place
and use only constant extra memory. Here are some examples. Inputs are
in the left-hand column and its corresponding outputs are in the righthand
column.

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

Solution—

public class Solution {

public void nextPermutation(int[] nums) {

int i = nums.length - 2;

while (i >= 0 && nums[i + 1] <= nums[i]) {

i--;

if (i >= 0) {

int j = nums.length - 1;

while (j >= 0 && nums[j] <= nums[i]) {

j--;

swap(nums, i, j);

reverse(nums, i + 1);

private void reverse(int[] nums, int start) {

int i = start, j = nums.length - 1;

while (i < j) {

swap(nums, i, j);

i++;
j--;

private void swap(int[] nums, int i, int j) {

int temp = nums[i];

Problem 2: Given a matrix of m x n elements (m rows, n columns), return all elements of


the matrix in spiral order.
Example 1: Input:
[ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]
Output:
[1,2,3,6,9,8,7,4,5]

Solution---
class Solution {

public List<Integer> spiralOrder(int[][] matrix) {

List ans = new ArrayList();

if (matrix.length == 0) return ans;

int R = matrix.length, C = matrix[0].length;

boolean[][] seen = new boolean[R][C];

int[] dr = {0, 1, 0, -1};

int[] dc = {1, 0, -1, 0};

int r = 0, c = 0, di = 0;

for (int i = 0; i < R * C; i++) {

ans.add(matrix[r][c]);

seen[r][c] = true;

int cr = r + dr[di];
int cc = c + dc[di];

if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]){

r = cr;

c = cc;

} else {

di = (di + 1) % 4;

r += dr[di];

c += dc[di];

return ans;

Submitted By----
Anmol Chauhan
17SCSE101411

You might also like